<?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;

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

    if ($price) {
        return $price->price;
    }

    return null;
}

// 获取会员账号
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 (!empty($payLog)) {
        foreach ($payLog as $v) {
            $payName[] = $v->pay_name; 
        }

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

    return false;
}

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 (!empty($shipping)) {
        return $shipping;
    }

    return false;
}

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

    if (!empty($invoice)) {
        return $invoice->invoice_status;
    }

    return false;
}

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

    if (!empty($company)) {
        return $company->com_name;
    }

    return false;
}

// 获取操作人名称
function getOperatorName($uid, $type)
{
    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 : '客户';
    } 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->name) ? $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->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->client_source;
}

// 获取自营商品型号
function getGoodsName($goods_id)
{
    $goods_info = json_decode(Redis::hget('Self_SelfGoods', $goods_id), true);
    
    return $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 == 3) {
        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 $response['data']['stock'];
    } 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;
}

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'], [6, 7])) {
            return redirect('self_order');
        }

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

    // 获取页面及订单信息 tid为订单类型:1.联营 2. 自营
    public function getOrderInfo($request, $tid)
    {
        $info = $this->getPageInfo($request);

        $map = array();

        // 页面参数
        if ($request->isMethod('get')) {
            $map['order_type']          = $request->input('order_type', '');
            $map['order_contain']       = $request->input('order_contain', '');
            $map['time_start']          = $request->input('time_start', '');
            $map['time_end']            = $request->input('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', '');
        }

        // 订单查看权限---交易员、客服、测试
        if (in_array($info['role'], [3, 4])) {
            // 筛选自己的订单
            $data['sale_id'] = $request->user->userId;
        }

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

        // 非竞调账号显示真实数据
        if ($info['username'] != 'vpadmin@ichunt.com') {
            $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'] = [1];
        } else if ($tid == 2) {
            $size = 20;
            $map['order_type_filter'] = [1, 3]; // 1. 网站 2. 京东
        } else if ($tid == 3) {
            $map['order_goods_type'] = 1; // 联营订单
            $map['order_type_filter'] = [2, 3]; // 2-ERP, 3-JD
        }

        // 获取所有的业务员 (包括经理、交易员、客服、测试)
        $perm = new PermController;

        if ($tid == 1 || $tid == 3) {
            $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 {
            $sale_list = $perm->getRoleUsers($request, '客服');
        }

        //获取订单列表
        $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'] = $size; // 当前页条数
        $data['map'] = $map;

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

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

        $info['condition']        = $map; 
        $info['sale_list']        = $sale_list; 
        $info['list']             = $response['data']['data']; 
        $info['pay_count']        = $response['data']['pay_count']; 
        $info['count']            = $response['data']['count']; 
        $info['user_count']       = $response['data']['user_count']; 
        $info['paid_user_count']  = $response['data']['paid_user_count']; 
        $info['paid_order_count'] = $response['data']['paid_order_count']; 
        $info['noreason_count']   = $response['data']['noreason_count']; 
        $info['page']             = $show; 

        return $info;
    }

    // 订单其他信息
    public function orderOtherInfoLoading(Request $request)
    {
        // 页面参数
        $map['order_type']          = $request->input('order_type', '');
        $map['order_contain']       = $request->input('order_contain', '');
        $map['time_start']          = $request->input('time_start', '');
        $map['time_end']            = $request->input('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', '');

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

        $data['k1']  = time();
        $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['map'] = $map;
echo '<pre>';
print_r(curlApi($url, $data));die;
        $response = json_decode(curlApi($url, $data), true); 
        
    }

    // 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)
    {
        $info = $this->getPageInfo($request);

        $orderModel = new OrderModel();

        return $orderModel->orderExport($request, $info); 
    }

    // 下载合同
    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])){ 
            return redirect('/prompt')->with(['message'=>"该订单不符合人工审单条件~【status:{$info['order_info']['status']}】",'url' =>$_SERVER['HTTP_REFERER'], '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) {
                errorLog(Error::E_PARAM, '订单参数有误');
                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', ''),
            ];

            $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 (empty($order_id) || empty($sale_id)) {
                errorLog(Error::E_NOT_EXISTS, '参数不存在');
                return array('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" => '#']);

        // 获取所有的业务员
        $sale_list = $this->getSales('销售');

        $perm = new PermController;

        $manager = $perm->getRoleUsers($request, '经理');
        $test = $perm->getRoleUsers($request, '测试');
        $sale_list = $perm->getRoleUsers($request, '交易员');
        $kefu = $perm->getRoleUsers($request, '客服');

        $info['manager']   = $this->filterLeave($manager);
        $info['test']      = $this->filterLeave($test);
        $info['sale_list'] = $this->filterLeave($sale_list);
        $info['kefu']      = $this->filterLeave($kefu);
        $info['sale_id']   = $request->user->userId;
        $info['role']      = $perm->getUserRole($request);

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

    // 去掉已离职人员
    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 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'] : '';
        }

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

        $response = [
            'user_mobile'                 => $mobile,
            'order_info'                  => $temp['data']['order_info'],
            'user_info'                   => $temp['data']['order_info']['user_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'=>0, 'errmsg'=>'延长失败'];
        }

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

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

    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);
                }    
            }
        });
    }

}