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

function CheckActive($menus, &$arr, $url)
{
    for ($i = 0; $i < count($menus); $i++) {
        $menu = $menus[$i];
        array_push($arr, $i);

        if (isset($menu->href) && ($menu->href == $url || ($menu->href == '/' && $url == '//')))
            return true;
        if (isset($menu->childs) && count($menu->childs) > 0) {
            $ret = CheckActive($menu->childs, $arr, $url);
            if ($ret)
                return $ret;
        }
        array_pop($arr);
    }

    return false;
}

function createMenuReal($menus, $active, $level)
{
    $subclass = ($level == 0) ? 'nav-second-level' : 'nav-third-level';

    $ret = '';
    for ($ii = 0; $ii < ($level == 0 ? 1 : 2); $ii++) {
        for ($i = 0; $i < count($menus); $i++) {
            $menu = $menus[$i];
            $act = (count($active) > $level && $active[$level] == $i) ? true : false;
            $actclass = $act ? ' class="active"' : '';
            $actmenu  = $act ? ' in': '';

            if (isset($menu->childs) && count($menu->childs) > 0) {
                if ($ii != 0 && $level > 0)
                    continue;
                $ret .= '<li'. $actclass .'><a><i class="'
                    . $menu->class . '"></i><span class="nav-label">'
                    . $menu->title . '</span><span class="fa arrow"></span></a>'
                    . '<ul class="nav ' . $subclass . ' collapse' . $actmenu . '">'
                    . createMenuReal($menu->childs, $act ? $active : [], $level + 1)
                    . '</ul></li>';
            } else {
                if ($ii != 1 && $level > 0)
                    continue;
                $ret .= '<li' . $actclass . '><a href="'. $menu->href . '"><i class="' .
                    $menu->class . '"></i><span class="nav-label">' . $menu->title . '</span></a></li>';
            }
        }
    }

    return $ret;
}

function createMenu($menus, $url)
{
    $actives = [];
    $ret = CheckActive($menus, $actives, $url);
    if (!$ret)
        $actives = [];
    return createMenuReal($menus, $actives, 0);
}

