<?php
declare (strict_types=1);

namespace app\system\controller;

use app\BaseController;
use app\model\api\MemberDetail;
//use app\model\api\Express;
use app\model\api\Order as OrderModel;
use app\model\api\ShowTemplateOrder as ShowTemplateOrderModel;
use app\model\api\OrderInfo;
use app\model\api\OrderMono;

use app\Request;
use library\services\UtilService;
use library\utils\Region;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;
use function GuzzleHttp\Psr7\str;

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

class Order extends BaseController
{

    /**
     * 获取订单数据
     * @param Request $request
     * @return mixed
     * @throws DbException
     */
    public function list(Request $request)
    {
        $pageSize = 50;
        $post = UtilService::getMore(
            [
                ['page', 1],
                ['uid',0],
                ['uip',''],
                ['order_id', ''],
                ['status',''],
                ['type',''],
                ['shop_id',''],
                ['is_ip_buy',''],
                ['mobile',''],
                ['name',''],
                ['tel',''],
                ['time',[]],
            ], $request
        );
        $where = [];
        if(!empty($post['uid'])){
            $where[]=["o.uid","=",$post['uid']];
        }else if(!empty($post['uip'])){
            $m  = Db::name("user")->where("uip",$post['uip'])->find();
            if(!empty($m)) {
                $where[]=["o.uid","=",$m['uid']];
            }
        }else if(!empty($post['mobile'])){
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["o.uid","=",$m['uid']];
            }
        }
        if(!empty($post['order_id'])){
            $where[]=["o.order_id","=",$post['order_id']];
        }
        if(in_array((string)$post['status'],["0","1","2","3","-1"])){
            $where[]=["o.status","=",(int)$post['status']];
        }
        if($post['is_ip_buy']!="" && in_array((string)$post['is_ip_buy'],["0","1"])){
            $where[]=["o.is_ip_buy","=",(int)$post['is_ip_buy']];
        }
        if($post['type']!="" && in_array((string)$post['type'],["shop","send"])){
            $where[]=["o.type","=",$post['type']];
        }
        if(!empty($post['name'])){
            $where[]=["o.name","=",$post['name']];
        }
        if(!empty($post['tel'])){
            $where[]=["o.tel","=",$post['tel']];
        }
        if(!empty($post['shop_id'])){
            $where[]=["o.shop_id","=",$post['shop_id']];
        }
        //创建时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $where[]=["o.time","between","{$startTime},{$endTime}"];
        }
        $order = new OrderModel;
        $data  = $order
                ->alias("o")
                ->field("o.*,u1.mobile,u1.uip,u1.nickname")
                ->leftJoin("user u1","u1.uid = o.uid")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("o.id","desc")
                ->select()
                ->toArray();
        $pageCount = $order->alias("o")->where($where)->count();
        $result = UtilService::getParam([
            "id",
            "order_id",
            "uid",
            "uip",
            "mobile",
            "nickname",
            
            "total_money",
            "all_money",
            "pay_money",
            "postage",
            "name",
            "tel",
            "address",
            "coupon_money",
            "is_ip_buy",
            "status",
            "score",
            "give_score",
            "mono",
            "express_num",
            "type",
            "shop_id",
            "content",
            ['time', 'time', 'date("Y-m-d H:i:s",$1)'],
            ['pay_time', 'pay_time', function ($item) {
                return empty($item) ? "-" : date('Y-m-d H:i:s', $item);
            }],
            ['fa_time', 'fa_time', function ($item) {
                return empty($item) ? "-" : date('Y-m-d H:i:s', $item);
            }],
            ['ok_time', 'ok_time', function ($item) {
                return empty($item) ? "-" : date('Y-m-d H:i:s', $item);
            }],
            
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 搜索统计
     */
    public function total(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['uid',0],
                ['uip',''],
                ['mobile',''],
                ['tel',''],
                ['name',''],
                ['type',''],
                ['shop_id',''],
                ['order_id', ''],
                ['status',''],
                ['is_ip_buy',''],
                ['time',[]],
            ], $request
        );
        $order       = new OrderModel;
        $totalWhere = [];
        if(!empty($post['uid'])){
            $totalWhere[]=["uid","=",$post['uid']];
        }else if(!empty($post['uip'])){
            $m  = Db::name("user")->where("uip",$post['uip'])->find();
            if(!empty($m)) {
                $totalWhere[]=["uid","=",$m['uid']];
            }
        }else if(!empty($post['mobile'])){
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $totalWhere[]=["uid","=",$m['uid']];
            }
        }
        if(!empty($post['order_id'])){
            $totalWhere[]=["order_id","=",$post['order_id']];
        }
        if($post['is_ip_buy']!="" && in_array((string)$post['is_ip_buy'],["0","1"])){
            $totalWhere[]=["is_ip_buy","=",(int)$post['is_ip_buy']];
        }
        if($post['type']!="" && in_array((string)$post['type'],["shop","send"])){
            $totalWhere[]=["type","=",$post['type']];
        }
        if(in_array((string)$post['status'],["0","1","2","3","-1"])){
            $totalWhere[]=["status","=",$post['status']];
        }
        if(!empty($post['name'])){
            $totalWhere[]=["name","=",$post['name']];
        }
        if(!empty($post['tel'])){
            $totalWhere[]=["tel","=",$post['tel']];
        }
        if(!empty($post['shop_id'])){
            $totalWhere[]=["shop_id","=",$post['shop_id']];
        }
        //创建时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $totalWhere[]=["time","between","{$startTime},{$endTime}"];
        }
        foreach($totalWhere as $k=>$v){
            if($v[0]=="status"){
                array_splice($totalWhere,$k,1);
            }
        }
        //全部
        $orderCount = $order->where($totalWhere)->count();
        //待支付
        $waitPayWhere   = $totalWhere;
        $waitPayWhere[] = ["status","=","0"];
        $waitPayCount   = $order->where($waitPayWhere)->count();
        //待发货
        $waitSendWhere    = $totalWhere;
        $waitSendWhere[]  = ["status","=",1];
        $waitSendCount    = $order->where($waitSendWhere)->count();
        //待收货
        $waitAcceptWhere    = $totalWhere;
        $waitAcceptWhere[]  = ["status","=",2];
        $waitAcceptCount    = $order->where($waitAcceptWhere)->count();
        //已完成
        $okWhere    = $totalWhere;
        $okWhere[]  = ["status","=",3];
        $okCount    = $order->where($okWhere)->count();
        
        
        //已取消
        $closeWhere    = $totalWhere;
        $closeWhere[]  = ["status","=",-1];
        $closeCount    = $order->where($closeWhere)->count();
        return app('json')->success([
            'orderCount' => $orderCount,
            'waitPayCount'=> $waitPayCount,
            'waitSendCount' => $waitSendCount,
            'waitAcceptCount'=>$waitAcceptCount,
            'okCount'=>$okCount,
            'closeCount' => $closeCount,
        ]);
    }

    /**
     * 订单详情
     * @param Request $request
     */
    public function info(Request $request)
    {
        [$id] = UtilService::getMore([
            ['id', '', 'empty', '参数错误'],
        ], $request, true);
        $oData = (new OrderModel)
                ->alias("o")
                ->field("o.*,u1.mobile,u1.uip,u1.nickname")
                ->leftJoin("user u1","u1.uid = o.uid")
                ->where("o.id",$id)
                ->find();
        if (empty($oData)) {
            return app('json')->fail('找不到订单号');
        }
        //主订单数据
        $data                 = [];
        $data['id']           = $oData['id'];
        $data['order_id']     = $oData['order_id'];
        $data['uid']          = $oData['uid'];
        $data['mobile']       = $oData['mobile'];
        $data['nickname']     = $oData['nickname'];
        $data['total_money']  = $oData['total_money'];
        $data['all_money']    = $oData['all_money'];
        $data['pay_money']    = $oData['pay_money'];
        $data['postage']      = $oData['postage'];
        $data['name']         = $oData['name'];
        $data['tel']          = $oData['tel'];
        $data['address']      = $oData['address'];
        $data['coupon_money'] = $oData['coupon_money'];
        $data['is_ip_buy']    = $oData['is_ip_buy'];
        $data['status']       = $oData['status'];
        $data['score']        = $oData['score'];
        $data['give_score']   = $oData['give_score'];
        $data['mono']         = $oData['mono'];
        $data['express_num']  = $oData['express_num'];
        $data['content']      = $oData['content'];
        $data['time']         = date('Y-m-d H:i:s', $oData['time']);
        $data['pay_time']     = empty($oData['pay_time'])?"-":date('Y-m-d H:i:s', $oData['pay_time']);
        $data['fa_time']      = empty($oData['fa_time'])?"-":date('Y-m-d H:i:s', $oData['fa_time']);
        $data['ok_time']      = empty($oData['ok_time'])?"-":date('Y-m-d H:i:s', $oData['ok_time']);
        //订单详情
        $info                 = (new OrderInfo)->where("o_id", $oData['id'])->select()->toArray();
        $infoData             = [];
        foreach ($info as $v) {
            $d               = [];
            $d['id']         = $v['id'];
            $d['p_id']       = $v['p_id'];
            $d['title']      = $v['title'];
            $d['img']        = $v['img'];
            $d['count']      = $v['count'];
            $d['price']      = $v['price'];
            $d['money']      = $v['money'];
            $d['is_ip_buy']  = $v['is_ip_buy'];
            $d['give_score'] = $v['give_score'];
            $infoData[] = $d;
        }
        $data['info'] = $infoData;
        return app('json')->success($data);
    }
    
    /**
     * 订单备注记录
     * @param Request $request
     * @return mixed
     */
    public function log(Request $request){
        $pageSize = 20;
        $post     = UtilService::getMore([
            ['page', 1],
            ['o_id', '','empty','参数错误']
        ], $request);
        $where=[];
        $where['m.o_id'] = $post['o_id'];
        $where['m.code'] = "shop";
        $pageCount = (new OrderMono)->alias("m")->where($where)->count();
        $data = (new OrderMono)
                ->alias("m")
                ->where($where)
                ->order("id","desc")
                ->page((int)$post["page"], $pageSize)
                ->select()
                ->toArray();
        $data = empty($data)?[]:$data;
        foreach($data as $k=>$v){
            $data[$k]["time"] = date("Y-m-d H:i:s",$v["time"]);
        }
        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 进行发货
     * @global type $_A
     * @param Request $request
     */
    public function fahuo(Request $request) {
        $post = UtilService::getMore([
            ['id','','empty','参数错误'],
            ['express_num',''],
            ['remark',''],
        ],$request);
        $oData = (new OrderModel)->where("id",$post["id"])->where("status",1)->find();
        if (empty($oData)) {
            return app('json')->fail('当前订单不可发货');
        }
        if($oData["type"]=='send' && empty($post["express_num"])){
            return app('json')->fail('请输入物流单号');
        }
        $r = (new OrderModel)->where("id",$post["id"])->update([
            "status"=>2,
            "express_num"=>$post["express_num"],
            "fa_time"=>time(),
        ]);
        if(!$r){
            return app('json')->fail('操作失败');
        }
        $saveData=[];
        
        $saveData[]=[
            "o_id"=>$oData["id"],
            "order_id"=>$oData["order_id"],
            "mono"=>$oData["type"]=='send'?"确定发货, 物流单号:" . $post["express_num"]:"门店确定清点完毕",
            "time"=>time(),
            "admin_id"=>$request->adminInfo['id'],
            "admin_name"=>$request->adminInfo['name'],
            "type"=>1,
            "code"=>"shop",
        ];
        if(!empty($post["remark"])){
            $saveData[]=[
                "o_id"=>$oData["id"],
                "order_id"=>$oData["order_id"],
                "mono"=>$post["remark"],
                "time"=>time(),
                "admin_id"=>$request->adminInfo['id'],
                "admin_name"=>$request->adminInfo['name'],
                "type"=>1,
                "code"=>"shop",
            ];
        }
        (new OrderMono)->insertAll($saveData);
        return app('json')->success('操作成功');
    }
    /**
     * 订单备注提交
     * @param Request $request
     * @return mixed
     */
    public function mono(Request $request) {
       $post = UtilService::getMore([
            ['remark','','empty','请输入备注内容'],
            ['id','','empty','参数错误']
        ],$request);
        $oData = (new OrderModel)->where("id",$post["id"])->find();
        if (empty($oData)) {
            return app('json')->fail('订单不存在');
        }
        (new OrderMono)->insert([
            "o_id"=>$oData["id"],
            "order_id"=>$oData["order_id"],
            "mono"=>$post["remark"],
            "time"=>time(),
            "admin_id"=>$request->adminInfo['id'],
            "admin_name"=>$request->adminInfo['name'],
            "type"=>1,
            "code"=>"shop",
        ]);
        return app('json')->success('处理成功');
    }
    
    /**
     * 获取活动订单数据
     * @param Request $request
     * @return mixed
     * @throws DbException
     */
    public function showTemplateList(Request $request)
    {
        $pageSize = 50;
        $post = UtilService::getMore(
            [
                ['page', 1],
                ['uid',0],
                ['show_template_id',''],
                ['uip',''],
                ['order_id', ''],
                ['status',''],
                ['mobile',''],
                ['time',[]],
            ], $request
        );
        $where = [];
        if(!empty($post['uid'])){
            $where[]=["o.uid","=",$post['uid']];
        }else if(!empty($post['mobile'])){
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["o.uid","=",$m['uid']];
            }
        }
        if(!empty($post['show_template_id'])){
            $where[]=["o.show_template_id","=",$post['show_template_id']];
        }
        if(!empty($post['order_id'])){
            $where[]=["o.order_id","=",$post['order_id']];
        }
        if(in_array((string)$post['status'],["0","1","-1"])){
            $where[]=["o.status","=",(int)$post['status']];
        }
        //创建时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $where[]=["o.time","between","{$startTime},{$endTime}"];
        }
        $order = new ShowTemplateOrderModel;
        $data  = $order
                ->alias("o")
                ->field("o.*,u1.mobile,u1.nickname,a.title as show_template_title,a.imgs as show_template_imgs")
                ->leftJoin("user u1","u1.uid = o.uid")
                ->leftJoin("show_template a","a.id = o.show_template_id")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("o.id","desc")
                ->select()
                ->toArray();
        $pageCount = $order->alias("o")->where($where)->count();
        $result = UtilService::getParam([
            "id",
            "order_id",
            "uid",
            "mobile",
            "nickname",
            "total_money",
            "all_money",
            "pay_money",
            "status",
            "show_template_id",
            "show_template_title",
            ['show_template_imgs', 'show_template_imgs', function ($item) {
                return empty($item) ? [] : explode(",", $item);
            }],
            ['time', 'time', 'date("Y-m-d H:i:s",$1)'],
            ['pay_time', 'pay_time', function ($item) {
                return empty($item) ? "-" : date('Y-m-d H:i:s', $item);
            }],
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 搜索统计
     */
    public function showTemplateTotal(Request $request)
    {
        $post = UtilService::getMore(
            [
                ['uid',0],
                ['mobile',''],
                ['order_id', ''],
                ['status',''],
                ['show_template_id',''],
                ['time',[]],
            ], $request
        );
        $order       = new ShowTemplateOrderModel;
        $totalWhere = [];
        if(!empty($post['uid'])){
            $totalWhere[]=["uid","=",$post['uid']];
        }else if(!empty($post['mobile'])){
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $totalWhere[]=["uid","=",$m['uid']];
            }
        }
        if(!empty($post['show_template_id'])){
            $totalWhere[]=["show_template_id","=",$post['show_template_id']];
        }
        if(!empty($post['order_id'])){
            $totalWhere[]=["order_id","=",$post['order_id']];
        }
        if(in_array((string)$post['status'],["0","1","-1"])){
            $totalWhere[]=["status","=",$post['status']];
        }
        //创建时间
        $startTime="";
        $endTime="";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime = strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $totalWhere[]=["time","between","{$startTime},{$endTime}"];
        }
        foreach($totalWhere as $k=>$v){
            if($v[0]=="status"){
                array_splice($totalWhere,$k,1);
            }
        }
        //全部
        $orderCount = $order->where($totalWhere)->count();
        //待支付
        $waitPayWhere   = $totalWhere;
        $waitPayWhere[] = ["status","=","0"];
        $waitPayCount   = $order->where($waitPayWhere)->count();
        //待发货
        $waitSendWhere    = $totalWhere;
        $waitSendWhere[]  = ["status","=",1];
        $waitSendCount    = $order->where($waitSendWhere)->count();
        //已取消
        $closeWhere    = $totalWhere;
        $closeWhere[]  = ["status","=",-1];
        $closeCount    = $order->where($closeWhere)->count();
        return app('json')->success([
            'orderCount' => $orderCount,
            'waitPayCount'=> $waitPayCount,
            'waitSendCount' => $waitSendCount,
            'closeCount' => $closeCount,
        ]);
    }

    /**
     * 活动订单详情
     * @param Request $request
     */
    public function showTemplateInfo(Request $request)
    {
        [$id] = UtilService::getMore([
            ['id', '', 'empty', '参数错误'],
        ], $request, true);
        $oData = (new ShowTemplateOrderModel)
                ->alias("o")
                ->field("o.*,u1.mobile,u1.nickname,a.title as show_template_title,a.imgs as show_template_imgs")
                ->leftJoin("user u1","u1.uid = o.uid")
                ->leftJoin("show_template a","a.id = o.show_template_id")
                ->where("o.id",$id)
                ->find();
        if (empty($oData)) {
            return app('json')->fail('找不到订单号');
        }
        //主订单数据
        $data                   = [];
        $data['id']             = $oData['id'];
        $data['order_id']       = $oData['order_id'];
        $data['uid']            = $oData['uid'];
        $data['mobile']         = $oData['mobile'];
        $data['nickname']       = $oData['nickname'];
        $data['total_money']    = $oData['total_money'];
        $data['all_money']      = $oData['all_money'];
        $data['pay_money']      = $oData['pay_money'];
        $data['status']         = $oData['status'];
        $data['show_template_id']    = $oData['show_template_id'];
        $data['show_template_title'] = $oData['show_template_title'];
        $data['show_template_imgs']  = empty($oData['show_template_imgs'])?[]: explode(",", $oData['show_template_imgs']);
        $data['status']         = $oData['status'];
        $data['time']           = date('Y-m-d H:i:s', $oData['time']);
        $data['pay_time']       = empty($oData['pay_time'])?"-":date('Y-m-d H:i:s', $oData['pay_time']);
        //订单详情
        $data['info']         = empty($oData["data"]) ? [] : unserialize($oData["data"]);
        return app('json')->success($data);
    }
    
    /**
     * 订单备注记录
     * @param Request $request
     * @return mixed
     */
    public function showTemplateLog(Request $request){
        $pageSize = 20;
        $post     = UtilService::getMore([
            ['page', 1],
            ['o_id', '','empty','参数错误']
        ], $request);
        $where=[];
        $where['m.o_id'] = $post['o_id'];
        $where['m.code'] = "show_template";
        $pageCount = (new OrderMono)->alias("m")->where($where)->count();
        $data = (new OrderMono)
                ->alias("m")
                ->where($where)
                ->order("id","desc")
                ->page((int)$post["page"], $pageSize)
                ->select()
                ->toArray();
        $data = empty($data)?[]:$data;
        foreach($data as $k=>$v){
            $data[$k]["time"] = date("Y-m-d H:i:s",$v["time"]);
        }
        return app('json')->success([
            'list'      => $data,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 报名订单备注提交
     * @param Request $request
     * @return mixed
     */
    public function showTemplateMono(Request $request) {
       $post = UtilService::getMore([
            ['remark','','empty','请输入备注内容'],
            ['id','','empty','参数错误']
        ],$request);
        $oData = (new ShowTemplateOrderModel)->where("id",$post["id"])->find();
        if (empty($oData)) {
            return app('json')->fail('订单不存在');
        }
        (new OrderMono)->insert([
            "o_id"=>$oData["id"],
            "order_id"=>$oData["order_id"],
            "mono"=>$post["remark"],
            "time"=>time(),
            "admin_id"=>$request->adminInfo['id'],
            "admin_name"=>$request->adminInfo['name'],
            "type"=>1,
            "code"=>"show_template",
        ]);
        return app('json')->success('处理成功');
    }
}
