<?php
declare (strict_types = 1);
namespace app\system\controller\v1;

use app\BaseController;
use app\model\api\MemberDetail;
use app\model\system\Order as OrderModel;
use app\model\system\OrderInfo;
use app\model\system\OrderInfoAsw;
use app\model\system\OrderInfoDd;
use app\model\system\OrderMono;
use app\Request;
use library\services\UtilService;
use library\utils\Region;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;

// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-09-06 21:53
// +----------------------------------------------------------------------

class Order extends  BaseController
{
    /**
     * 获取订单数据
     * @param Request $request
     */
    public function getOrderList(Request $request){
        $pageSize = 20;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['order_id',''],
                ['mono',''],
                ['platform_id',''],
                ['warehouse_id',''],
                ['data',[]],
                ['orderType',''],
                ['timeType',''],
                ['uid','']
            ],$request
        );
        $where = $post;
        $order = new OrderModel;
        list($pageCount,$data) = $order->getList($post['page'],$where,$pageSize,'id desc');
        $result = UtilService::getParam([
            "id",
            ['time','time','date("Y-m-d H:i:s",$1)'],
            "order_id",
            "mobile",
            "avatar",
            "order_count",
            "all_price",
            "status",
            "platfrom_name",
            "ck_name",
            "exp_name",
            "site_name",
            "pro_title",
            "send_count",
            "uid",
            "pro_img",
            "mono",
            "err_msg"
            ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }


    public function getOrderPushList(Request $request) {
        $pageSize = 20;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['order_id',''],
                ['mono',''],
                ['platform_id',''],
                ['warehouse_id',''],
                ['data',[]],
                ['orderType',''],
                ['timeType','']
            ],$request
        );
        $where = $post;
        $order = new OrderModel;
        list($pageCount,$data) = $order->getPushList($post['page'],$where,$pageSize,'id desc');
        $result = UtilService::getParam([
            "id",
            ['time','time','date("Y-m-d H:i:s",$1)'],
            "order_id",
            "mobile",
            "avatar",
            "order_count",
            "all_price",
            "status",
            "platfrom_name",
            "ck_name",
            "exp_name",
            "site_name",
            "pro_title",
            "push_count",
            "pro_img",
            "is_push",
            "pro_img",
            "mono",
            "err_msg"
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    /**
     * 导出数据
     * @param Request $request
     */
    public function orderDown(Request $request) {
        $post = UtilService::getMore([['id','','empty','参数错误'],],$request);
        $where = [];
        $idsAr = explode(',',$post['id'].'');
        $where['id'] = $idsAr;
        $data = (new OrderInfo)->getAllList($where,'id desc');
        $tAr = [];
        foreach ($data as $v) {
            $d = [];
            $d['name']          = $v['name'];
            $d['mobile']        = $v['mobile'];
            $d['out_order_id']  = $v['out_order_id'];
            $d['in_order_id']   = $v['in_order_id'];
            $d['address']       = $v['address'];
            $d['exp_name']      = $v['exp_name'];
            $d['exp_number']    = $v['exp_number'];
            $d['pro_name']      = $v['pro_name'];
            $d['pro_code']      = $v['csno'];
            $d['pro_price']     = $v['pro_price'];
            $d['platform_name'] = $v['platform_name'];
            $d['time']     =date('Y-m-d H:i:s',$v['time']);
            $d['count']    = 1;
            $d['money'] = $v['money'];
            $d['exp_price'] = $v['exp_price'];
            $tAr[] = $d;
        }
        return app('json')->success($tAr);
    }

    /**
     * 子订单数据
     * @param Request $request
     */
    public function orderSubItem(Request $request) {
        $pageSize = 20;
        $post =  UtilService::getMore(
            [
                ['id',''],
                ['page',1],
                ['order_id',''],
                ['mobile',''],
                ['name','']
            ],$request
        );
        $where = $post;
        $where['id']     = $post['id'];
        list($pageCount,$data) = (new OrderInfo)->getList($post['page'],$where,$pageSize,"*","id desc");
        $result = UtilService::getParam([
            "id",
            "exp_name",
            "order_id",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "is_push",
            "mono",
            "time",
            "send_time",
            "exp_number",
            "msg_err",
            "money",
            "status",
            "pro_title"
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    /**
     * 售后列表
     * @param Request $request
     */
    public function orderMonoList(Request $request) {
        $pageSize = 10;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['timeType',''],
                ['aswStatus','']
            ],$request
        );
        $tx = new OrderInfoAsw();
        $where = $post;
        list($pageCount,$data) = $tx->getList($post['page'],$where,$pageSize,"*");
        $result = UtilService::getParam([
            "id",
            "o_id",
            "mono",
            "status",
            "cl_time",
            "cl_admin_time",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "time",
            "send_time",
            "exp_number",
            'msg_mono',
            'msg_img',
            'admin_id',
            "exp_name"
        ],$data);
        foreach ($result as $k=>$v){
            $result[$k]['msg_img_ar'] =  empty($v["msg_img"])?[]:explode(",",$v["msg_img"]);
        }
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }
    /**
     * 订单撤销数据
     * @param Request $request
     */
    public function orderMonoCancel(Request $request){
        $post =  UtilService::getMore(
            [
                ['id',"","empty","参数错误"],
                ['mono',""]
            ],$request
        );
        (new OrderInfoAsw)->where('id',$post['id'])->delete();
        return app('json')->success('撤销成功');
    }
    public function orderMonoHandle(Request $request){
        $post =  UtilService::getMore(
            [
                ['id',"","empty","参数错误"],
                ['msg_mono',""],
                ['msg_img',""],
            ],$request
        );
        $post["admin_time"]=NOW_TIME;
        $post["status"]=1;
        $post["admin_id"]=$request->adminInfo["id"];
        $id = $post['id'];
        unset($post['id']);
        (new OrderInfoAsw)->where('id',$id)->save($post);
        return app('json')->success('处理成功');
    }


    /**
     * 底单申请列表
     * @param Request $request
     */
    public function orderDdList(Request $request) {
        $pageSize = 10;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['timeType',''],
                ['aswStatus','']
            ],$request
        );
        $tx = new OrderInfoDd();
        $where = $post;
        list($pageCount,$data) = $tx->getList($post['page'],$where,$pageSize,"*");
        $result = UtilService::getParam([
            "id",
            "o_id",
            "mono",
            "status",
            "cl_time",
            "cl_admin_time",
            "out_order_id",
            "name",
            "mobile",
            "address",
            "time",
            "send_time",
            "exp_number",
            'msg_mono',
            'msg_img',
            'admin_id',
            "exp_name"
        ],$data);
        foreach ($result as $k=>$v){
            $result[$k]['msg_img_ar'] =  empty($v["msg_img"])?[]:explode(",",$v["msg_img"]);
        }
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }
    /*
     * 底单申请处理
     */
    public function orderDdHandle(Request $request){
        $post =  UtilService::getMore(
            [
                ['id',"","empty","参数错误"],
                ['msg_img',""],
            ],$request
        );
        $post["admin_time"]=NOW_TIME;
        $post["status"]=1;
        $post["admin_id"]=$request->adminInfo["id"];
        $id = $post['id'];
        unset($post['id']);
        (new OrderInfoDd)->where('id',$id)->save($post);
        return app('json')->success('处理成功');
    }


    /**
     * 退款功能
     * @param Request $request
     */
    public function orderTui(Request $request){
        $post =  UtilService::getMore(
            [
                ['o_id',"","empty","参数错误"],
                ['mono',""],
            ],$request
        );
        //订单
        $order = (new OrderModel)->where('id',$post['o_id'])->find();
        if(empty($order)) {
            return app('json')->fail("找不到订单，无法退款");
        }
        if($order['status'] == 0 || $order['status'] == -2) {
            return app('json')->fail("当前订单状态，无法退款！");
        }
        try {
            if (empty($order['all_price'])) {
                return app('json')->fail('抱歉,无退款的订单');
            }
            $count = (new OrderInfo)->where('o_id',$order['id'])->count();
            //退款金额
            $book = (new MemberDetail)->refund($order['all_price'],$order['uid'],[
                'order_id'  =>  $order['order_id'],
                'count'     =>  $count,
                'money'     =>  $order['all_price']
                ],$order['sassid']);
            //改订单状态
            (new OrderModel)->where('id',$order['id'])->save(['status' => -2]);
            (new OrderInfo)->where('o_id', $order['id'])->save(['status'=> -2]);
            //生成操作记录
            (new OrderMono)->insert([
                'o_id'      => $order['id'],
                'mono'      => "退款金额:{$order['all_price']}，退款笔数:{$count}".(empty($post['mono']) ? '' : ('，反馈内容:'.$post['mono'])),
                'time'      => time(),
                'admin_id'  => $request->adminInfo["id"],
                'type'      => 'refund',
                'money'     => $order['all_price']
            ]);
            return app('json')->success('退款成功');
        } catch (DbException $db) {
            return app('json')->success('操作失败');
        }
    }

    /**
     * 子订单退款
     * @param Request $request
     */
    public function subOrderTui(Request $request){
        $post =  UtilService::getMore(
            [
                ['id',"","empty","参数错误"],
                ['mono',""],
            ],$request
        );
        //订单
        $order = (new OrderInfo)->where('id',$post['id'])->find();
        if(empty($order)) {
            return app('json')->fail("找不到订单，无法退款");
        }
        if($order['status'] == 0 || $order['status'] == -2) {
            return app('json')->fail("当前订单状态，无法退款！");
        }
        try {
            //退款金额
            $res1 = (new MemberDetail)->refund($order['money'],$order['uid'],[
                'order_id'  =>  $order['in_order_id'],
                'count'     =>  1,
                'money'     =>  $order['money']
            ],$order['sassid']);
            $res2 = (new OrderInfo)->where('id', $order['id'])->save(['status'=>-2]);
            //生成操作记录
            $res3 = (new OrderMono)->insert([
                'o_id'       => $order['id'],
                'mono'      => "退款金额:{$order['money']}，退款笔数:1".(empty($post['mono']) ? '' : ('，反馈内容:'.$post['mono'])),
                'time'      => time(),
                'admin_id'  => $request->adminInfo["id"],
                'type'      => 'sub_refund',
                'money'     => $order['money']
            ]);
            if($res1 && $res2 && $res3){
                return app('json')->success('退款成功');
            }
        } catch (DbException $db) {
            return app('json')->success('操作失败');
        }
    }

    /**
     * 订单异常
     * @param Request $request
     */
    public function orderYc(Request $request) {
        $post =  UtilService::getMore(
            [
                ['o_id',"","empty","参数错误"],
                ['mono',""],
            ],$request
        );
        //订单
        $order = (new OrderModel)->where('id',$post['o_id'])->find();
        if(empty($order)) {
            return app('json')->fail("找不到订单，无法处理");
        }
        try {
            //改订单
            (new OrderModel)->where('id',$order['id'])->save([
                'status' => 9,
                "err_msg" => $post['mono']
            ]);
            //生成操作记录
            (new OrderMono)->insert([
                'o_id'       => $order['id'],
                'mono'      => "异常处理内容:".$post['mono'],
                'time'      => time(),
                'admin_id'  => $request->admin['id'],
                'type'      => 'yc',
                'money'     => 0
            ]);
            return app('json')->success('处理成功');
        } catch (DbException $db) {
            return app('json')->success('操作失败');
        }
    }

    /**
     * 订单发货
     * @param Request $request
     */
    public function orderFahuo(Request $request) {
        $post =  UtilService::getMore(
            [
                ['o_id',"","empty","参数错误"],
                ['mono',""],
            ],$request
        );
        //订单
        $order = (new OrderModel)->where('id',$post['o_id'])->find();
        if(empty($order)) {
            return app('json')->fail("找不到订单，无法处理");
        }
        if($order['status'] < 1) {
            return app('json')->fail("当前订单无法处理");
        }
        $monoAr = explode(PHP_EOL,$post['mono']);
        if(empty($monoAr)) {
            return app('json')->fail("无发货数据");
        }
        $tAr = [];
        $orderInfo = new OrderInfo;
        foreach ($monoAr as $v) {
            $bool = false;
            $exp = explode('-',$v);
            if(count($exp) == 2) {
                $mobile = $exp[0];
                $number = $exp[1];
                if(!empty($number)) {
                    $bool = $orderInfo
                        ->where('o_id',$order['id'])
                        ->where('mobile',$mobile)
                        ->save(['exp_number'=>$number,'status'=>2,'send_time'=>time()]);
                }
            }
            $tAr[] = ['txt'=>$v,'status'=>$bool];
        }

        if($order['status'] == 1) {
            (new OrderModel)->where('id',$post['o_id'])->save([
               'status' => 2
            ]);
        }

        return app('json')->success($tAr);
    }

    /**
     * 揽件预警
     * @param Request $request
     */
    public function orderWarningList(Request $request){
        $pageSize = 20;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['orderType',''],
                ['order_id',''],
                ['exp_number',''],
                ['warehouse_id',''],
                ['data',[]]
            ],$request
        );
        $where = $post;
        list($pageCount,$data) = (new OrderInfo)->getWarningList($where,$post['page'],$pageSize);
        $result = UtilService::getParam([
            'id',
            'order_id',
            'in_order_id',
            ['pay_time','pay_time','date("Y-m-d H:i:s",$1)'],
            ['send_time','send_time','date("Y-m-d H:i:s",$1)'],
            ['in_send_time','send_time','time() - $1'],
            'exp_name',
            'exp_number',
            'name',
            'mobile',
            'address',
            'site_name',
            'warehouse_name',
            'user_mobile',
            'user_avatar'
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    public function queryOrderNum($id)
    {
        //3天内的 | 8小时查询一次
        $time = strtotime('-3 day');
        //8小时之内不查询
        $timeLast = strtotime('-8 hour');
        //8小时查询一次
        $time2 = strtotime('-8 hour');
        $count = (new OrderInfo)
            ->where('status', 2)
            ->where('exp_status', 0)
            ->where('send_time', '<', $timeLast)
            ->where('send_time', '>', $time)
            ->where('exp_g_time', '<=', $time2)
            ->where('warehouse_id', $id)
            ->count();
        return app('json')->success(['count' => $count]);
    }

    public function expInquiry(Request $request)
    {
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['id','']
            ],$request
        );
        //3天内的 | 8小时查询一次
        $time = strtotime('-3 day');
        //8小时之内不查询
        $timeLast = strtotime('-8 hour');
        //8小时查询一次
        $time2 = strtotime('-8 hour');
        $data = (new OrderInfo)
            ->where('status', 2)
            ->where('exp_status', 0)
            ->where('send_time', '<', $timeLast)
            ->where('send_time', '>', $time)
            ->where('exp_g_time', '<=', $time2)
            ->where('warehouse_id', $post['id'])
            ->page($post['page'], 100)
            ->select()
            ->toArray();
        foreach ($data as $v) {
            file_put_contents("log/exp_" . date("Ymd") . ".log", $v['exp_number'] . ' ' . $v['name'] . ' ' . $v['address'] . ' 发货时间:' . date('Y-m-d H:i:s', $v['send_time']) . PHP_EOL, FILE_APPEND);
            $this->setActionData($v);
        }
        file_put_contents("log/exp_" . date("Ymd") . ".log", "-----------------------------------------页码[" . $post['page'] . "]-------------------------------------", FILE_APPEND);
        return app('json')->success('查询物流成功！');
    }

    /**
     * @param $data
     */
    private function setActionData($oData){
        $exp = new \library\lib\expInfo;
        $ocode = Db::name("express")->where('id',$oData['exp_id'])->value('ocode');
        $data = $exp->showapiExpInfo(trim($oData['exp_number']),empty($ocode) ? 'auto' : $ocode);
        if(empty($data['showapi_res_body'])) {
            OrderInfo::where('id',$oData['id'])->save(['exp_g_time' => time()]);
            return ;
        }
        $expData = empty($data['showapi_res_body']['data']) ? [] : $data['showapi_res_body']['data'];
        $signFor = 0;
        $signTime = 0;
        $inAr = ['揽收','收件'];
        foreach ($expData as $v) {
            $bAr = array_filter($inAr,function ($item) use($v){
                if(strpos($v['context'],$item) !== false) {
                    return true;
                }
                return false;
            });
            if(!empty($bAr)) {
                $signFor = 1;
                $signTime = strtotime($v['time']);
                break;
            }
        }
        //超过5次信息算【揽收】
        if(count($expData) > 2) {
            $signFor = 1;
            $signTime =  time();
        }
        if($signFor) {
            //存储数据
            OrderInfo::where('id',$oData['id'])
                ->save([
                    'exp_status' => $signFor,
                    'exp_time'   => $signTime,
                    'exp_msg'    =>json_encode($expData),
                    'exp_g_time' => time()
                ]);
        } else {
            OrderInfo::where('id',$oData['id'])->save(['exp_g_time' => time()]);
        }
        file_put_contents("log/exp_" . date("Ymd") . ".log", '['.$oData['id'].']已查询物流，' . ($signFor ? '已揽件' : '未揽件').PHP_EOL, FILE_APPEND);
    }
}
