<?php

namespace app\api\controller\company;

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

use alipaysdkphpallmaster\aop\AopClient;
use alipaysdkphpallmaster\aop\request\AlipayTradePayRequest;

/**
 * 订单管理
 */
class Order extends Apic
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';


    private function status_text($status){
        $arr = [
            1 => '待支付',
            2 => '待处理',
            3 => '已完成',
            4 => '已取消',
        ];

        return isset($arr[$status]) ? $arr[$status] : '';
    }
    //
    public function lists(){
        $keyword = input('keyword','');
        $starttime = input('starttime',0);
        $endtime = input('endtime',0);
        $servicetype_id = intval(input('servicetype_id',0));
        $status  = intval(input('status',0));

        $order = 'order.id desc';

        $where = [
            'company_id' => $this->auth->company_id,
        ];
        //员工
        if($this->auth->type == 2){
            $where['staff_id'] = $this->auth->id;
        }//员工

        if($starttime || $endtime){
            $where['createtime'] = ['between',$starttime,$endtime];
        }
        if($servicetype_id){
            $where['servicetype_id'] = $servicetype_id;
        }
        if($status){
            $where['status'] = $status;  //状态:2=待处理,3=已核销(完成),4=已取消
            if($status > 2){
                $order = 'order.finish_time desc';
            }

        }

        if(!empty($keyword))
        {
            $where['user_car_number|user_mobile'] = ['LIKE','%'.$keyword.'%'];
        }
        $list = Db::name('order')->alias('order')
            ->join('servicetype','order.servicetype_id = servicetype.id','LEFT')
            ->field('order.id,orderno,ordertype,user_name,user_mobile,user_car_number,createtime,servicetype_id,server_info,server_time,status,finish_time,cancel_reason,hexiao_time,cancel_time,servicetype.title as servicetype_title,servicetype.baoyang_switch')->where($where)->order($order)->autopage()->select();

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


    //详情
    public function info(){
        $id = input('id',0);
        $info = Db::name('order')->alias('order')
            ->join('servicetype','order.servicetype_id = servicetype.id','LEFT')
            ->field('order.*,servicetype.title as servicetype_title,servicetype.baoyang_switch')
            ->where('order.id',$id)->find();
        $info = info_domain_image($info,['server_images']);
        $info['status_text'] = $this->status_text($info['status']);
        $info['total_fee'] = bcadd($info['pay_fee'],$info['appen_fee'],2);

        $info['appen_list'] = Db::name('order_appen')->where('order_id',$id)->select();

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

    //取消
    public function cancel(){
        $id = input('id',0);
        $reason = input('reason','');

        $info = Db::name('order')->where('id',$id)->where('company_id',$this->auth->company_id)->find();
        if($info['status'] == 4){
            $this->error('当前订单已经取消');
        }
        if($info['status'] != 0 && $info['status'] != 2){
            $this->error('当前订单状态不能取消');
        }
        if($info['ordertype'] == 3){
            $this->error('套餐订单不能取消');
        }
        $time = time();
        //同步到预约单
        if (!empty($info['pre_order_id'])) {
            $preOrderWhere['id'] = $info['pre_order_id'];
            $preOrder = Db::name('pre_order')->where($preOrderWhere)->find();
            if (!empty($preOrder) && $preOrder['pre_order_status'] != 0) {
                $preOrderData = ['pre_order_status'=>0,'cancel_time'=>$time,'cancel_reason'=>$reason];
                $preOrderRes = Db::name('pre_order')->where($preOrderWhere)->update($preOrderData);
                if (!$preOrderRes) {
                    $this->error('预约单取消失败');
                }
            }
        }
        //取消
        $rs = Db::name('order')->where('id',$id)->update(['status'=>4,'cancel_time'=>time(),'finish_time'=>time(),'cancel_reason'=>$reason]);

        if($rs === false){
            $this->error('取消失败');
        }
        //订单取消发送消息
        $userService = new UserService();
        $params['order_id'] = $id;
        $userService->msgOrder($params);
        $this->success('取消成功');

    }

    //完成
    public function finish(){
        $id = input('id',0);

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

        //完成
        $time = time();
        $updateData = ['status'=>3,'finish_time'=>time(),'staff_id'=>$this->auth->id];
        if (empty($info['hexiao_time'])) {
            $updateData['hexiao_time'] = $time;
        }
        $rs = Db::name('order')->where('id',$id)->update($updateData);
        if($rs === false){
            Db::rollback();
            $this->error('操作失败');
        }

        //给门店加钱
        if($info['ordertype'] == 3 && $info['paytype'] == 3 && $info['pay_fee'] > 0){
            $wallet_rs = model('walletcompany')->lockChangeAccountRemain($this->auth->company_id,'money',$info['pay_fee'],203,$remark='套餐订单完成服务','order',$id);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }
        }

        Db::commit();
        //订单取消发送消息
        $userService = new UserService();
        $params['order_id'] = $id;
        $userService->msgOrder($params);
        //是否弹出保养
        $baoyang_switch = Db::name('servicetype')->where('id',$info['servicetype_id'])->value('baoyang_switch');

        $this->success('操作成功',$baoyang_switch);
    }

    //设置保养时间提醒
    public function baoyang(){
        $id = input('id',0);

        $info = Db::name('order')->where('id',$id)->where('company_id',$this->auth->company_id)->find();
        if(!$info){
            $this->error('不存在的订单');
        }

        //更新
        $next_date       = input('next_date','');
        $next_carlicheng = input('next_carlicheng','');
        $data = [
            'next_date'       => $next_date,
            'next_carlicheng' => $next_carlicheng,
        ];

        Db::name('order')->where('id',$id)->update($data);
        $this->success('操作成功');

    }

    //追加列表
    public function appen_lists(){
        $id = input('id',0);

        $info = Db::name('order')->field('id,orderno,pay_fee,appen_fee')->where('id',$id)->where('company_id',$this->auth->company_id)->find();
        if(!$info){
            $this->error('不存在的订单');
        }

        $info['appen_list'] = Db::name('order_appen')->where('order_id',$id)->select();

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

    //追加新费用
    public function appen_newone(){
        $id = input('id',0);

        Db::startTrans();
        $info = Db::name('order')->field('id,orderno,pay_fee,appen_fee')->where('id',$id)->where('company_id',$this->auth->company_id)->lock(true)->find();
        if(!$info){
            $this->error('不存在的订单');
        }

        //加入新的一条
        $name = input('name','');
        $price = intval(input('price',0));

        if($price <= 0){
            Db::rollback();
            $this->error('请填写正确的金额');
        }

        $data = [
            'company_id'   => $this->auth->company_id,
            'order_id'   => $id,
            'name'       => $name,
            'price'      => $price,
            'createtime' => time(),
        ];

        $log_id = Db::name('order_appen')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('操作失败');
        }

        //计算追加总额做冗余
        $sum_price = Db::name('order_appen')->where('order_id',$id)->sum('price');

        $update = [
            'appen_fee'=>$sum_price,
            'total_fee'=>bcadd($sum_price,$info['pay_fee'],2),
        ];
        $rs = Db::name('order')->where('id',$id)->update($update);
        if($rs === false){
            Db::rollback();
            $this->error('操作失败');
        }

        //结束
        Db::commit();
        $this->success();
    }



}
