<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Cookie;
use App\Http\Page;
use App\Http\Controllers\PermController;
use Illuminate\Support\Facades\Redis;
use App\Http\Error;
use Excel;
use App\Model\OrderModel;
use App\Model\UserMainModel;
use App\Model\OrderActionLogModel;
use App\Model\OrderReturnModel;
use App\Model\OrderItemsTrackModel;
use Session;
use Hprose\Http\Client;

// 获取订单优惠券金额
function getCoupon($order_id)
{
    $price = DB::connection('order')
            ->table('lie_order_price')
            ->where(['order_id' => $order_id, 'price_type' => -4])
            ->first();

    if (!$price) return null;

    return $price->price;
}

// 获取会员账号
function getAccountName($user_id)
{
    if (!$user_id) return false;

    $userMainModel = new UserMainModel();
    $user = $userMainModel->where('user_id', $user_id)->select('mobile', 'email')->first();

    if (!$user) return false;

    return $user->mobile ? $user->mobile : $user->email;
}

// 获取支付名称
function getPayName($order_id) 
{
    $payLog = DB::connection('order')
            ->table('lie_pay_log')
            ->where(['order_id' => $order_id])
            ->select('pay_name')
            ->get();

    if (!$payLog) return false;

    foreach ($payLog as $v) {
        $payName[] = $v->pay_name; 
    }

    return implode(',', $payName);
}

function getShipping($order_id, $shipping_type=1) 
{
    $shipping = DB::connection('order')
                ->table('lie_order_shipping')
                ->where(['order_id' => $order_id, 'shipping_type' => $shipping_type])
                ->select('shipping_no', 'status')
                ->orderBy('order_shipping_id')
                ->get();

    if (!$shipping) return false;

    return $shipping;
}

function getInvoiceStatus($order_id) 
{
    $invoice = DB::connection('order')
                ->table('lie_order_invoice')
                ->where(['order_id' => $order_id])
                ->select('invoice_status')
                ->first();

    if (!$invoice) return false;

    return $invoice->invoice_status;
}

// 发票抬头 -> 公司
function getCompanyName($order_id, $user_id) 
{
    $order_invoice = DB::connection('order')->table('lie_order_invoice')->where(['order_id'=>$order_id])->select('tax_title', 'inv_type')->first();

    if ($order_invoice && $order_invoice->inv_type != 1) return $order_invoice->tax_title;

    $company = DB::connection('order')->table('lie_user_company')->where(['user_id' => $user_id])->select('com_name')->first();

    if (!$company) return false;

    return $company->com_name;
}

// 获取操作人名称
function getOperatorName($uid, $type)
{
    $name = '';

    if ($type == 1) {
        // $user = DB::connection('order')->table('lie_user_main')->where('user_id', $uid)->select('user_name')->first();
        // $name = !empty($user->user_name) ? $user->user_name : '客户';
        $name = '客户';
    } else if ($type == 2)  {
        $user = DB::table('user_info')->where('userId', $uid)->select('name')->first();
        $name = isset($user->name) ? $user->name : '未知';
    } else if ($type == 3) {
        $name = '系统定时任务';
    } else if ($type == 4) {
        $name = 'ERP';
    } else if ($type == 5) {
        $name = 'WMS';
    }

    return $name;
}

// 获取交易员名称
function getSalesName($sale_id)
{
    if (!$sale_id) return false;

    $user = DB::table('user_info')->where('userId', $sale_id)->select('name')->first();

    return isset($user) ? $user->name : '';
}

// 判断用户是否为新用户 -- 第一次下单
function isNewClient($order_goods_type, $user_id, $create_time)
{
    // $half_year_time = intval($create_time - round(365 / 2) * 86400);   

    // $order = DB::connection('order')->table('lie_order')->where('order_goods_type', $order_goods_type)->where('user_id', $user_id)->whereBetween('create_time', [$half_year_time, $create_time-1])->get();

    $user = DB::connection('order')->table('lie_user_main')->where('user_id', $user_id)->first();

    // return empty($order) && empty($user->client_source) ? true : false;
    return $user && $user->is_new == 0 && empty($user->client_source) ? true : false;
}

// 用户来源
function clientSource($user_id)
{
    if (!$user_id) return false;

    $user = DB::connection('order')->table('lie_user_main')->where('user_id', $user_id)->select('client_source')->first();

    return $user ? $user->client_source : '';
}

// 获取自营商品型号
function getGoodsName($goods_id)
{
    $goods_info = json_decode(Redis::hget('Self_SelfGoods', $goods_id), true);
    
    return $goods_info ? $goods_info['goods_name'] : '';
}

// 获取订单来源
function getOrderSource($order_id, $order_type=1)
{
    if ($order_type == 1) {
        $order = DB::connection('order')->table('lie_order_extend')->where('order_id', $order_id)->select('order_type')->first();

        if ($order) {
            switch ($order->order_type) {
                case 1: 
                case 2: 
                case 3: 
                    return '后台';               
            }
        }

        $order_source = DB::connection('order')->table('lie_order')->where('order_id', $order_id)->select('order_source')->first();

        if (preg_match('/pf=1/', $order_source->order_source)) {
            $source = 'PC端';
        } else if (preg_match('/pf=2/', $order_source->order_source)) {
            $source = '移动端';
        } else if (preg_match('/pf=6/', $order_source->order_source)) {
            $source = '小程序';
        } else {
            $source = '未知';
        }

        return $source;
    } else if ($order_type == 2) {
        return 'ERP';
    } else if ($order_type == 3) {
        return '京东';
    } else if ($order_type == 4) {
        return '象牙宝';
    }

    return false;
}

// 过滤来源字段
function handleOrderSource($order_source)
{
    if (!$order_source) return false;

    $source = explode(',', $order_source);

    foreach ($source as $k => $v) {
        if (!preg_match('/^(pf=|k=|adtag=|ptag=)/', $v)) {
            unset($source[$k]);
        }
    }

    return implode(',', $source);
}

// 获取订单收货人
function getOrderAddress($order_id)
{
    $order = DB::connection('order')->table('lie_order_address')->where('order_id', $order_id)->select('consignee')->first();

    if (!$order) return false;

    return $order->consignee;
}

// 获取渠道名称
function getSupplierName($key)
{
    $redis = Redis::connection('read');
    $supp_info = $redis->hget('supp_info_', $key);

    return $supp_info;
}

// 获取自营库存
function getSelfStock($goods_id)
{
    if (!$goods_id) return '商品ID不存在';

    $url = Config('website.self-stock-url');
    $data['sku_id'] = $goods_id;
    
    $response = json_decode(curlApi($url, $data, 'POST'), true); 

    if ($response['errcode'] == 0) {
        return isset($response['data'][$goods_id]['stock']) ? $response['data'][$goods_id]['stock'] : 0;
    } else {
        return '未找SKU信息';
    }
}

// 调用财务系统接口判断是否能修改发票
function isChangeInvoice($order_sn)
{
    $url = Config('website.finance-self-invoice-url');
    $data['order_sn'] = $order_sn;

    $res = json_decode(curlApi($url, $data, 'POST'), true); 

    if ($res['err_code'] == 0) {
        return true;
    } else {
        return false;
    }
}

// 订单扩展表
function getOrderExtend($order_id, $field="*", $where=array())
{
    $map['order_id'] = $order_id;

    if (!empty($where)) {
        $map = array_merge($map, $where);
    }

    $extend = DB::connection('order')->table('lie_order_extend')->where($map)->select($field)->first();

    return $extend;
}

// 获取订单跟踪
function getLastTrack($rec_id)
{
    $OrderItemsTrackModel = new OrderItemsTrackModel;
    $track = $OrderItemsTrackModel->getLastItemTrack($rec_id);

    if (!$track) return false;

    return $track['track_content'].',数量:'.$track['track_num'];
}

