<?php

namespace app\api\controller\company;

use app\common\controller\Apic;
use think\Db;

use alipaysdkphpallmaster\aop\AopClient;
use alipaysdkphpallmaster\aop\request\AlipayTradePayRequest;
/**
 * 订单管理
 */
class Order extends Apic
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';


    //
    public function lists(){
        $keyword = input('keyword','');
        $status  = input('status','all');

        $where = [
            'company_id' => $this->auth->id,
        ];
        if($status !== 'all'){
            $where['status'] = $status;
        }
        if($status == 20){ //待还车
            $where['status'] = 20;
            $where['endtime'] = ['gt',time()];
        }
        if($status == 200){ //逾期
            $where['status'] = 20;
            $where['endtime'] = ['elt',time()];
        }
        if($status == 30){
            $where['status'] = ['IN',[-1,-2,30]];
        }
        if(!empty($keyword))
        {
            $where['user_truename|user_mobile|orderno'] = ['LIKE','%'.$keyword.'%'];
        }
        $list = Db::name('order')->where($where)->order('id desc')->autopage()->select();

        $list = list_domain_image($list,['car_image','idcard_images','driver_images','get_yibiao_images','get_carvideo','back_yibiao_images','back_carvideo']);

        foreach($list as $key => &$val){
            $val['status_text'] = $this->status_text($val['status'],$val['endtime']);

            if($val['status'] == 20 && time() >= $val['endtime']){
                $val['status'] = 200; //強制改掉
            }

            //追加取消
            $val['cancel_info'] = (object)[];
            if($val['status'] == -1 || $val['status'] == -2){
                //取消订单追加取消原因
                $val['cancel_info'] = Db::name('order_cancel')->where('order_id',$val['id'])->find();
            }

            //追加评价
            $val['comment_info'] = (object)[];
            if($val['status'] == 30){
                //完成订单追加评价
                $comment_info = Db::name('order_comment')->where('order_id',$val['id'])->find();
                if($comment_info){
                    $val['comment_info'] = $comment_info;
                }
            }
        }
        $this->success(1,$list);
    }

    //各个状态的订单数量
    public function status_each_number(){
        //全部
        $where = [
            'company_id' => $this->auth->id,
        ];
        $all = Db::name('order')->where($where)->count();
        //待取车
        $where = [
            'company_id' => $this->auth->id,
            'status' => 10
        ];
        $daiquche = Db::name('order')->where($where)->count();

        //待还车
        $where = [
            'company_id' => $this->auth->id,
            'status' => 20,
            'endtime' => ['gt',time()],
        ];
        $daihuanche = Db::name('order')->where($where)->count();

        //逾期
        $where = [
            'company_id' => $this->auth->id,
            'status' => 20,
            'endtime' => ['elt',time()],
        ];
        $yuqi = Db::name('order')->where($where)->count();

        //完成/取消
        $where = [
            'company_id' => $this->auth->id,
            'status' => ['IN',[-1,-2,30]],
        ];
        $wancheng = Db::name('order')->where($where)->count();

        $result = [
            'all' => $all,
            'daiquche'   => $daiquche,
            'daihuanche' => $daihuanche,
            'yuqi'       => $yuqi,
            'wancheng'   => $wancheng,
        ];

        $this->success(1,$result);
    }

    //状态
    private function status_text($status,$endtime){
        $arr = [
            -1 => '未付款被取消',
            -2 => '已付款被取消',
             0 => '待付款',
            10 => '已付款',
            20 => '已取车',
            30 => '完成',
        ];
        $status_text =  isset($arr[$status]) ? $arr[$status] : $status;

        //取走了车没还，时间却超过了还车时间
        if($status == 20 && time() >= $endtime){
            $status_text = '已逾期';
        }

        return $status_text;
    }

    //详情
    public function info(){
        $id = input('id',0);
        $info = Db::name('order')->where('id',$id)->find();
        $info = info_domain_image($info,['car_image','idcard_images','driver_images','get_yibiao_images','get_carvideo','back_yibiao_images','back_carvideo']);

        $info['status_text'] = $this->status_text($info['status'],$info['endtime']);
        if($info['status'] == 20 && time() >= $info['endtime']){
            $info['status'] = 200; //強制改掉
        }

        //完成订单追加评价
        $comment_info = Db::name('order_comment')->alias('c')
            ->field('c.*,user.avatar,user.mobile')
            ->join('user','c.user_id = user.id','LEFT')
            ->where('c.order_id',$id)->find();
        $comment_info = info_domain_image($comment_info,['avatar']);
        if(!empty($comment_info)){
            $comment_info['mobile'] = str_replace(substr($comment_info['mobile'],3,5),'****',$comment_info['mobile']);
        }
        $info['comment_info'] = $comment_info;

        //取消订单追加取消原因
        $info['cancel_info'] = Db::name('order_cancel')->where('order_id',$id)->find();

        $this->success(1,$info);
    }
    //取消理由
    public function cancel_config(){
        $list = Db::name('company_cancel_config')->order('id asc')->select();
        $this->success(1,$list);
    }
    //取消
    public function cancel(){
        $id = input('id',0);
        $reason = input('reason','');

        Db::startTrans();
        $info = Db::name('order')->where('id',$id)->where('company_id',$this->auth->id)->lock(true)->find();
        if($info['status'] == -2){
            Db::rollback();
            $this->error('当前订单已经申请取消,已付款订单审核后可退款');
        }
        if($info['status'] != 0 && $info['status'] != 10){
            Db::rollback();
            $this->error('当前订单状态不能取消');
        }

        //未付款取消
        if($info['status'] == 0){
            $rs = Db::name('order')->where('id',$id)->update(['status'=>-1]);
        }

        //已付款取消
        if($info['status'] == 10){
            $rs = Db::name('order')->where('id',$id)->update(['status'=>-2]);
            //扣除车行收益
            //从计划任务里走
        }

        if($rs === false){
            Db::rollback();
            $this->error('申请取消失败');
        }

        $data = [
            'user_id'  => $info['user_id'],
            'company_id'  => $info['company_id'],
            'order_id' => $info['id'],
            'reason'   => '商家取消:'.$reason,
            'refund_price' => 0,
            'type' => $info['status'],               //分类:0=未付款,10=已付款
            'createtime' => time(),
            'status' => $info['status'] == 0 ? 2 : 0, //状态:0=未处理,1=已处理,2=无需处理
            'from' => 2,  //取消方:1=用户取消,2=商户取消
        ];

        $rs_cancle = Db::name('order_cancel')->insertGetId($data);
        if(!$rs_cancle){
            Db::rollback();
            $this->error('申请取消失败');
        }

        //解除汽车占用
        $rs_car = Db::name('car')->where('id',$info['car_id'])->update(['status'=>1]);
        if(!$rs_car){
            Db::rollback();
            $this->error('申请取消失败');
        }

        Db::commit();
        $this->success('取消成功');

    }
    //确认取车
    public function get_car(){
        $id = input('id',0);

        Db::startTrans();
        $info = Db::name('order')->where('id',$id)->where('company_id',$this->auth->id)->lock(true)->find();
        if($info['status'] != 10){
            Db::rollback();
            $this->error('当前订单状态不能取车');
        }

        //
        $data = [
            'idcard_images' => input('idcard_images',''),
            'driver_images' => input('driver_images',''),
            'get_yibiao_images' => input('get_yibiao_images',''),
            'get_carvideo'  => input('get_carvideo',''),
            'status' => 20,
            'getcartime' => time(),
        ];
        Db::name('order')->where('id',$id)->update($data);
        Db::commit();

        $this->success('取车完成');
    }
    //还车车伤确认，配置
    public function back_config(){
        $list = Db::name('order_back_config')->order('id asc')->select();
        $this->success(1,$list);
    }
    //还车
    public function back_car(){
        $id = input('id',0);

        Db::startTrans();
        $info = Db::name('order')->where('id',$id)->where('company_id',$this->auth->id)->lock(true)->find();
        if($info['status'] != 20){
            Db::rollback();
            $this->error('当前订单状态不能还车');
        }

        //还车
        $data = [
            'back_yibiao_images' => input('back_yibiao_images',''),
            'back_carvideo' => input('back_carvideo',''),
            'back_remark' => input('back_remark',''),
            'status' => 30,
            'backcartime' => input('backcartime',''),
            'back_oilfee' => input('back_oilfee',0),
            'back_damage' => input('back_damage',''),
        ];
        $rs_update = Db::name('order')->where('id',$id)->update($data);
        if($rs_update === false){
            Db::rollback();
            $this->error('还车失败');
        }

        //汽车解除占用
        $rs_car = Db::name('car')->where('id',$info['car_id'])->update(['status'=>1]);
        if($rs_car === false){
            Db::rollback();
            $this->error('还车失败');
        }

        //给上一级用户赠送一张满100减100的券
        $intro_user = Db::name('user')->where('id',$info['user_id'])->value('intro_uid');
        if($intro_user){
            //检查送过没有
            $where = [
                'user_id' => $info['user_id'],
                'status'  => 30,
                'id' => ['neq',$info['id']],
            ];
            $check = Db::name('order')->where($where)->find();
            if(!$check){
                //赠送一个
                $only_coupon = Db::name('coupons')->where('id',1)->lock(true)->find();
                if($only_coupon['stock'] > 1){
                    //送到
                    $data = [
                        'user_id' => $intro_user,
                        'company_id' => $only_coupon['company_id'],
                        'enough' => $only_coupon['enough'],
                        'amount' => $only_coupon['amount'],
                        'type' => $only_coupon['type'],
                        'coupons_id' => $only_coupon['id'],

                        'createtime' => time(),
                        'usetimestart' => $only_coupon['usetimestart'],
                        'usetimeend' => $only_coupon['usetimeend'],
                    ];
                    $rs_user_coupon = Db::name('user_coupons')->insertGetId($data);
                    //减库存
                    $rs_only_coupon = Db::name('coupons')->where('id',1)->update(['stock'=>$only_coupon['stock']-1]);
                    if(!$rs_user_coupon || $rs_only_coupon === false){
                        Db::rollback();
                        $this->error('还车失败了');
                    }
                }

                //给上级奖励money
                $intro_money = config('site.yaoqing_user_backcar_money');
                if($intro_money > 0){
                    $wallet = new \app\common\model\Wallet;
                    $wallet_rs = $wallet->lockChangeAccountRemain($intro_user,'money',$intro_money,3,'邀请新用户下单('.$info['user_id'].')','order',$info['id']);
                    if($wallet_rs['status'] === false){
                        Db::rollback();
                        $this->error($wallet_rs['msg']);
                    }
                }


            }
        }


        Db::commit();

        $this->success('还车完成');
    }



    //回复评价
    public function comment_reply(){
        $comment_id = input('comment_id',0);
        $reply = input('reply','');

        $data = [
            'reply' => $reply,
            'replytime' => time(),
        ];
        Db::name('order_comment')->where('id',$comment_id)->update($data);

        $this->success('回复完成');
    }
}