// 获取订单优惠券金额
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 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 = DB::connection('order')
                ->table('lie_order_shipping')
                ->where(['order_id' => $order_id, 'shipping_type' => 1])
                ->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 {
            $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;
}

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;

        // 获取权限菜单
        if ($request->user->email != 'admin@ichunt.com' && $request->user->userId != 1000) 
            $menus = $perm->getPermMenu($request, $menus);   

        $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();

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

        // 获取权限菜单
        if ($request->user->email != 'admin@ichunt.com' && $request->user->userId != 1000) 
            $menus = $perm->getPermMenu($request, $menus);   

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

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

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

        // 若为京东自营角色,则跳转到自营列表
        if ($info['role'] == 6) {
            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['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_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', '');
        }

        // 订单查看权限---交易员、客服、测试
        if (in_array($info['role'], [3, 4, 5])) {
            // 筛选自己的订单
            $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;

        if ($tid == 1) {
            $map['order_type_filter'] = [1];
        } else {
            $map['order_type_filter'] = [1, 3]; // 1. 网站 2. 京东
        }

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

        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 {
            $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['map'] = $map;

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

        // 分页
        $page = new Page($response['data']['count'], 10);
        $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;
    }

    // erp订单
    public function erpOrder(Request $request)
    {
        $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['order_send']          = $request->input('order_send', '');
            $map['order_source']        = $request->input('order_source', '');
        }

        $map['order_goods_type'] = 1; // 联营订单

        /* 查看ERP/JD订单 */
        $map['order_type_filter'] = [2, 3]; // 2-ERP, 3-JD

        // 非竞调账号,则查看真实数据
        if ($info['username'] != 'vpadmin@ichunt.com') {
            $map['is_fake'] = 0;
        } else {
            $map['vp_time_set'] = strtotime(Config('website.vp_time_set'));
        }

        // 获取所有的业务员 (包括经理和交易员)
        $perm = new PermController;
        $manager = $perm->getRoleUsers($request, '经理');
        $sale_list = $perm->getRoleUsers($request, '交易员');
        $test = $perm->getRoleUsers($request, '测试');

        $sale_list = array_merge($manager, $sale_list, $test);

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

        $data['k1']  = time();
        $data['k2']  = md5(md5($data['k1']).'fh6y5t4rr351d2c3bryi');
        $data['p']   = $request->input('p', 1); // 当前页码
        $data['map'] = $map;
 
        $response = json_decode(curlApi($url, $data), true); 

        // 分页
        $page = new Page($response['data']['count'], 10);
        $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['page']      = $show; 

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

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

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

        $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['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_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['order_goods_type']    = $request->input('order_goods_type', '');
        }

        // 若没有'查看线下订单'权限,则仅查看线上订单
        if (!in_array('check_offline_order', $info['userPerms'])) {
            $map['online_order'] = 1;
        }

        /* 临时添加 所有人只能查看线上订单 */
        $map['online_order'] = 1;

        if ($map['order_goods_type'] == 1) {
            $sale_name = '推送业务员';
        } else {
            $sale_name = '客服';
        }

        // 格式
        $xlsCell  = array(
            array('order_id',       '订单ID'),
            array('order_sn',       '订单编号'),
            array('user_account',   '会员账号'),
            array('consignee',      '收货人'),
            array('create_time_date', '下单日期'),
            array('create_time_sec',  '下单时间'),
            array('com_name',       '公司名称'),
            array('goods_name',     '商品型号'),
            array('goods_number',   '数量'),
            array('goods_price',    '单价'),
            array('goods_amount',   '商品小计'),
            array('goods_sum',      '商品总额'),
            array('shipping_fee',   '运费'),
            array('extra_fee',      '附加费'),
            array('coupon',         '优惠券'),
            array('order_amount',   '订单总额'),
            array('currency',       '币种'),
            array('order_type',     '订单类型'),
            array('order_status',   '订单状态'),
            array('shipping_status','发货状态'),
            array('invoice_status', '发票状态'),
            array('company_name',   '供应商'),
            array('sale_name',       $sale_name),
            array('adtags',         'adtags来源'),
            array('client_source',  '新用户来源'),
            array('cancel_reason',  '取消原因'),
            array('send_remark',    '推送备注'),
        );

        // 非竞调账号,则查看真实数据
        if ($info['username'] != 'vpadmin@ichunt.com') {
            $map['is_fake'] = 0;
        }

        $list = DB::connection('order')
                ->table('lie_order_items as it')
                ->leftJoin('lie_order as o', 'it.order_id', '=', 'o.order_id')
                ->leftJoin('lie_pay_log as p', 'it.order_id', '=', 'p.order_id')
                ->leftJoin('lie_order_invoice as i', 'it.order_id', '=', 'i.order_id')
                ->leftJoin('lie_order_extend as oe', 'oe.order_id', '=', 'i.order_id')
                ->leftJoin('lie_order_address as a', function($join) {
                    $join->on('it.order_id', '=', 'a.order_id')->where('a.address_type', '=', 1);
                })
                ->leftJoin('lie_order_shipping as s', function($join) {
                    $join->on('it.order_id', '=', 's.order_id')->where('s.shipping_type', '=', 1);
                })
                ->leftJoin('lie_user_main as u', 'it.user_id', '=', 'u.user_id')
                ->leftJoin('lie_user_company as c', 'it.user_id', '=', 'c.user_id')
                ->where(function ($query) use ($map) {
                    // 查询类型
                    if (!empty($map['order_contain'])) {
                        if ($map['order_type'] == 1) { // 订单编号
                            $query->where('o.order_sn', '=', $map['order_contain']);
                        } else if ($map['order_type'] == 2) { // 型号名称
                            $query->whereIn('it.goods_name', '=', $map['order_contain']);
                        } else { // 会员账号
                            if (preg_match('/@/', $map['order_contain'])) {
                                $query->where('u.email', '=', $map['order_contain']);
                            } else {
                                $query->where('u.mobile', '=', $map['order_contain']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($map) {
                    // 创建时间
                    if (!empty($map['time_start']) && !empty($map['time_end'])) {
                        $query->whereBetween('o.create_time', [$map['time_start'], $map['time_end']]); 
                    } else if (!empty($map['time_start'])) {
                        $query->where('o.create_time', '>', $map['time_start']);
                    } else if (!empty($map['time_end'])) {
                        $query->where('o.create_time', '<', $map['time_end']); 
                    }
                })
                ->where(function ($query) use ($map) {
                    // 订单状态
                    if (!empty($map['order_status'])) {
                        $query->whereIn('o.status', explode(',', $map['order_status']));
                    }
                })
                ->where(function ($query) use ($map) {
                    // 配送方式
                    if (!empty($map['shipping_name'])) {
                        $query->where('o.order_shipping_type', '=', $map['shipping_name']);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 订单推送业务员
                    if (!empty($map['order_send'])) {
                        $query->where('o.sale_id', '=', $map['order_send']);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 订单类型
                    if (!empty($map['order_pay_type'])) {
                        $query->where('o.order_pay_type', '=', $map['order_pay_type']);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 测试订单
                    if (empty($map['test_order'])) {            
                        $query->whereNotIn('o.user_id', $this->testMobile());
                    } 
                })
                ->where(function ($query) use ($map) {
                    // 订单来源
                    if (!empty($map['order_source_pf'])) {
                        if ($map['order_source_pf'] == 1) {
                            $query->whereRaw("FIND_IN_SET('pf=1', o.order_source)");
                        } else {
                            $query->whereRaw("FIND_IN_SET('pf=2', o.order_source)");

                        }
                    }
                })
                // ->where(function ($query) use ($map) {
                //     // adtags来源
                //     if (!empty($map['order_source_adtag'])) {
                //         $query->whereRaw('FIND_IN_SET("adtag='.$map['order_source_adtag'].'", o.order_source)');
                //     }
                // })
                ->where(function ($query) use ($map) {
                    // adtags来源
                    if (!empty($map['order_source_adtag'])) {
                        $query->where('o.order_source', 'like', '%adtag='.$map['order_source_adtag'].'%');
                    }
                })
                ->where(function ($query) use ($map) {
                    // ptag来源
                    if (!empty($map['order_source_ptag'])) {
                        $query->where('o.order_source', 'like', '%ptag='.$map['order_source_ptag'].'%');
                    }
                })
                ->where(function ($query) use ($map) {
                    // 线上订单
                    if (isset($map['online_order'])) {
                        $query->where('o.order_type', '=', $map['online_order']);
                    } 
                })
                ->where(function ($query) use ($map) {
                    // 同步状态
                    if (!empty($map['erp_order_id'])) {
                        $query->where('o.erp_order_id', '<>', '');    
                    }
                })
                ->where(function ($query) use ($map) {
                    // 竞调数据
                    if (isset($map['is_fake'])) {
                        $query->where('o.is_type', '=', $map['is_fake']);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 支付方式
                    if (!empty($map['order_payment_mode'])) {
                        switch ($map['order_payment_mode']) {
                            case '1': $order_payment_mode = '微信';break;
                            case '2': $order_payment_mode = '支付宝';break;
                            case '3': $order_payment_mode = '银联';break;
                        }
                        $query->where('p.pay_name', '=', $order_payment_mode);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 发票类型
                    if (!empty($map['order_invoice_status'])) {
                        $query->where('i.inv_type', '=', $map['order_invoice_status']);
                    }
                })
                ->where('it.status', '<>', -1)
                ->where('o.order_goods_type', '=', $map['order_goods_type'])
                ->select('it.goods_id', 'it.goods_name', 'it.goods_number', 'it.goods_price', 'it.supplier_name', 'o.order_id', 'o.order_sn', 'o.order_pay_type', 'o.order_source', 'o.create_time', 'o.status', 'o.order_amount', 'o.currency', 'o.sale_id', 'o.cancel_reason', 'i.invoice_status', 'a.consignee', 's.status as shipping_status', 'u.user_id', 'u.mobile', 'u.email', 'u.client_source', 'c.com_name', 'oe.send_remark')
                ->groupBy('it.rec_id')
                ->orderBy('o.create_time', 'DESC')
                ->get();

        if (!empty($list)) {
            // 订单数据处理
            $export = $this->exportList($list);

            $xlsName  = '订单数据导出';
            $xlslist = exportExcel($xlsName, $xlsCell, $export);
            $this->$xlslist;
        } else {
            errorLog(Error::E_NOT_EXISTS, '数据为空无法导出');
            return redirect('/prompt')->with(['message'=>"数据为空无法导出!",'url' =>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }
    }

    // 测试帐号
    public function testMobile()
    {
        $testId = array();

        $user = DB::connection('order')->table('lie_user_main')->select('user_id')->where(['is_test' => 1])->get();

        foreach ($user as $k => $v) {
            $testId[$k] = $v->user_id;
        }

        return $testId;
    }

    /**
     * 导出到Excel
     * @param  [type] $order [查询出的订单数据]
     * @return [type]        [description]
     */
    public function exportList($order)
    {
        // 订单类型
        $order_type = array(
            '1' => '全款',
            '2' => '预付款',
            '3' => '账期支付',
        );

        // 订单状态
        $order_status = array(
            '-1' => '已取消',
            '1'  => '待审核',
            '2'  => '待付款',
            '3'  => '待付尾款',
            '4'  => '待发货',
            '7'  => '部分发货',
            '8'  => '待收货',
            '10' => '交易成功',
        );

        // 订单发货状态
        $shipping_status = array(
            '-1' => '未配送',
            '1'  => '配送中',
            '2'  => '已签',
        );

        // 发票状态
        $invoice_status = array(
            '-1' => '待确认',
            '1'  => '已开票',
            '2'  => '已发货', 
            '3'  => '已签收',
        );

        $tmp = array();

        for ($i = 0; $i < count($order); $i++) {
            // 推送人
            if ($order[$i]->sale_id) {
                $sales = DB::table('user_info')->where(['userId' => $order[$i]->sale_id])->select('name')->first();
            }

            $tmp[$i]['order_id'] = $order[$i]->order_id;
            
            $tmp[$i]['goods_name'] = $order[$i]->goods_name; 
            $tmp[$i]['goods_number'] = $order[$i]->goods_number; 
            $tmp[$i]['goods_price'] = $order[$i]->goods_price;  
            $tmp[$i]['goods_amount'] = $order[$i]->goods_number*$order[$i]->goods_price; 

            if ($i > 0 && $order[$i]->order_id == $order[$i-1]->order_id) {
                $tmp[$i]['order_sn'] = '';
                $tmp[$i]['user_account'] = '';
                $tmp[$i]['consignee'] = '';
                $tmp[$i]['create_time_date'] = ''; 
                $tmp[$i]['create_time_sec'] = ''; 
                $tmp[$i]['com_name'] = ''; 
                $tmp[$i]['goods_sum'] = '';
                $tmp[$i]['shipping_fee'] = '';
                $tmp[$i]['extra_fee'] = '';
                $tmp[$i]['coupon'] = '';
                $tmp[$i]['order_amount'] = '';
                $tmp[$i]['currency'] = '';
                $tmp[$i]['order_type'] = '';
                $tmp[$i]['order_status'] = '';
                $tmp[$i]['shipping_status'] = ''; // 发货状态
                $tmp[$i]['invoice_status'] = ''; // 发票状态
                $tmp[$i]['company_name'] = '';
                $tmp[$i]['sale_name'] = '';  // 推送业务员
                $tmp[$i]['adtags'] = '';
                $tmp[$i]['client_source'] = '';
                $tmp[$i]['cancel_reason'] = '';
                $tmp[$i]['send_remark'] = '';
            } else {
                $tmp[$i]['order_sn'] = "\t".$order[$i]->order_sn."\t";
                $tmp[$i]['user_account'] = $order[$i]->mobile ? $order[$i]->mobile : $order[$i]->email;
                $tmp[$i]['consignee'] = isset($order[$i]->consignee) ? $order[$i]->consignee : '';
                $tmp[$i]['create_time_date'] = date('Y-m-d', $order[$i]->create_time); 
                $tmp[$i]['create_time_sec'] = date('H:i:s', $order[$i]->create_time); 
                $tmp[$i]['com_name'] = isset($order[$i]->com_name) ? $order[$i]->com_name : ''; 
                $tmp[$i]['goods_sum'] = $this->getOrderPrice($order[$i]->order_id, 1);
                $tmp[$i]['shipping_fee'] = $this->getOrderPrice($order[$i]->order_id, 3);
                $tmp[$i]['extra_fee'] = $this->getOrderPrice($order[$i]->order_id, 2);
                $tmp[$i]['coupon'] = $this->getOrderPrice($order[$i]->order_id, -4);
                $tmp[$i]['order_amount'] = $order[$i]->order_amount;
                $tmp[$i]['currency'] = $order[$i]->currency == 1 ? 'RMB' : 'USD';
                $tmp[$i]['order_type'] = !empty($order[$i]->order_pay_type) ? $order_type[$order[$i]->order_pay_type] : '未知';
                $tmp[$i]['order_status'] = !empty($order[$i]->status) ? $order_status[$order[$i]->status] : '未知';
                $tmp[$i]['shipping_status'] = !empty($order[$i]->shipping_status) ? $shipping_status[$order[$i]->shipping_status] : '无发货信息'; // 发货状态
                $tmp[$i]['invoice_status'] = !empty($order[$i]->invoice_status) ? $invoice_status[$order[$i]->invoice_status] : '无发票信息'; // 发票状态
                $tmp[$i]['company_name'] = $order[$i]->supplier_name;
                $tmp[$i]['sale_name'] = isset($sales) ? $sales->name : '';  // 推送业务员
                $tmp[$i]['adtags'] = $order[$i]->order_source;
                $tmp[$i]['client_source'] = $order[$i]->client_source;
                $tmp[$i]['cancel_reason'] = $order[$i]->cancel_reason;
                $tmp[$i]['send_remark'] = $order[$i]->send_remark;
            }

            unset($sales);     
        }

        return $tmp;
    }

    // 订单金额展示
    public function getOrderPrice($order_id, $type)
    {
        $price = DB::connection('order')->table('lie_order_price')->where('order_id', '=', $order_id)->where('price_type', '=', $type)->select('price')->first();

        return $price ? $price->price : 0;
    }

    // 下载合同
    public function ajaxDownloadContract(Request $request) 
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id');
            // 操作记录
            $log['order_id'] = $order_id;
            $log['operator_id'] = $request->user->userId;
            $log['operator_type'] = 2;
            $log['event'] = '下载合同';
            $log['ip'] = get_client_ip();
            $log['create_time'] = time();
            $actionLog = DB::connection('order')->table('lie_order_action_log')->insert($log);

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

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

            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)
    {
        $data = $this->orderDetail($request, $id);

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

        return view($view_id, $data);
    }

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

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

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

        $extend = DB::connection('order')->table('lie_order_extend')->where(['order_id' => $order_id, 'order_type' => 3])->first();

        $data['extend'] = $extend ? $extend : ''; 

        return $data;
    }

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

    // 调价
    public function changeOrder(Request $request, $id)
    {
        $info = $this->orderDetail($request, $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') OR !$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', ''),
                "status"         => $request->input('order_status', ''),
                "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,
            ];

            $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'=>'驳回失败');
            } 

            // 操作记录
            $log['order_id'] = $order_id;
            $log['operator_id'] = $request->user->userId;
            $log['operator_type'] = 2;
            $log['event'] = '审核驳回';
            $log['ip'] = get_client_ip();
            $log['create_time'] = time();
            DB::connection('order')->table('lie_order_action_log')->insert($log);

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

        // 获取所有的业务员
        $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']['adjust_count'] >= 2) {
            errorLog(Error::E_FORBIDDEN, '该订单无法再进行调价操作');
            return redirect('/prompt')->with(['message'=>"该订单无法再进行调价操作",'url' =>'/details/'.$id, 'jumpTime'=>3,'status'=>false]);
        }

        $data['confirm_time'] = 0;
        $data['pay_time'] = 0;
        $data['status'] = 1;
        // $data['sale_id'] = 0; // 再次调价调整sale_id

        $update = DB::connection('order')->table('lie_order')->where('order_id', $id)->update($data);

        if (!$update) {
            errorLog(Error::E_UPDATE_FAILED, '调价操作更新数据失败');
            return redirect('/prompt')->with(['message'=>"调价操作更新数据失败!",'url' =>'/details/'.$id, 'jumpTime'=>3,'status'=>false]);
        }    

        $extend = DB::connection('order')->table('lie_order_extend')->where(['order_id' => $id])->first();
        
        if ($extend) {
            // 调价失败临时表状态更改
            DB::connection('order')->table('lie_order_extend')->where(['order_id' => $id])->update(['status' => 0]);
        }

        // 操作记录
        $log['order_id'] = $id;
        $log['operator_id'] = $request->user->userId;
        $log['operator_type'] = 2;
        $log['event'] = '再次调价';
        $log['ip'] = get_client_ip();
        $log['create_time'] = time();
        DB::connection('order')->table('lie_order_action_log')->insert($log);

        return redirect('/change/'.$id);  
    }

    // 填写订单取消原因
    public function ajaxInputCancelReason(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id');
            $cancel_reason = $request->input('cancel_reason');

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

            if (!$update) return ['errcode' => -1, 'errmsg' => '填写订单取消原因失败'];
        
            // 操作记录
            $log['order_id'] = $order_id;
            $log['operator_id'] = $request->user->userId;
            $log['operator_type'] = 2;
            $log['event'] = '填写订单取消原因:'.$cancel_reason;
            $log['ip'] = get_client_ip();
            $log['create_time'] = time();
            DB::connection('order')->table('lie_order_action_log')->insert($log);

            return ['errcode' => 0, 'errmsg' => '填写订单取消原因成功'];
        }
    }

    // 申请再次调价
    public function applyAdjust(Request $request, $id)
    {
        $info = $this->orderDetail($request, $id);

        if($info['order_info']['status'] == 3 || $info['order_info']['status'] == 4){
            return redirect('/prompt')->with(['message'=>"客户已经支付了,无法进行调价了.",'url' =>'/check/'.$id, 'jumpTime'=>3,'status'=>false]);
        }

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

            } elseif ($info['order_info']['status'] == 2 && $info['order_info']['adjust_count'] <= 2 && !in_array($info['role'], array(1, 2))) {
                return redirect('/prompt')->with(['message'=>"没有权限进行二次调价",'url' =>'/check/'.$id, 'jumpTime'=>3,'status'=>false]);
            }
        }

        if ($request->isMethod('post')) {
            $remark = $request->input('adjust_remark', '', 'trim');
            $order_id = $info['order_info']['order_id'];

            if (empty($remark)) {
                return array('errcode' => -1, 'errmsg' => '调价原因不能为空');
            }

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

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

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

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

            if ($temp['err_code'] == 0) {
                return array('errcode'=>0,'errmsg'=>'申请成功');
            } else {
                return array('errcode'=>0,'errmsg'=>'申请失败');
            }
        }

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

     // 审核
    public function check(Request $request, $id)
    {
        $data = $this->orderDetail($request, $id);

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

        $perm = new PermController;

        $manager = $perm->getRoleUsers($request, '经理');
        $sale_list = $perm->getRoleUsers($request, '交易员');

        // $manager = array();

        // 过滤业务员,并新建经理数组
        // if (!empty($managerId)) {
        //     foreach ($sale_list as $k=>$v) {
        //         foreach ($managerId as $id)
        //         if ($v->userId == $id) {
        //             $manager[$v->userId] = $v->name;

        //             array_splice($sale_list, $k, 1);
        //         }
        //     }
        // }

        $data['sale_list'] = $sale_list;
        $data['manager']   = $manager;

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

    // 审核ajax
    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;

            $order_status = $request->input('order_status', ''); //审核通过 2  审核不通过(即取消订单) -1
            $cancel_reason = $request->input('cancel_reason', '');
            $order_sn = $request->input('order_sn', '');

            if ($order_status == -1 && !$cancel_reason) {
                return array('errcode'=>1, 'errmsg'=>'审核不通过的原因不可为空!');
            }

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

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

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

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

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

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

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

    //取消订单(仅限审核通过,未付款前)
    public function cancelPay(Request $request, $id)
    {
       if($request->isMethod('post')){
            $order_id = $request->input('order_id');
            $cancel_reason = $request->input('cancel_reason');
            $operator_id = $request->user->userId;

            if (!$order_id) {
                errorLog(Error::E_NOT_EXISTS, '订单不存在');
                return array('errcode'=>Error::E_NOT_EXISTS,'errmsg'=>'订单不存在~');
            }

            if (!$cancel_reason) {
                errorLog(Error::E_NOT_EXISTS, '取消订单的原因不可为空');
                return array('errcode'=>Error::E_NOT_EXISTS,'errmsg'=>'取消订单的原因不可为空~');
            }

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

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

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

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

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

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

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

    // 对账
    public function checkPay(Request $request, $id)
    {
        $info = $this->orderDetail($request, $id);

        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 changeShipping(Request $request, $id='')
    {
        if($request->isMethod('post')){
            $data['map'] = $request->input();

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

        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['id'] = $request->input('order_id','');
            $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);

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

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

        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,
        ];

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

        return $response;
    }

    // 取消订单
    public function ajaxSelfCancel(Request $request)
    {
        if ($request->isMethod('post')) {
            $order_id = $request->input('order_id');
            $cancel_reason = $request->input('reason');
            $operator_id = $request->user->userId;

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

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

            $resData = array("pf"=>1, "k1"=>$check['k1'], "k2"=>$check['k2'], "order_id"=>$order_id, "cancel_reason"=>$cancel_reason, 'operator_id'=>$operator_id);
            
            $temp = json_decode(curlApi($url, $resData, "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')) {
            $order_id = $request->input('order_id', '');
            $serial_number = $request->input('serial_number', '');
            $operator_id = $request->user->userId;

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

            $data['order_id'] = $order_id;
            $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'=>'操作失败');
            }
        }

        $info = $this->orderDetail($request, $id);
        $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);

        $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);
    }
    
    /**
     * 定时任务:提前一天上午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;
                    }
                }
            }
        }
    }

    // 定时任务:每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('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) {
                        $log = array(); 
                        
                        // 记录
                        $log['order_id'] = $v->order_id;
                        $log['operator_id'] = 0;
                        $log['operator_type'] = 3;
                        $log['event'] = '取消订单,取消原因:超时未付款';
                        $log['ip'] = 0;
                        $log['create_time'] = time();
                        DB::connection('order')->table('lie_order_action_log')->insert($log);

                        continue;
                    }
                }
            }
        }
    }

    // 延长付款时间
    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'=>'延长失败'];
        }

        // 操作记录
        $log['order_id'] = $order_id;
        $log['operator_id'] = $request->user->userId;
        $log['operator_type'] = 2;
        $log['event'] = '延长付款时间,截止到:'.date('Y-m-d H:i:s', $delay_time);
        $log['ip'] = get_client_ip();
        $log['create_time'] = time();
        $actionLog = DB::connection('order')->table('lie_order_action_log')->insert($log);

        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'); // 一年

        // 订单数量
        $halfCount = DB::connection('order')->table('lie_order')
                    // ->where('order_goods_type', 1)
                    // ->where('order_type', 1)
                    ->whereNotIn('user_id', $this->testMobile())
                    ->where('is_type', 0)
                    ->whereBetween('create_time', [$half, $current])
                    ->count();
        echo '半年订单数:'.$halfCount.'<br>';
                    
        $yearCount = DB::connection('order')->table('lie_order')
                    ->whereNotIn('user_id', $this->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', $this->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', $this->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', $this->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', $this->testMobile())
                    ->where('o.is_type', 0)
                    ->where('i.inv_type', 3)
                    ->whereBetween('o.create_time', [$year, $current])
                    ->count();        
        echo '一年增票订单数:'.$yearAddInvoice.'<br>';       
    }

}