Class OrderController extends Controller
{
    // 首页
    public function index(Request $request)
    {
        $uri = '/' . $request->path();

        $username = $request->user->email;
        $useremail= $request->user->email;

        // 菜单
        $menuconfig = DB::table('config')->where('config_title', '订单系统')->first();
        $menus = [];
        if ($menuconfig && !($menus = json_decode($menuconfig->config_data)))
            $menus = [];

        $perm = new PermController;

        // 用户角色
        $role = $perm->getUserRole($request);

        // 获取权限菜单
        if ($role != 1) {
            $menus = $perm->getPermMenu($menus, $request->user->userId);   
        }

        $data = [
            'header'    => $request->user->header,
            'uri'       => $uri,
            'username'  => $username,
            'useremail' => $useremail,
            'menus'     => $menus,
        ];

        return view('index', $data);
    }

    // 页面用户、菜单信息
    public function getPageInfo(Request $request)
    {
        $uri = '/' . $request->path();

        if ($request->path() == '/') $uri = '/list';           

        $username = $request->user->email;
        $useremail= $request->user->email;

        // 菜单
        $menuconfig = DB::table('config')->where('config_title', '订单系统')->first();
        $menus = [];
        if ($menuconfig && !($menus = json_decode($menuconfig->config_data)))
            $menus = [];

        $perm = new PermController;

        // 用户角色
        $role = $perm->getUserRole($request);

        // 获取权限菜单
        if ($role != 1) {
            $menus = $perm->getPermMenu($menus, $request->user->userId);   
        }

        $userPerms = $perm->getUserAllPerms($request->user->userId, $role); // 用户权限

        $data = [
            'header'    => $request->user->header,
            'uri'       => $uri,
            'username'  => $username,
            'useremail' => $useremail,
            'menus'     => $menus,
            'userPerms' => $userPerms,
            'role'      => $role,
        ];

        return $data;
    }

    // 订单列表
    public function orderList(Request $request)
    {
        $info = $this->getOrderInfo($request, 1);
        $info['title'] = '订单列表';

        // 若为京东自营、自营客服等角色,则跳转到自营列表
        if (in_array($info['role'], Config('perm_args.self_roles'))) {
            return redirect('self_order');
        }

        return view('orderlist', $info);
    }

    // 订单搜索参数
    public function _search(Request $request, $tid)
    {
        $info = $this->getPageInfo($request);

        $map = array();
        
        // 页面参数
        $map['order_type']           = $request->input('order_type', '');
        $map['order_contain']        = $request->input('order_contain', '');
        $map['order_sn']             = $request->input('order_sn', '');
        $map['erp_sn']               = $request->input('erp_sn', '');
        $map['goods_name']           = $request->input('goods_name', '');
        $map['time_start']           = $request->input('time_start', '');
        $map['time_end']             = $request->input('time_end', '');
        $map['confirm_time_start']   = $request->input('confirm_time_start', '');//开始审核时间
        $map['confirm_time_end']     = $request->input('confirm_time_end', '');//结束审核时间
        $map['pay_time_start']       = $request->input('pay_time_start', '');//收款开始时间
        $map['pay_time_end']         = $request->input('pay_time_end', '');//收款结束时间
        $map['shipping_time_start']  = $request->input('shipping_time_start', '');//发货开始时间
        $map['shipping_time_end']    = $request->input('shipping_time_end', '');//发货结束时间
        $map['finish_time_start']    = $request->input('finish_time_start', '');//订单完成开始时间
        $map['finish_time_end']      = $request->input('finish_time_end', '');//订单完成结束时间
        $map['order_status']         = $request->input('order_status', '');
        $map['sale_type']            = $request->input('sale_type', '');
        $map['shipping_name']        = $request->input('shipping_name', '');
        $map['order_send']           = $request->input('order_send', '');
        $map['test_order']           = $request->input('test_order', '');
        $map['order_pay_type']       = $request->input('order_pay_type', '');
        $map['order_type_a']         = $request->input('order_type_a', '');
        $map['order_source']         = $request->input('order_source', '');
        $map['order_source_pf']      = $request->input('order_source_pf', '');
        $map['order_source_adtag']   = $request->input('order_source_adtag', '');
        $map['order_source_ptag']    = $request->input('order_source_ptag', '');
        $map['erp_order_id']         = $request->input('erp_order_id', '');
        $map['order_payment_mode']   = $request->input('order_payment_mode', '');
        $map['order_invoice_status'] = $request->input('order_invoice_status', '');
        $map['is_new']               = $request->input('is_new', '');
        $map['is_new_order']         = $request->input('is_new_order', '');
        $map['business_type']        = $request->input('business_type', '');

        $perm = new PermController;

        $map['sale_id'] = $map['order_send'];

        // 订单查看权限
        if (strpos($info['role'], ',') !== false) { // 多角色情况下
            $res = $perm->checkUserRoles($request, $info['role']);

            $info['role'] = $res['role_id'];

            // 若无指定客服,则返回客服组里的所有订单
            if (!$map['order_send']) {
                $map['sale_id'] = $res['sale_id'];
            } else if (!in_array($map['order_send'], $res['sale_id'])) { // 若指定客服不存在与客服组,则不能筛选
                $map['sale_id'] = -1;
            } else {
                $map['sale_id'] = $map['order_send'];
            }
        } else if (in_array($info['role'], Config('perm_args.kefu_order'))) { // 交易员、联营客服(线销一组、二组、三组客服)、自营客服、自营内部采购
            $map['sale_id'] = $request->user->userId; // 筛选自己的订单
        } else if (in_array($info['role'], Config('perm_args.manager_order'))) { // 线销一组、二组、三组主管(查看自己及其下组员的订单)
            $sale_ids = $perm->getGroupSalesId($request, $info['role']);

            // 若无指定客服,则返回客服组里的所有订单
            if (!$map['order_send']) {
                $map['sale_id'] = $sale_ids;
            } else if (!in_array($map['order_send'], $sale_ids)) { // 若指定客服不存在与客服组,则不能筛选
                $map['sale_id'] = -1;
            } else {
                $map['sale_id'] = $map['order_send'];
            }
        }          

        // 自营客服权限
        if ($tid == 2 && $info['role'] == 6) {
            $map['check_jd_order'] = 1; // 只允许查看京东自营订单
        }

        // 非尽调账号显示真实数据
        if ($info['role'] != 13) {
            $map['is_fake'] = 0;
        } else {
            // $map['vp_time_set'] = strtotime(Config('website.vp_time_set')); // 竞调账号根据时间展示订单
        }

        $map['order_goods_type'] = $tid;
        $size = 10;

        if ($tid == 1) {
            $map['order_type_filter'] = in_array($info['role'], [1, 13]) ? [1, 2, 3] : [1]; // 管理员和尽调账号可以查看平台、ERP、京东订单
        } else if ($tid == 2) {
            $size = 20;
            $map['order_type_filter'] = [1, 3, 4]; // 1.网站 3.京东 4.象牙宝
        } else if ($tid == 3) {
            $map['order_goods_type'] = 1; // 联营订单
            $map['order_type_filter'] = [2, 3]; // 2-ERP, 3-JD
        }

        $info['size'] = $size;
        $info['map']  = $map;

        return $info;
    }

    // 获取页面及订单信息 tid为订单类型:1.联营, 2. 自营, 3. ERP
    public function getOrderInfo($request, $tid=1)
    {
        $info = $this->_search($request, $tid);
      
        $key       = Config('perm_args.redis_search_sales')[$tid]; 
        $redis     = Redis::connection('read');
        $sale_list = $redis->get($key);
        
        if (!$sale_list) {
             // 获取所有的业务员 (包括经理、交易员、客服、测试)
            $perm = new PermController;
            $sale_list = [];

            if ($tid == 1) {
                $search_sales = Config('perm_args.search_joint_sales');
            } else {
                $search_sales = Config('perm_args.search_self_sales');

                $sale_list[] = (object) array('userId'=>1000, 'name'=>'admin', 'status'=>0);
            }  

            if ($search_sales) {
                foreach ($search_sales as $v) {
                    $role_name = array_keys(Config('perm_args.roles'), $v);
                    $temp      = $perm->getRoleUsers($request, $role_name[0]);
                    $sale_list = array_merge($sale_list, $temp);
                }
            }

            $sale_list = $this->assoc_unique($sale_list);

            $expire = Config('perm_args.redis_search_sales_expire'); // 缓存两小时
            Redis::setex($key, $expire, json_encode($sale_list));
        } else {
            $sale_list = json_decode($sale_list);
        }

        // if ($tid == 1) {
        //     $manager   = $perm->getRoleUsers($request, '经理');
        //     $test      = $perm->getRoleUsers($request, '测试');
        //     $sales     = $perm->getRoleUsers($request, '交易员');
        //     $kefu      = $perm->getRoleUsers($request, '客服');
        //     $sale_list = array_merge($manager, $sales, $test, $kefu);
        // } else if ($tid == 2) {
        //     $manager   = $perm->getRoleUsers($request, '自营客服主管');
        //     $test      = $perm->getRoleUsers($request, '测试');
        //     $assistant = $perm->getRoleUsers($request, '自营客服主管助理');
        //     $purchase  = $perm->getRoleUsers($request, '自营内部采购');
        //     $kefu      = $perm->getRoleUsers($request, '自营客服');
        //     $sale_list = array_merge($manager, $test, $assistant, $purchase, $kefu);
        // }

        //获取订单列表
        $url = Config('website.api_domain').'order/getAllOrder';

        $data['k1']   = time();
        $data['k2']   = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['p']    = $request->input('p', 1); // 当前页码
        $data['size'] = $info['size']; // 当前页条数
        $data['map']  = $info['map'];

        $response = json_decode(curlApi($url, $data), true); 

        // 分页
        $page = new Page($response['data']['count'], $info['size']);
        $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $show = $page->show();

        $info['condition'] = $info['map']; 
        $info['sale_list'] = isset($sale_list) ? $sale_list : ''; 
        $info['list']      = $response['data']['data']; 
        $info['count']     = $response['data']['count']; 
        $info['page']      = $show; 
        $info['credit']    = isset($response['data']['credit']) ? $response['data']['credit'] : ''; // 自营判断是否为账期会员 

        return $info;
    }

    // 二维数组,针对某个键名去重
    public function assoc_unique($arr, $key='userId')
    {
        if (!$arr) return false;

        $tmp = [];

        foreach ($arr as $k=>$v) {
            if (in_array($v->$key, $tmp)) {
                unset($arr[$k]);
            } else {
                $tmp[] = $v->$key;
            }
        }

        return array_merge($arr); // 重新索引
    }

    // 订单其他信息
    public function orderOtherInfoLoading(Request $request)
    {
        $is_manager = $request->input('is_manager', 0);

        if (!$is_manager) { // 非管理账户检查查询时间
            $time_start = $request->input('time_start', '');
            $time_end   = $request->input('time_end', '');

            if ($time_start && $time_end) {
                $diff = $time_end - $time_start;

                if ($diff >= 60*60*24*365) return ['err_code'=>1, 'err_msg'=>'查询时间不能超过一年'];
            } else if ($time_end) {
                return ['err_code'=>2, 'err_msg'=>'请选择开始时间'];
            } else if ($time_start) {
                $diff = time() - $time_start;

                if ($diff >= 60*60*24*365) return ['err_code'=>1, 'err_msg'=>'查询时间不能超过一年'];
            } else {
                return ['err_code'=>3, 'err_msg'=>'请选择查询时间'];
            }
        }

        // 判断页面
        $tid = $request->input('pid', 1);
        $info = $this->_search($request, $tid);

        $url = Config('website.api_domain').'order/getOrderOtherInfo';

        $data['k1']  = time();
        $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['map'] = $info['map'];

        $response = json_decode(curlApi($url, $data), true); 
        
        return $response;
    }

    // erp订单
    public function erpOrder(Request $request)
    {
        $info = $this->getOrderInfo($request, 3);
        $info['title'] = 'ERP订单';

        return view('erpOrder', $info);
    }

    // 自营订单
    public function selfOrder(Request $request)
    {
        $info = $this->getOrderInfo($request, 2);
        $info['title'] = '自营订单';

        return view('selfOrder', $info);
    }

    // 获取对应部门人员
    public function getSales($title='') 
    {
        // 查找部门
        $department = DB::select("SELECT * FROM department WHERE parent = (SELECT departmentId FROM department WHERE title = '$title')");

        $departmentId = array();

        // 获取部门ID集合
        foreach ($department as $k => $v) {
            $departmentId[$k] = $v->departmentId;
        }

        // 获取部门人员
        $employee = DB::table('user_info as u')->leftJoin('organization as o', 'u.userId', '=', 'o.userId')->whereIn('departmentId', $departmentId)->get();

        return $employee;
    }

    // 订单导出
    public function export(Request $request)
    {
        $order_goods_type = $request->input('order_goods_type', 1);
        $info = $this->_search($request, $order_goods_type);

        if ($order_goods_type == 1) {
            $file_name       = '联营订单导出';
            $source_items_id = Config('website.export_joint_source_id');
            $headerCell      = ['订单ID', '订单编号', 'ERP单号', '京东订单号', '会员账号', '收货人', '下单日期', '下单时间', '客户名称', '平台来源', 'SKUID', '商品型号', '商品分类', '制造商', '供应商', '数量', '单价', '均摊后单价', '商品小计', '币种', '客服', '商品总额', '运费', '附加费', '优惠券', '订单总额', '人民币总额', '付款类型', '订单状态', '发货状态', '收货地址', '发票类型', '发票状态', '发票抬头', '公司注册地址', '公司电话', 'adtags来源', '新用户来源', '取消原因', '推送备注', '是否为测试订单', '是否为新订单'];
            $return_url      = '/list';
        } else {
            $file_name       = '自营订单导出';
            $source_items_id = Config('website.export_self_source_id');
            $headerCell      = ['订单ID', '订单编号', 'ERP单号', '京东订单号', '会员账号', '收货人', '下单日期', '下单时间', '客户名称', '平台来源', 'SKUID', '商品型号', '商品分类', '制造商', '供应商', '数量', '单价', '均摊后单价', '商品小计', '币种', '客服', '商品总额', '运费', '附加费', '优惠券', '订单总额', '付款类型', '订单状态', '发货状态', '收货地址', '发票类型', '发票状态', '发票抬头', '公司注册地址', '公司电话', 'adtags来源', '新用户来源', '取消原因', '推送备注', '是否为测试订单', '销售类型', '业务类型', '自采标记', '项目需求描述','收货联系电话'];
            $return_url      = '/self_order';
        }

        $info['map']['p'] = 1;

        $potrol = $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http';

        $params = [
            "type"            => 2,  // 类型 1:模板调用 2: api回调 (必填)
            "source_items_id" => $source_items_id, //设置来源明细id:http://data.ichunt.net/database/1199(必填)
            "file_name"       => $file_name,//导出后文件名称(必填)
            "excel_suf"       => "csv", //导出文件格式 csv,xls(必填)
            "header"          => $headerCell, //导出文件头部 (必填,不得用 ID 做头部,数据顺序必须一致) 
            "query_param"     => $info['map'], //p 第几页,limit每页多少条 占位符,照抄不需要改 (必填)
            "callbackurl"     => $potrol."://".$_SERVER['HTTP_HOST']."/hprose/service", //hrpose 数据提供网址(提供导出脚本分页回调获取数据,必填)
            "callbackfuc"     => "orderExport", //hrpose 回调函数(必填)       
            "create_uid"      => $request->user->userId, #创建人id(必填)
        ];

        // 调用导出系统
        $url    = Config('website.export_url');
        $client = new \Hprose\Http\Client($url."/insertExport", false);
        $res    =  $client->insertExport(json_encode($params));
        // print_r($res);
        $res = json_decode($res, true);

        if ($res['err_code'] == 0) return ['err_code'=>0, 'err_msg'=>'推入到导出系统成功', 'data'=>$res['data']];
        
        return ['err_code'=>1, 'err_msg'=>'推入到导出系统失败'];

        // $orderModel = new OrderModel();

        // return $orderModel->orderExport($info['map']); 
    }

    // 下载合同
    public function ajaxDownloadContract(Request $request) 
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id'); 

            $apiUrl = Config('website.api_domain');
            $k1  = time();
            $k2  = md5(md5($k1).'fh6y5t4rr351d2c3bryi');
            $downLoadUrl = $apiUrl.'contract/pdfinfo?id='.$order_id.'&k1='.$k1.'&k2='.$k2;

            // 操作记录
            $OrderActionLogModel = new OrderActionLogModel();
            $actionLog = $OrderActionLogModel->addLog($order_id, $request->user->userId, 2, '下载合同');

            if (!$actionLog){
                errorLog(Error::E_ADD_FAILED, '添加操作记录失败');
                return ['errcode'=>Error::E_ADD_FAILED, 'errmsg'=>'添加操作记录失败'];
            }

            return ['errcode'=>0, 'errmsg'=>'', 'data'=>$downLoadUrl];
        }
    }

    // 订单详情页面
    public function details(Request $request, $id)
    {
        return $this->templateData($request, $id, 'detail');
    }

    // 详情页
    public function templateData(Request $request, $id, $view_id)
    {
        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '订单详情');

        if ($info['order_info']['order_goods_type'] == 2 && in_array($info['order_info']['order_type'], [1, 3])) { // 平台自营订单
            if ($request->input('tags') != 'self') {
               return redirect('self_order');  // URL重定向
            } else {
                $this->selfOtherData($info, $id);
            }
        }

        return view($view_id, $info);
    }

    // 详情页自营其他数据
    public function selfOtherData(&$info, $order_id)
    {
        $shipping = DB::connection('order')->table('lie_shipping')->select('shipping_id', 'shipping_name')->get();

        $info['shippings'] = [];

        if ($shipping) {
            foreach ($shipping as $v) {
                $shippingInfo[$v->shipping_id] = $v->shipping_name;
            }

            $info['shippings'] = $shippingInfo;
        }

        $extend = DB::connection('order')->table('lie_order_extend')->where(['order_id' => $order_id, 'order_type' => 3])->first(); // 自营线下订单

        $info['extend'] = $extend ? $extend : ''; 
    }

    // 外部引用---会员系统、CRM系统
    public function detailsPage(Request $request, $id)
    {
        return $this->templateData($request, $id, 'page');
    }

    // 调价
    public function changeOrder(Request $request, $id)
    {
        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '人工审单', ["title" => '人工审单', "href" => '#']);

        if ($info['order_info']['order_goods_type'] == 2 && in_array($info['order_info']['order_type'], [1, 3])) { // 平台自营订单
            if ($request->input('tags') != 'self') {
               return redirect('self_order');  // URL重定向
            } else {
                $this->selfOtherData($info, $id);
            }
        }

        // 账期订单跳转到详情页
        if ($info['order_info']['status'] == 4) {
            return redirect('/details/'.$id);
        }

        // 待审核才可以
        if(!in_array($info['order_info']['status'], [-1, 1, 2])){ 
            $redirect = $info['order_info']['order_goods_type'] == 1 ? '/list' : '/self_order';

            return redirect('/prompt')->with(['message'=>"该订单不符合人工审单条件~【status:{$info['order_info']['status']}】",'url' =>$redirect, 'jumpTime'=>3,'status'=>false]);       
        }

        return view('detail', $info);
    }

    //删除单个商品操作
    public function ajaxdeletegoods(Request $request)
    {
        $collert = $request->input();
        $operator_id = $request->user->userId;

        if(!$request->isMethod('post') || !$collert['rec_id']){
            return array('errcode'=>1, 'errmsg'=>'错误操作');
        }

        if(!$collert['reason']){
            errorLog(Error::E_NOT_EXISTS, '请填写删除原因');
            return array('errcode'=>Error::E_NOT_EXISTS,'errmsg'=>'请填写删除原因');
        }

        $url = Config('website.api_domain').'order/deleteGoods';

        $check['k1']  = time();
        $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

        $resData = array(
            "reason"=>$collert['reason'],
            "rec_id"=>$collert['rec_id'],
            'operator_id'=>$operator_id,
            "pf"=>1,
            "k1"=>$check['k1'],
            "k2"=>$check['k2']
        );

        $temp = json_decode(curlApi($url, $resData, "POST"), true);

        return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
    }

    // 保存调价信息
    public function ajaxSaveChange(Request $request)
    {
        if($request->isMethod('post')){
            $order_id   = $request->input('order_id', '');

            if (!$order_id) return array('errcode'=>Error::E_PARAM, 'errmsg'=>'订单参数有误!');

            if (!$request->input('pay_time_limit')) {
                $payTime      = $request->input('payTime', '');
                $payTimeOther = $request->input('payTimeOther', '');

                $pay_time_limit = $payTime == 'other' ? $payTimeOther : $payTime;
            } else {
                $pay_time_limit = $request->input('pay_time_limit');
            }    

            $url = Config('website.api_domain').'order/changeOrder';

            $check['k1']  = time();
            $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

            $client_source = $request->input('client_source') == 1 ? $request->input('input-other-source') : $request->input('client_source');

            $resData = [
                "user_id"           => $request->input('user_id', ''), 
                "cancel_reason"     => $request->input('cancel_reason', ''), 
                "sale_id"           => $request->input('sale_id', ''), 
                "order_pay_type"    => $request->input('order_pay_type', '') ? $request->input('order_pay_type') : 1,
                "status"            => $request->input('order_status', '') ? $request->input('order_status') : 2,
                "deposit_amount"    => $request->input('deposit_amount', ''), 
                "goods_amount"      => $request->input('goods_amount', ''), 
                "order_amount"      => $request->input('order_amount', ''), 
                "extra_fee"         => $request->input('extra_fee', ''), 
                "change_info"       => $request->input('change_info', ''), 
                "pay_time_limit"    => $pay_time_limit, 
                "check_failed"      => $request->input('check_failed', ''), 
                "check_failed_info" => $request->input('check_failed_info', ''), 
                "change_pay_type"   => $request->input('change_pay_type', ''), 
                "order_id"          => $order_id, 
                'operator_id'       => $request->user->userId,
                "pf"                => 1, 
                "k1"                => $check['k1'], 
                "k2"                => $check['k2'],
                "client_source"     => $client_source,
                "change_extend_fee" => $request->input('change_extend_fee', ''),
                "kefu_remark"       => $request->input('kefu_remark', ''), // 客服备注
                "freight_fee"       => $request->input('freight_fee', ''), // 运费
            ];
// dd(curlApi($url, $resData, "POST"));
            $temp = json_decode(curlApi($url, $resData, "POST"), true);

            return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
        }
    }

    // 驳回调价信息
    public function ajaxRejected(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id');

            // 调价失败临时表状态更改
            $order_temp = DB::connection('order')->table('lie_order_extend')->where(['order_id' => $order_id])->update(['status' => -1]);

            if (!$order_temp) {
                errorLog(Error::E_UPDATE_FAILED, '驳回失败');
                return array('errcode'=>Error::E_UPDATE_FAILED, 'errmsg'=>'驳回失败');
            } 

            // 操作记录
            $OrderActionLogModel = new OrderActionLogModel();
            $actionLog = $OrderActionLogModel->addLog($order_id, $request->user->userId, 2, '审核驳回');

            return array('errcode'=>0,'errmsg'=>'驳回成功');
        }
    }

    // 推送业务员
    public function sendSales(Request $request, $id='')
    {
        if ($request->isMethod('post')) {
            $order_id    = $request->input('order_id', '');
            $sale_id     = $request->input('sale_id', '');
            $send_remark = $request->input('send_remark', '');
            $operator_id = $request->user->userId;

            if (!$order_id || !$sale_id) return ['errcode'=>Error::E_NOT_EXISTS, 'errmsg'=>'参数不存在'];

            $url = Config('website.api_domain').'order/sendSales';

            $check['k1']  = time();
            $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

            $resData = array(
                "order_id"    => $order_id,
                "sale_id"     => $sale_id,
                'operator_id' => $operator_id,
                'send_remark' => $send_remark,
                "pf"          => 1,
                "k1"          => $check['k1'],
                "k2"          => $check['k2']
            );

            $temp = json_decode(curlApi($url, $resData, "POST"), true);

            return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
        }   

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '推送业务员', ["title" => '推送业务员', "href" => '#']);

        $perm = new PermController;

        $tags = $request->input('tags', '');

        // 联营
        $joint_manager     = $perm->getRoleUsers($request, '经理');
        $joint_in_charge_1 = $perm->getRoleUsers($request, '线销一组主管');
        $joint_in_charge_2 = $perm->getRoleUsers($request, '线销二组主管');
        $joint_in_charge_3 = $perm->getRoleUsers($request, '线销三组主管');
        $joint_kefu_1      = $perm->getRoleUsers($request, '线销一组客服');
        $joint_kefu_2      = $perm->getRoleUsers($request, '线销二组客服');
        $joint_kefu_3      = $perm->getRoleUsers($request, '线销三组客服');
        $sale_list         = $perm->getRoleUsers($request, '交易员');
        $test              = $perm->getRoleUsers($request, '测试');

        $self_manager = $self_kefu = '';

        if ($tags && $tags == 'self') {
            $self_manager   = $perm->getRoleUsers($request, '自营客服主管');
            $self_assistant = $perm->getRoleUsers($request, '自营客服主管助理');
            $self_kefu      = $perm->getRoleUsers($request, '自营客服');
            $self_kefu      = array_merge($self_assistant, $self_kefu);
        }

        $info['joint_manager']   = $this->filterLeave($joint_manager);
        $info['kefu_manager']    = Config('perm_args.kefu_manager');
        
        $joint_in_charge_1       = $this->filterLeave($joint_in_charge_1);
        $joint_in_charge_2       = $this->filterLeave($joint_in_charge_2);
        $joint_in_charge_3       = $this->filterLeave($joint_in_charge_3);
        $info['joint_in_charge'] = $this->remove_duplicate(array_merge($joint_in_charge_1, $joint_in_charge_2, $joint_in_charge_3));

        // 临时处理 (主管里面去掉张娟)
        foreach ($info['joint_in_charge'] as $k=>$v) {
            if ($v->userId == '1445') {
                unset($info['joint_in_charge'][$k]);
            }
        }

        $info['joint_kefu_1'] = $this->filterLeave($joint_kefu_1);
        $info['joint_kefu_2'] = $this->filterLeave($joint_kefu_2);
        $info['joint_kefu_3'] = $this->filterLeave($joint_kefu_3);       
        $info['sale_list']    = $this->filterLeave($sale_list);
        $info['test']         = $this->filterLeave($test); 
        $info['self_manager'] = $this->filterLeave($self_manager);
        $info['self_kefu']    = $this->filterLeave($self_kefu);
        $info['sale_id']      = $request->user->userId;
        $info['role']         = $perm->getUserRole($request); 

        return view('detail', $info);
    }

    // 二维数组去重
    public function remove_duplicate($array)
    {
        $result = array();

        foreach ($array as $key => $value) {
            $has = false;

            foreach($result as $val){
                if($val->userId == $value->userId){
                    $has = true;
                    break;
                }
            }

            if(!$has) $result[] = $value;  
        }

        return $result;
    }

    // 去掉已离职人员
    public function filterLeave(&$data)
    {
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                if ($v->status == 4) {
                    unset($data[$k]);
                }
            }
        }

        return $data;
    }

    // 人工审单后再次调价 --- 20180404
    public function adjustPrice(Request $request, $id)
    {
        $info = $this->orderDetail($request, $id);

        //总共允许2次调价(以点击审核按钮次数来统计)
        if ($info['order_info']['order_goods_type'] != 1 && $info['order_info']['adjust_count'] >= 2) {
            errorLog(Error::E_FORBIDDEN, '该订单无法再进行调价操作');
            return redirect('/prompt')->with(['message'=>"该订单无法再进行调价操作",'url' =>'/details/'.$id, 'jumpTime'=>3,'status'=>false]);
        }
        
        $url = Config('website.api_domain').'order/applyAdjust';

        $check['k1']  = time();
        $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

        $resData = array("order_id"=>$id, "pf"=>1, "k1"=>$check['k1'], "k2"=>$check['k2'], "operator_id" => $request->user->userId);

        $temp = json_decode(curlApi($url, $resData, "POST"), true);

        // url 标签
        $tags = $request->input('tags', '');

        if ($tags) {
            $param = '?tags='.$tags;
        } else {
            $param = '';
        }

        if ($temp['err_code'] == 0) {
            return redirect('/change/'.$id.$param);
        } else {
            return redirect('/prompt')->with(['message'=>$temp['err_msg'],'url' =>'/details/'.$id.$param, 'jumpTime'=>3,'status'=>false]);
        }     
    }

    // 审核不通过 
    // public function ajaxCheck(Request $request)
    // {
    //     if($request->isMethod('post')){
    //         $order_id = $request->input('order_id', ''); //订单号
    //         $sale_id = $request->input('sale_id', null); //对应销售
    //         $operator_id = $request->user->userId;
    //         $cancel_reason = $request->input('cancel_reason', '');

    //         if (!isset($sale_id)) {
    //             return array('errcode'=>1, 'errmsg'=>'请选择订单业务员!');
    //         }

    //         if (!$order_id) {
    //             return array('errcode'=>1, 'errmsg'=>'订单参数有误!');
    //         }

    //         //用于后台订单审核
    //         $url = Config('website.api_domain').'order/cancel';

    //         $check['k1']  = time();
    //         $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

    //         $resData = array("cancel_reason"=>$cancel_reason, "order_id"=>$order_id, 'sale_id'=>$sale_id, "pf"=>1, "k1"=>$check['k1'], "k2"=>$check['k2'], 'operator_id'=>$operator_id, 'type' => 3);

    //         $temp = json_decode(curlApi($url, $resData, "POST"), true);

    //         return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
    //     }
    // }

    // 对账
    public function checkPay(Request $request, $id)
    {
        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '对账', ["title" => '对账', "href" => '#']);

        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id', '');
            $cid = $request->input('cid', '');
            $serial_number = $request->input('serial_number', '');
            $operator_id = $request->user->userId;

            // last_check 尾款确认
            if (!$request->input('last_check', '')) {
                $url = Config('website.api_domain').'order/checkpay';

                $data['order_id'] = $order_id;
                $data['cid'] = $cid;
                $data['serial_number'] = $serial_number;
                $data['operator_id'] = $operator_id;

                $data['k1'] = time();
                $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

                $temp = json_decode(curlApi($url, $data, "POST"), true); // 连接API

                if ($temp['err_code'] == 0) {
                    return array('errcode'=>0,'errmsg'=>'操作成功');
                } else {
                    errorLog(Error::E_UPDATE_FAILED, '操作失败');
                    return array('errcode'=>Error::E_UPDATE_FAILED,'errmsg'=>'操作失败');
                }
            } else {
                $payLog['is_paid'] = 2;

                if (DB::connection('order')->table('lie_pay_log')->where(['order_id'=>$order_id, 'pay_type'=>2])->update($payLog)) {
                    return array('errcode'=>0,'errmsg'=>'操作成功');
                } 
            }

            return array('errcode'=>-1,'errmsg'=>'操作失败');
        }

        // 订单待付款状态可操作对账
        if ($info['order_info']['order_pay_type'] == 1) { // 全款
            if (!in_array($info['order_info']['status'], array(2, 4))) {
                errorLog(Error::E_FORBIDDEN, '订单无法操作');
                return redirect('/prompt')->with(['message'=>'订单无法操作','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
            }
        } else if ($info['order_info']['order_pay_type'] == 2) { // 预付款
            if (!in_array($info['order_info']['status'], array(2, 3, 4))) {
                errorLog(Error::E_FORBIDDEN, '订单无法操作');
                return redirect('/prompt')->with(['message'=>'订单无法操作','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
            }
        }

        return view('detail', $info);
    }

    // 联营退货退款
    public function refund(Request $request, $id) 
    {
        if ($request->isMethod('post'))
        {
            $data['order_id']          = $request->input('order_id');
            $data['refund_info']       = $request->input('refund_info');
            $data['all_refund_amount'] = $request->input('all_refund_amount');
            $data['price_fall']        = $request->input('price_fall');
            $data['refund_reason']     = $request->input('refund_reason');
            $data['operator_id']       = $request->user->userId;

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'refund/refundGoods';

            $temp = json_decode(curlApi($url, $data, 'POST'), true);

            return array('errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']); 
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '退货申请', ["title" => '退货申请', "href" => '#']);

        // 未发货明细
        $data['k1']       = time();
        $data['k2']       = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['order_id'] = $id;

        $url = Config('website.api_domain').'removal/getUnshippedItems';

        $res = json_decode(curlApi($url, $data, 'POST'), true);

        if ($res['err_code'] != 0) 
            return redirect('/prompt')->with(['message'=>'退货退款无法操作'.$res['err_msg'], 'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);

        $info['unshippedItems'] = $res['data'];

        return view('detail', $info);
    }

    // 自营退货申请
    public function orderReturn(Request $request, $id) 
    {
        if ($request->isMethod('post')) {
            $data['order_id']          = $id;
            $data['return_info']       = $request->input('return_info');
            $data['return_items_info'] = $request->input('return_items_info');
            $data['operator_id']       = $request->user->userId;

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'return/returnGoods';

            $temp = json_decode(curlApi($url, $data, 'POST'), true);

            return array('errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']); 
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '退货申请', ["title" => '退货申请', "href" => '#']);

        // 未发货明细
        $data['k1']       = time();
        $data['k2']       = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['order_id'] = $id;

        $url = Config('website.api_domain').'removal/getRemovalItems';

        $res = json_decode(curlApi($url, $data, 'POST'), true);

        if ($res['err_code'] != 0) return redirect('/prompt')->with(['message'=>'退货无法操作,原因:'.$res['err_msg'], 'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);

        if (empty($res['data'])) return redirect('/prompt')->with(['message'=>'退货无法操作,原因:无出库数据', 'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);

        $info['removalItems'] = $res['data'];

        return view('detail', $info);
    }

    // 退货申请编辑
    public function orderReturnEdit(Request $request, $id) 
    {
        if ($request->isMethod('post')) {
            $data['return_id']         = $request->input('return_id');
            $data['return_info']       = $request->input('return_info');
            $data['return_items_info'] = $request->input('return_items_info');
            $data['operator_id']       = $request->user->userId;

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'return/editReturnGoods';

            $temp = json_decode(curlApi($url, $data, 'POST'), true);

            return array('errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']); 
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '编辑退货申请', ["title" => '编辑退货申请', "href" => '#']);

        $return_id = $request->input('return_id', '');

        $redirect_url = $info['order_info']['order_goods_type'] == 1 ? '/return_list' : '/self_return_list';

        if (!$return_id) return redirect($redirect_url);

        $OrderReturnModel    = new OrderReturnModel();
        $info['return']      = $OrderReturnModel->find($return_id);
        $info['returnItems'] = $OrderReturnModel->find($return_id)->hasManyReturnItems;

        if (!in_array($info['return']['status'], [-2, 1])) return redirect('/prompt')->with(['message'=>'status为'.$info['return']['status'].',无法编辑退货单', 'url' =>$redirect_url, 'jumpTime'=>3,'status'=>false]);

        // 补充退货明细
        foreach ($info['returnItems'] as $k=>&$v) {
            $map = array();
            $map['order_id'] = $v['order_id'];
            $map['rec_id']   = $v['rec_id'];
            $map['goods_id'] = $v['goods_id'];
            // 获取出库数量
            $removal = DB::connection('order')->table('lie_removal_items')->where($map)->select('removal_number')->first();
            $v['removal_number'] = $removal ? $removal->removal_number : 0; 

            // 获取已申请退货数量
            $v['already_return_num'] = DB::connection('order')->table('lie_order_return_items')->where($map)->sum('return_num');
        }
       
        return view('detail', $info);
    }

    //订单物流信息
    public function changeShipping(Request $request, $id='')
    {
        if($request->isMethod('post')){
            $data['shipping_type'] = $request->input('shipping_type', 1);
            $data['consignee']     = $request->input('consignee', '');
            $data['mobile']        = $request->input('mobile', '');
            $data['province']      = $request->input('province', 0);
            $data['city']          = $request->input('city', 0);
            $data['district']      = $request->input('district', '');
            $data['address']       = $request->input('address', '');

            $data['k1']            = time();
            $data['k2']            = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
            $data['order_id']      = $request->input('order_id','');
            $data['operator_id']   = $request->user->userId;

            $update_url = Config('website.api_domain').'order/updateOrderAddress';

            $update = json_decode(curlApi($update_url, $data, 'POST'), true);

            if ($update['err_code'] == 0) {
                return array('errcode'=>0,'errmsg'=>'操作成功');
            } else {
                errorLog(Error::E_UPDATE_FAILED, '操作失败');
                return array('errcode'=>-1,'errmsg'=>'操作失败');
            }
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '订单收货地址', ["title" => '收货地址', "href" => '#']);

        if (!$info['order_address_info']) {
            errorLog(Error::E_NOT_EXISTS, '订单地址不存在');
            return redirect('/prompt')->with(['message'=>'订单地址不存在!', 'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3, 'status'=>false]);
        }

        $info['detail'] = $info['order_address_info'];
        $info['detail']['order_id'] = $id;

        return view('changeShipping', $info);
    }

    // 订单发票信息
    public function changeInvoice(Request $request, $id='')
    {
        if($request->isMethod('post')){
            $data['map'] = $request->input();

            $data['k1']  = time();
            $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
            $data['operator_id'] = $request->user->userId;

            $update_url = Config('website.api_domain').'order/updateOrderInvoice';

            $update = json_decode(curlApi($update_url, $data, 'POST'), true);

            if ($update['err_code'] == 0) {
                return array('errcode'=>0,'errmsg'=>'操作成功');
            } else {
                errorLog(Error::E_UPDATE_FAILED, '操作失败');
                return array('errcode'=>-1,'errmsg'=>'操作失败');
            }
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '订单发票信息', ["title" => '发票信息', "href" => '#']);

        if (!$info['order_invoice_info']) {
            errorLog(Error::E_NOT_EXISTS, '发票不存在');
            return redirect('/prompt')->with(['message'=>'发票不存在!','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }

        $info['detail'] = $info['order_invoice_info'];
        $info['detail']['order_id'] = $id;

        return view('changeInvoice', $info);
    }

    // 订单详情页面头部信息
    public function pageHeader($request, &$info, $title, $addInfo=[])
    {
        $info['title'] = $title;

        $param = $request->only('tags');

        if (!$param['tags']) {
            $info['paths'] = [["title" => '联营订单', "href" => '#'], ["title" => '平台订单列表', "href" => '/list'], ["title" => '订单明细', "href" => !empty($addInfo) ? '/details/'.$info['order_info']['order_id'] : '#']];
        } else if ($param['tags'] && $param['tags'] == 'erp') {
            $info['paths'] = [["title" => '联营订单', "href" => '#'], ["title" => 'ERP订单列表', "href" => '/erp_order'], ["title" => '订单明细', "href" => !empty($addInfo) ? '/details/'.$info['order_info']['order_id'].'?tags=erp' : '#']];
        } else if ($param['tags'] && $param['tags'] == 'self') {
            $info['paths'] = [["title" => '自营订单', "href" => '#'], ["title" => '自营订单列表', "href" => '/self_order'], ["title" => '订单明细', "href" => !empty($addInfo) ? '/details/'.$info['order_info']['order_id'].'?tags=self' : '#']];
        }

        if (!empty( $addInfo))
            array_push($info['paths'], $addInfo);
    }

    /**
     *发货
     */
    public function send(Request $request, $id)
    {
        if($request->isMethod('post')){
            $data = $request->input();

            $check['k1']  = time();
            $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'order/send';

            $resData = array("shipping_no"=>$data['shipping_no'], "order_id"=>$data['order_id'], 'shipping_id'=>$data['shipping_id'], "pf"=>1, "k1"=>$check['k1'], "k2"=>$check['k2']);

            $temp = json_decode(curlApi($url,$resData,"POST"), true);

            return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '发货', ["title" => '发货', "href" => '#']);

        $shippings = DB::connection('order')->table('lie_shipping')->where(['enabled'=>1,'is_order'=>1])->get();//获取配送方式
        
        $ship_type = [];
        foreach ($shippings as $key => $value) {
            $ship_type[$value->shipping_id] = $value->shipping_name;
        }
 
        $info['ship_type'] = $ship_type;
        $info['shippings'] = $shippings;

        return view('detail', $info);
    }

    // 发票物流信息
    public function invShipping(Request $request, $id)
    {
        if($request->isMethod('post')){
            $data = $request->input();
            $operator_id = $request->user->userId;

            if (!$data['inv_shipping_no']) {
                errorLog(Error::E_NOT_EXISTS, '发票物流单号不可为空');
                return redirect('/prompt')->with(['message'=>'发票物流单号不可为空~','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
            }

            $check['k1']  = time();
            $check['k2']  = md5(md5($check['k1']).'fh6y5t4rr351d2c3bryi');

            $url = Config('website.api_domain').'order/invShipping';

            $resData = array("pf"=>1, "k1"=>$check['k1'], "k2"=>$check['k2'], "order_id"=>$data['order_id'], "inv_shipping_no"=>$data['inv_shipping_no'], "inv_shipping_id"=>$data['inv_shipping_id'], 'operator_id'=>$operator_id);

            $temp = json_decode(curlApi($url, $resData, "POST"), true);

            if ($temp['err_code'] == 0) {
                return redirect('/prompt')->with(['message'=>$temp['err_msg'],'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>true]);
            }

            return redirect('/prompt')->with(['message'=>$temp['err_msg'],'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }

        $info = $this->orderDetail($request, $id);
        $this->pageHeader($request, $info, '寄送发票', ["title" => '寄送发票', "href" => '#']);

        if($info['order_invoice_info']['inv_type'] == 1){
            return redirect('/prompt')->with(['message'=>'当前订单不需要发票~','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }

        if($info['order_info']['status'] != 10){
            return redirect('/prompt')->with(['message'=>'订单未交易成功,无法寄送发票~','url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }

        //物流信息
        $shippings = DB::connection('order')->table('lie_shipping')->where(['enabled'=>1,'is_invoice'=>1])->get();

        $shippingArr = [];
        foreach ($shippings as $key => $value) {
            $shippingArr[$value->shipping_id] = $value->shipping_name;
        }

        $info['shippingArr'] = $shippingArr;
        $info['shippings'] = $shippings;

        return view('detail', $info);
    }

    //3.0后台订单临时版 api
    public function orderDetail(Request $request, $id, $type = '0')
    {
        $info = $this->getPageInfo($request);

        if (!$type) {
            $type = '0';
        }

        //调用订单接口,获取订单详细信息
        $url = Config('website.api_domain').'order/getOrderDetails';

        $data['k1']  = time();
        $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

        $userData = array("order_id"=>$id, "type"=>$type, "pf"=>1, "k1"=>$data['k1'], "k2"=>$data['k2']);

        $temp = json_decode(curlApi($url, $userData, "POST"), true);

        // 消息通知
        $mobile = isset($temp['data']['order_info']['user_info']['msg_mobile']) ? $temp['data']['order_info']['user_info']['msg_mobile'] : '';

        if (!$mobile) {
            // $mobile = isset($temp['data']['order_info']['user_info']['mobile']) ? $temp['data']['order_info']['user_info']['mobile'] : '';
            $user = DB::connection('order')->table('lie_user_main')->where('user_id', $temp['data']['order_info']['user_id'])->select('mobile')->first();
            $mobile = $user ? $user->mobile : '';
        }

        // 获取操作记录
        $actionLog = DB::connection('order')->table('lie_order_action_log')->where('order_id', $id)->orderBy('create_time', 'DESC')->orderBy('log_id', 'DESC')->get();

        $response = [
            'user_mobile'                 => $mobile,
            'order_info'                  => $temp['data']['order_info'],
            'user_info'                   => $temp['data']['order_info']['user_info'],
            'company_info'                => $temp['data']['order_info']['company_info'],
            'order_invoice_info'          => $temp['data']['order_invoice_info'],
            'order_items_info'            => $temp['data']['order_items_info'],
            'order_address_info'          => $temp['data']['order_address_info'],
            'order_invoice_address_info'  => $temp['data']['order_invoice_address_info'],
            'order_shipping_info'         => $temp['data']['order_shipping_info'],
            'order_invoice_shipping_info' => $temp['data']['order_invoice_shipping_info'],
            'order_pay_log'               => $temp['data']['order_pay_log'],
            'order_price_info'            => $temp['data']['order_price_info'],
            'order_temp_info'             => $temp['data']['order_temp_info'],
            'order_shipping_inside'       => $temp['data']['order_shipping_inside'],
            'actionLog'                   => $actionLog,
            'order_refund_info'           => $temp['data']['order_refund_info'],
            'order_refund_items'          => $temp['data']['order_refund_items'],
        ];

        $response = array_merge($response, $info);

        return $response;
    }

    // 取消订单
    public function ajaxCancel(Request $request)
    {
        if ($request->isMethod('post')) {
            $data['order_id'] = $request->input('order_id', 0);
            $data['cancel_reason'] = $request->input('cancel_reason', '');
            $data['type'] = $request->input('type', 2); // 2.取消订单,3.审核不通过,4-填写取消原因 
            $data['operator_id'] = $request->user->userId;

            $url = Config('website.api_domain').'order/cancel';

            $data['k1']  = time();
            $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $temp = json_decode(curlApi($url, $data, "POST"), true);

            return array('errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']);
        }
    }

    // 填写自营订单/发票快递单
    public function ajaxSelfExpress(Request $request)
    {
        if ($request->isMethod('post')) {
            $shipping_type = $request->input('type');

            //调用接口
            $url = Config('website.api_domain').'order/send';

            $data['k1']  = time();
            $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $resData = array(
                "k1" => $data['k1'], 
                "k2" => $data['k2'],
                'order_id' => $request->input('order_id'),
                'shipping_type' => $shipping_type,      
                'shipping_no' => $request->input('express_no'),
                'shipping_id' => $request->input('shipping_id'),
                'operator_id' => $request->user->userId,
            );

            $temp = json_decode(curlApi($url, $resData, "POST"), true);

            return array('errcode'=>$temp['err_code'],'errmsg'=>$temp['err_msg']);
        }
    }

    // 自营对账
    public function selfCheckPay(Request $request, $id)
    {
        if ($request->isMethod('post')) {
            $url = Config('website.api_domain').'order/selfcheckpay';

            $data['order_id'] = $request->input('order_id', '');
            // $data['serial_number'] = $request->input('serial_number', '');
            $data['operator_id'] = $request->user->userId;
            $data['trans_amount'] = $request->input('trans_amount', 0);

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $temp = json_decode(curlApi($url, $data, "POST"), true); // 连接API

            if ($temp['err_code'] == 0) {
                return array('errcode'=>0, 'errmsg'=>'操作成功');
            } else {
                errorLog(Error::E_UPDATE_FAILED, '操作失败');
                return array('errcode'=>Error::E_UPDATE_FAILED, 'errmsg'=>'操作失败');
            }
        }

        $info = $this->orderDetail($request, $id);

        if (!$request->input('tags') && $request->input('tags') != 'self') { // 自营订单页面
            return redirect('/self_order');
        }

        $this->pageHeader($request, $info, '自营对账', ["title" => '自营对账', "href" => '#']);

        $this->selfOtherData($info, $id);

        return view('detail', $info);
    }

    // 快递配置
    public function expressSet(Request $request)
    {
        $key = Config('website.express_fee_key');
        $express_fee = Config('website.express_fee');

        if ($request->isMethod('post')) {
            $data['sz_inside'] = $request->input('sz_inside');
            $data['gd_inside'] = $request->input('gd_inside');
            $data['gd_outside'] = $request->input('gd_outside');

            Redis::set($key, json_encode($data));

            return ['errcode'=>0, 'errmsg'=>'修改成功'];
        }

        $info = $this->getPageInfo($request);
        $info['title'] = '快递费用配置';

        $redis = Redis::connection('read');
        $express = $redis->get($key);
        
        if (!$express) {
            Redis::set($key, json_encode($express_fee));
            $info['express_fee'] = $express_fee;
        } else {
            $info['express_fee'] = json_decode($express, true);
        }

        return view('express_set', $info);
    }

    // 查看物流轨迹
    public function shipping(Request $request)
    {
        if ($request->isMethod('post')) {
            $data['id'] = $request->input('order_id'); 
            $data['uid'] = $request->input('user_id'); 
            $data['type'] = $request->input('type'); 

            $url = Config('website.api_domain').'order/shipping';

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $temp = json_decode(curlApi($url, $data, "POST"), true); // 连接API

            if ($temp['err_code'] == 0) {
                return ['errcode'=>0, 'errmsg'=>'', 'data'=>$temp['data'][0]['info']];
            } else {
                errorLog(Error::E_UPDATE_FAILED, '操作失败');
                return ['errcode'=>Error::E_UPDATE_FAILED, 'errmsg'=>$temp['err_msg']];
            }
        }
    }
    
    /**
     * 定时任务:提前一天上午10点
     * 检查订单付款时间
     * 过滤条件:状态、测试人员、是否是真实数据、付款时间大于当前时间
     * @return [type] [description]
     */
    public function checkOrderSendSms()
    {
        $order = DB::connection('order')
                ->table('lie_order')
                ->where('order_goods_type', '=', 1)
                ->where('status', '=', 2)
                // ->whereNotIn('user_id', $this->testMobile())
                ->where('is_type', '=', 0)
                ->where('pay_time', '>', time())
                ->select('order_id', 'order_sn', 'user_id', 'order_amount', 'currency', 'pay_time')
                ->orderBy('create_time', 'DESC')
                ->get();

        //调用消息接口
        $url = Config('website.api_domain').'msg/sendmessagebyauto';

        $data['k1']  = time();
        $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

        $keyword = 'order-pay-time-remind';

        if (!empty($order)) {
            foreach ($order as $v) {
                $orderInfo = array();
                
                // 提前一天推送消息
                $diff = $v->pay_time - time();

                if ($diff <= 86400) {
                    $currency = $v->currency == 1 ? '¥' : '$';

                    $orderInfo['data']['order_sn'] = $v->order_sn;
                    $orderInfo['data']['order_amount'] = $currency.$v->order_amount;

                    $orderInfo = json_encode($orderInfo['data'], JSON_UNESCAPED_UNICODE);

                    $orderData = [
                        "keyword" => $keyword, 
                        "pf"       => 1, 
                        "k1"       => $data['k1'], 
                        "k2"       => $data['k2'],
                        'touser'   => json_encode($v->user_id),
                        'data'     => $orderInfo,
                    ];

                    $temp = json_decode(curlApi($url, $orderData, "POST"), true);

                    if ($temp['err_code'] == 0) {
                        continue;
                    } else {
                        errorLog($temp['err_code'], $temp['err_msg'].',订单ID:'.$v->order_id); // 消息推送失败记录
                    }
                }
            }


        }
    }

    // 定时任务:每5分钟
    // 付款时间到达后自动取消订单
    public function checkOrderCancel()
    {
        $time = strtotime(date('Y-m-d', time())); // 当天0点

        $order = DB::connection('order')
                ->table('lie_order')
                ->where('order_goods_type', '=', 1)
                ->where('order_pay_type', '<>', 3) // 过滤账期订单
                ->where('status', '=', 2)
                // ->whereNotIn('user_id', $this->testMobile())
                ->where('is_type', '=', 0)
                ->where('pay_time', '>=', $time)
                ->select('order_id', 'pay_time')
                ->orderBy('create_time', 'DESC')
                ->get();

        if (!empty($order)) {
            foreach ($order as $v) {
                // 到达付款时间后自动取消订单
                if ($v->pay_time <= time()) {
                    $update = DB::connection('order')
                            ->table('lie_order')
                            ->where('order_id', '=', $v->order_id)
                            ->update(['status' => -1, 'pay_time' => 0, 'cancel_time' => time()]);

                    if ($update) {
                        // 操作记录
                        $OrderActionLogModel = new OrderActionLogModel();
                        $actionLog = $OrderActionLogModel->addLog($v->order_id, 0, 3, '取消订单,取消原因:超时未付款'); // 系统取消

                        continue;
                    } else {
                        errorLog(E_UPDATE_FAILED, '自动取消订单失败, 订单ID:'.$v->order_id); // 自动取消订单失败记录
                    }
                }
            }
        }
    }

    // 延长付款时间
    public function ajaxDelayTime(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id', '');
            $delay_time = $request->input('delay_time', '');
        }

        if (empty($order_id) || empty($delay_time)) {
            errorLog(Error::E_NOT_EXISTS, '参数不存在');
            return ['errcode'=>Error::E_NOT_EXISTS, 'errmsg'=>'参数不存在'];
        } 

        $order = DB::connection('order')->table('lie_order')->where('order_id', '=', $order_id)->select('pay_time')->first();

        $delay_time = $order->pay_time + $delay_time * 86400;

        $update = DB::connection('order')->table('lie_order')->where('order_id', '=', $order_id)->update(['pay_time'=>$delay_time]);

        if (!$update) {
            errorLog(Error::E_UPDATE_FAILED, '延长失败');
            return ['errcode'=>1, 'errmsg'=>'延长失败'];
        }

        // 操作记录
        $OrderActionLogModel = new OrderActionLogModel();
        $actionLog = $OrderActionLogModel->addLog($order_id, $request->user->userId, 2, '延长付款时间,截止到:'.date('Y-m-d H:i:s', $delay_time));

        return ['errcode'=>0, 'errmsg'=>'延长成功'];
    }

    // 线下转账
    public function offlinePaid(Request $request)
    {
        if ($request->isMethod('post')) {
            $data['order_id'] = $request->input('order_id', '');
            $data['order_sn'] = $request->input('order_sn', '');
            $data['operator_id'] = $request->user->userId;

            if (empty($data['order_id']) && empty($data['order_sn'])) return ['errcode'=>Error::E_NOT_EXISTS, 'errmsg'=>'参数不存在'];

            $url = Config('website.api_domain').'order/offlinePaid';

            $data['k1'] = time();
            $data['k2'] = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');

            $temp = json_decode(curlApi($url, $data, "POST"), true); // 连接API

            if ($temp['err_code'] != 0) {
                return ['errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']];
            }

            return ['errcode'=>$temp['err_code'], 'errmsg'=>$temp['err_msg']];
        }
    }

    // 编辑合同乙方信息
    public function editContract(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id                   = $request->input('order_id', '');
            $data['contract_com_name']  = $request->input('contract_com_name', '');
            $data['contract_com_addr']  = $request->input('contract_com_addr', '');
            $data['contract_link_name'] = $request->input('contract_link_name', '');
            $data['contract_link_tel']  = $request->input('contract_link_tel', '');

            DB::connection('order')->transaction(function() use ($request, $order_id, $data) {
                DB::connection('order')->table('lie_order_extend')->where('order_id', $order_id)->update($data);

                $OrderActionLogModel = new OrderActionLogModel();
                $OrderActionLogModel->addLog($order_id, $request->user->userId, 2, '编辑合同乙方信息'); // 操作记录       
            });

            return ['errcode'=>0, 'errmsg'=>'编辑合同成功'];   
        }
    }

    // 回传合同
    public function uploadContract(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id                  = $request->input('order_id');
            $data['upload_contract_url'] = $request->input('url');

            DB::connection('order')->transaction(function() use ($request, $order_id, $data) {
                DB::connection('order')->table('lie_order')->where('order_id', $order_id)->update(['erp_syn'=>1]); // 标记ERP同步
                DB::connection('order')->table('lie_order_extend')->where('order_id', $order_id)->update($data);

                $OrderActionLogModel = new OrderActionLogModel();
                $OrderActionLogModel->addLog($order_id, $request->user->userId, 2, '回传合同'); // 操作记录       
            });

            return ['errcode'=>0, 'errmsg'=>'回传合同成功']; 
        }
    }

    // 获取订单明细跟踪
    public function getOrderItemsTrack(Request $request)
    {
        if ($request->isMethod('post')) {
            $rec_id = $request->input('rec_id');

            $OrderItemsTrackModel = new OrderItemsTrackModel;
            $data = $OrderItemsTrackModel->getOrderItemsTrack($rec_id);

            return ['errcode'=>0, 'errmsg'=>'成功', 'data'=>$data]; 
        }
    }

    public function tempCount(Request $request)
    {
        $current = strtotime(date('Y-m-d', time())); // 当天0点
       
        $half = strtotime('2017-11-28'); // 半年

        $year = strtotime('2017-05-28'); // 一年

        $userMainModel = new UserMainModel();
        $testMobile = $userMainModel->testMobile();

        // 订单数量
        $halfCount = DB::connection('order')->table('lie_order')
                    // ->where('order_goods_type', 1)
                    // ->where('order_type', 1)
                    ->whereNotIn('user_id', $testMobile)
                    ->where('is_type', 0)
                    ->whereBetween('create_time', [$half, $current])
                    ->count();
        echo '半年订单数:'.$halfCount.'<br>';
                    
        $yearCount = DB::connection('order')->table('lie_order')
                    ->whereNotIn('user_id', $testMobile)
                    ->where('is_type', 0)
                    ->whereBetween('create_time', [$year, $current])
                    ->count();
        echo '一年订单数:'.$yearCount.'<br>';
                    
        // 普票订单数
        $halfInvoice = DB::connection('order')
                    ->table('lie_order as o')
                    ->leftJoin('lie_order_invoice as i', 'o.order_id', '=', 'i.order_id')
                    ->whereNotIn('o.user_id', $testMobile)
                    ->where('o.is_type', 0)
                    ->where('i.inv_type', 2)
                    ->whereBetween('o.create_time', [$half, $current])
                    ->count(); 
        echo '半年普票订单数:'.$halfInvoice.'<br>'; 

        $yearInvoice = DB::connection('order')
                    ->table('lie_order as o')
                    ->leftJoin('lie_order_invoice as i', 'o.order_id', '=', 'i.order_id')
                    ->whereNotIn('o.user_id', $testMobile)
                    ->where('o.is_type', 0)
                    ->where('i.inv_type', 2)
                    ->whereBetween('o.create_time', [$year, $current])
                    ->count();   
        echo '一年普票订单数:'.$yearInvoice.'<br>'; 
                    
        // 增票订单数
        $halfAddInvoice = DB::connection('order')
                    ->table('lie_order as o')
                    ->leftJoin('lie_order_invoice as i', 'o.order_id', '=', 'i.order_id')
                    ->whereNotIn('o.user_id', $testMobile)
                    ->where('o.is_type', 0)
                    ->where('i.inv_type', 3)
                    ->whereBetween('o.create_time', [$half, $current])
                    ->count();  
        echo '半年增票订单数:'.$halfAddInvoice.'<br>';

        $yearAddInvoice = DB::connection('order')
                    ->table('lie_order as o')
                    ->leftJoin('lie_order_invoice as i', 'o.order_id', '=', 'i.order_id')
                    ->whereNotIn('o.user_id', $testMobile)
                    ->where('o.is_type', 0)
                    ->where('i.inv_type', 3)
                    ->whereBetween('o.create_time', [$year, $current])
                    ->count();        
        echo '一年增票订单数:'.$yearAddInvoice.'<br>';       
    }

    // 检查历史订单数据
    public function checkHistroyOrder(Request $request)
    {
        // 查找用户订单数,并更新用户表和订单扩展表
        $subQuery = OrderModel::where('is_type', '=', 0)->where('status', '<>', -1)->orderBy('order_id');

        DB::connection('order')->table('lie_order_extend')->update(['is_new' => 0]); // 是否新订单恢复默认值0

        OrderModel::from(DB::raw("({$subQuery->toSql()}) as sub"))
        ->mergeBindings($subQuery->getQuery())
        ->select(DB::raw('sub.user_id, sub.order_id, count(*) as order_count'))
        ->groupBy('sub.user_id')
        ->chunk(100, function($orderCount) {
            foreach ($orderCount as $k=>$v) { 
                $new_user = $new_order = [];
                
                if ($v->order_count == 1) {
                    $new_user['is_new'] = 1; // 新用户
                    $new_order['is_new'] = 1; // 新订单
                } else {
                    $new_user['is_new'] = 2; // 老用户 
                    $new_order['is_new'] = 1; // 多订单将第一个订单设置为新订单 
                }

                // 更新用户
                DB::connection('order')->table('lie_user_main')->where('user_id', $v->user_id)->update($new_user);

                $extend = DB::connection('order')->table('lie_order_extend')->where('order_id', $v->order_id)->first();

                if ($extend) {
                    // 更新订单          
                    DB::connection('order')->table('lie_order_extend')->where('order_id', $v->order_id)->update($new_order);
                } else {
                    // 创建  
                    $new_order['order_id'] = $v->order_id;   
                    DB::connection('order')->table('lie_order_extend')->insert($new_order);
                }    
            }
        });
    }

}