<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service;
use app\common\library\Tenim;
use app\common\model\Wenzhenorder;

/**
 * 问诊订单
 */
class Wenzhen extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    //创建订单
    public function create_order(){
        $member_id = input('member_id',0);
        $doctor_id = input('doctor_id',0);
        $ordertype = input('ordertype',0);

        $book_date = input('book_date',0); //2024-05-05
        $book_hour = input('book_time',0); //10:00
        $book_time = strtotime($book_date.' '.$book_hour);


        $member_disease = input('member_disease','');
        $member_images  = input('member_images','');

        $auth_id = $this->auth->id;
        $order_no = createUniqueNo('W',$auth_id);

        //成员信息
        $member_info = Db::name('user_member')->where('user_id',$auth_id)->where('id',$member_id)->find();
        if(empty($member_info)){
            $this->error('不存在的就诊者');
        }

        //医生信息
        $doctor = Db::name('doctor')->where('id',$doctor_id)->find();
        $doctor_info = Db::name('doctor_info')->where('doctor_id',$doctor_id)->find();
        if(empty($doctor_info)){
            $this->error('不存在的医生');
        }

        //ordertype
        if(!in_array($ordertype,[1,2])){
            $this->error();
        }

        //价格
        $price = 0;
        if($ordertype == 1){
            if($doctor_info['typing_switch'] != 1){
                $this->error('该医生未开通图文问诊');
            }
            if($doctor['job_status'] != 1){
                $this->error('该医生现在不在上班中');
            }
            $price = $doctor_info['typing_price'];
        }
        if($ordertype == 2){
            if($doctor_info['video_switch'] != 1){
                $this->error('该医生未开通视频问诊');
            }
            if($doctor_info['video_model'] == 2 && $doctor['job_status'] != 1){ //即时方式，需要在上班中
                $this->error('该医生现在不在上班中');
            }
            $price = $doctor_info['video_price'];
        }
        if($price <= 0){
            $this->error('问诊价格为零');
        }

        //排班判断
        if($ordertype == 1){
            $book_time = 0;
        }
        if($ordertype == 2){
            if($doctor_info['video_model'] == 1){  //排班预约
                //检查
                if($book_time < time() + 7200){
                    //测试临时屏蔽
                    //$this->error('最早只能预约'.date('m-d H:00',time() + 10800)); //最早预约两个小时后的一个整点
                }
                //排班状态
                $doctor_paiban = Db::name('doctor_paiban')->where('doctor_id',$doctor_id)->where('activetime',$book_time)->find();
                if(empty($doctor_paiban)){
                    $this->error('您预约的时间该医生无法接诊');
                }
                if($doctor_paiban['active'] != 1){
                    $this->error('您预约的时间该医生无法接诊');
                }
                //是否排满
                $map = [
                    'doctor_id' => $doctor_id,
                    'book_time' => $book_time,
                    'ordertype' => 2,
                    'status'    => ['IN','10,20,25,30'],//有效订单
                    'video_model' => 1,//预约模式
                ];
                $order_count = Db::name('wenzhen_order')->where($map)->count();
                if($order_count >= 4){
                    $this->error('该时间点已排满，请重选预约时间');
                }
            }
            else
            {
                $book_time = time();                //即时预约
            }

        }

         //订单数据
        $order_data = [
            'order_no'   => $order_no,
            'user_id'    => $auth_id,
            'member_id'  => $member_id,
            'doctor_id'  => $doctor_id,
            'ordertype'  => $ordertype,
            'total_fee'  => $price,
            'book_time'  => $book_time,
            'createtime' => time(),
            'status'     => 0,//订单状态enum
            'video_model'=> $doctor_info['video_model'],  //视频问诊预约方式
        ];

        Db::startTrans();

        //下单
        $order_id = Db::name('wenzhen_order')->insertGetId($order_data);
        if(!$order_id){
            Db::rollback();
            $this->error('下单失败');
        }

        //订单附表，就诊人信息
        $member_data = $member_info;
        unset($member_data['id']);
        $member_data['order_id']       = $order_id;
        $member_data['member_id']      = $member_info['id'];
        $member_data['member_disease'] = $member_disease;
        $member_data['member_images']  = $member_images;

        $order_member_id = Db::name('wenzhen_order_member')->insertGetId($member_data);
        if(!$order_member_id){
            Db::rollback();
            $this->error('下单失败');
        }

        //
        Db::commit();
        $this->success('下单成功',$order_id);
    }

    //支付订单
    public function pay_order(){
        $order_id = input('order_id',0);
        $pay_type = input('pay_type','wechat');

        //pay_type
        if(!in_array($pay_type,['wechat','alipay','wallet'])){
            $this->error();
        }

        //订单详情
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }
        if($wenzhen_order['status'] != 0){
            $this->error('该订单不能支付');
        }


        if($pay_type == 'wallet'){
            Db::startTrans();

            //用户扣钱
            $logtype = $wenzhen_order['ordertype'] == 1 ? 11 : 12;
            $rs_wallet = model('wallet')->lockChangeAccountRemain($this->auth->id,'money',-$wenzhen_order['total_fee'],$logtype,'图文问诊'.$wenzhen_order['order_no'],'wenzhen_order',$order_id);
            if($rs_wallet['status'] == false){
                Db::rollback();
                $this->error($rs_wallet['msg']);
            }

            //订单改为已支付
            $wenzhen_update['status'] = 10;//订单状态enum
            $wenzhen_update['pay_type'] = $pay_type;
            $wenzhen_update['pay_time'] = time();
            $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->where('status',0)->update($wenzhen_update);
            if(!$update_rs){
                Db::rollback();
                $this->error('支付失败,重试一下吧');
            }

            Db::commit();

            //发送im消息给医生
            if($wenzhen_order['ordertype'] == 1){
                $tenim = new Tenim();
                $message = [
                    'businessID' => 'order_status',
                    'name' => '待接单',
                    'status' => '10',
                    'id' => (string)$order_id,
                    'content' => '已通知医生尽快接诊，超时未接诊的将自动取消订单并退款',
                ];
                $rs = $tenim->sendCustomMessageToUser('user'.$this->auth->id,'doctor'.$wenzhen_order['doctor_id'],$message);
            }

            //输出
            $result = [
                'pay_type' => $pay_type,
                'pay_params' => '',
            ];
            $this->success(1,$result);
        }

        //创建订单
        $platform = 'app';
        $data = [];
        $data['user_id'] = $this->auth->id;
        $data['out_trade_no'] = createUniqueNo('W',$this->auth->id);
        $data['order_amount'] = $wenzhen_order['total_fee'];
        $data['createtime'] = time();

        $data['pay_type'] = $pay_type;
        $data['platform'] = $platform;
        $data['order_status'] = 0;
        $data['table_name'] = 'wenzhen_order';
        $data['table_id'] = $order_id;
        $data['args'] = '';

        $orderid = Db::name('pay_order')->insertGetId($data);

        $openid = '';
        //下单
        $params = [
            'type'         => $pay_type,
            'orderid'      => $data['out_trade_no'],
            'title'        => '支付订单',
            'amount'       => $data['order_amount'],
            'method'       => $platform,
            'openid'       => $openid,
            'notifyurl' => config('pay_notify_url').'/api/notify/wenzhen_notify_base/paytype/'.$pay_type,
            'returnurl' => '',
        ];

        $res = Service::submitOrder($params);

        $result = [
            'pay_type'=> $pay_type,
            'pay_params'=> $pay_type

        ];
        if($pay_type == 'wechat'){
            $result['pay_params'] = json_decode($res,true);
        }else{
            $result['pay_params'] = $res;
        }

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

    //订单列表
    public function order_list(){
        $status = input('status','all');

        $where = ['user_id'=>$this->auth->id];
        if($status != 'all'){
            $where['order.status'] = $status;

            if($status == 20){// 已接诊、问诊中
                $where['order.status'] = ['IN',[20,25]];
            }
        }

        $field = [
            'order.id','order.order_no','order.createtime','order.status','order.ordertype','order.accept_time','order.video_time','order.doctor_id','order.cancel_reason','order.comefrom','order.video_model',
            'doctor.avatar as doctor_avatar','doctor.nickname as doctor_nickname',
        ];
        $list = Db::name('wenzhen_order')->alias('order')
            ->field($field)
            ->join('doctor','order.doctor_id = doctor.id','LEFT')
            ->order('order.id desc')
            ->where($where)
            ->autopage()->select();
        $list = list_domain_image($list,['doctor_avatar']);

        if(!empty($list)){
            //循环处理
            foreach($list as $key => $val){
                $val = $this->orderinfo_appen($val);

                //医生原因的退款，都直接算到退珍
                if(in_array($val['status'],[16,18,22])){
                    $val['status'] = 100;
                }

                //视频拨打中  也算问诊中
                if($val['status'] == 25){
                    $val['status'] = 20;
                }

                //视频订单是否能拨打，即时模式才可以
                $val['video_call_switch'] = 0;
                if($val['video_model'] == 2 && $val['ordertype'] == 2 && in_array($val['status'],[10,20,25])){  //三个状态都可以，理论上不存在20
                    $val['video_call_switch'] = 1;
                }

                $list[$key] = $val;
            }
        }

        $this->success(1,$list);

    }

    //单个订单，追加数据
    private function orderinfo_appen($val){
        //订单类型
        $ordertype_data = [
            1 => ['name'=>'图文订单','name_en'=>'Visual Order'],
            2 => ['name'=>'视频订单','name_en'=>'Video Order'],
        ];

        //状态备注
        $status_data = $this->order_status_enum();

        //开始处理
        //订单类型，辅助
        $val['ordertype_data'] = $ordertype_data[$val['ordertype']];

        //订单状态，辅助
        $status_data_status = $val['status'];
        if($val['status'] == 10 && $val['video_model'] == 2){$status_data_status = 102;}
        $status_data_val = $status_data[$status_data_status];

        //未支付订单N分钟后自动取消
        if($val['status'] == 0){
            $remain_time = $val['createtime'] + (config('site.nopay_order_autocancel_minute')*60) - time();
            if($remain_time > 0){
                $status_data_val['minute'] = Sec2Time($remain_time);
                $status_data_val['minute_en'] = Sec2Time_en($remain_time);
                $status_data_val['seconds'] = $remain_time;
            }
        }

        //被医生退珍，追加原因
        if($val['status'] == 18){
            $status_data_val['name'] .= '：'.$val['cancel_reason'];
        }


        //图文订单接诊后N分钟自动结束
        if($val['status'] == 20 && $val['ordertype'] == 1){
            $remain_time = $val['accept_time'] + (config('site.accept_textorder_autofinish_minute')*60) - time();
            if($remain_time > 0){
                $status_data_val['minute'] = Sec2Time($remain_time);
                $status_data_val['minute_en'] = Sec2Time_en($remain_time);
                $status_data_val['seconds'] = $remain_time;
            }
        }

        //视频订单接通后N分钟自动结束
        if($val['status'] == 25 && $val['ordertype'] == 2){
            $minute = config('site.firstvideo_videoorder_autofinish_minute');
            if($val['comefrom'] == 2){
                $minute = config('site.tv_firstvideo_videoorder_autofinish_minute');
            }
            $remain_time = $val['video_time'] + ($minute*60) - time();
            if($remain_time > 0){
                $status_data_val['minute'] = Sec2Time($remain_time);
                $status_data_val['minute_en'] = Sec2Time_en($remain_time);
                $status_data_val['seconds'] = $remain_time;
            }
        }

        $val['status_data'] = $status_data_val;

        //处理完成，返回
        return $val;
    }

    //订单状态备注枚举
    private function order_status_enum(){
        //状态:0=未付款,3=已失效,10=待接诊,13=用户退诊,16=医生未接诊,18=医生退诊,20=已接诊,22=超时未拨打,25=视频通话中,30=问诊完成
        $status_data = [
            0 =>  [
                'name'=>'等待支付时间',
                'name_en'=>'Waiting time for payment',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            3 =>  [
                'name'=>'您的订单未及时支付，已失效',
                'name_en'=>'Your order was not paid on time and has expired.',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            10 => [
                'name'=>'等待医生接诊:已通知医生尽快接诊，超时自动取消订单并退款',
                'name_en'=>'Waiting for the doctor. If not accepted within the specified time,the consultation will be automatically canceled, and a refund will be issued',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            //给即时视频用的
            102 => [
                'name'=>'视频问诊:您可立即发起视频问诊',
                'name_en'=>'Video consultation: You can initiate a video consultation immediately',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            13 => [
                'name'=>'您的订单已退珍',
                'name_en'=>'Your order has been canceled',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            16 => [
                'name'=>'医生未接诊',
                'name_en'=>'Doctor Not received',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            18 => [
                'name'=>'退珍原因',
                'name_en'=>'',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            20 => [
                'name'=>'医生已接诊,咨询中',
                'name_en'=>'',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            22 => [
                'name'=>'医生超时未拨打视频',
                'name_en'=>'',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            25 => [
                'name'=>'视频问诊进行中',
                'name_en'=>'Time Remaining',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],
            30 => [
                'name'=>'点击查看医生反馈结果',
                'name_en'=>'Click to view the consultation results',
                'minute' => '',
                'minute_en' => '',
                'seconds' => 0,
            ],

        ];
        return $status_data;
    }

    //订单详情
    public function order_info(){
        $order_id = input('order_id',0);

        //订单详情
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }
        $wenzhen_order = info_domain_image($wenzhen_order,['feedback_images']);
        $wenzhen_order = $this->orderinfo_appen($wenzhen_order);


        //就诊人详情
        $order_member_info = Db::name('wenzhen_order_member')->where('order_id',$order_id)->find();
        $order_member_info = info_domain_image($order_member_info,['member_images']);
        $order_member_info['age'] = birthtime_to_age($order_member_info['birthday']);

        $wenzhen_order['member_info'] = $order_member_info;

        //医生详情
        $field = [
            'd.nickname','d.avatar','d.keshi_id','d.level_id','d.hospital','d.goodat','d.ordernum',
            'keshi.name as keshi_name',
            'level.name as level_name'
        ];
        $doctor_info = Db::name('doctor')->alias('d')
            ->field($field)
            ->join('doctor_level level','d.level_id = level.id','LEFT')
            ->join('keshi','d.keshi_id = keshi.id','LEFT')
            ->where('d.id',$wenzhen_order['doctor_id'])->find();
        $doctor_info = info_domain_image($doctor_info,['avatar']);

        $wenzhen_order['doctor_info'] = $doctor_info;

        //视频订单是否能拨打，即时模式才可以
        $wenzhen_order['video_call_switch'] = 0;
        if($wenzhen_order['video_model'] == 2 && $wenzhen_order['ordertype'] == 2 && in_array($wenzhen_order['status'],[10,20,25])){  //三个状态都可以，理论上不存在20
                $wenzhen_order['video_call_switch'] = 1;
        }

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

    //编辑订单里的就诊人资料
    public function edit_member(){
        $order_id = input('order_id',0);

        //订单详情
        $wenzhen_order_member = Db::name('wenzhen_order_member')->where('user_id',$this->auth->id)->where('order_id',$order_id)->find();
        if(empty($wenzhen_order_member)){
            $this->error('不存在的订单');
        }

        $update = [
            'member_disease' => input('member_disease',''),
            'member_images'  => input('member_images',''),
        ];

        Db::name('wenzhen_order_member')->where('user_id',$this->auth->id)->where('order_id',$order_id)->update($update);

        $this->success();
    }

    //用户发起退珍
    //因为存在第三方，悲观锁
    public function tuizhen(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

        //订单详情
        $order_id = input('order_id',0);
        Db::startTrans();

        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->lock(true)->find();
        if(empty($wenzhen_order)){
            Db::rollback();
            $this->error('不存在的订单');
        }

        //仅限视频订单
        if($wenzhen_order['ordertype'] == 1){
            Db::rollback();
            $this->error('图文问诊不能退诊');
        }

        //下面全是视频订单
        //状态限制
        if($wenzhen_order['video_model'] == 1){
            if(!in_array($wenzhen_order['status'],[10,20])){
                Db::rollback();
                $this->error('当前订单不能退诊');
            }

            //超过支付时间一小时不能退
            if($wenzhen_order['status'] == 20 && (time() - $wenzhen_order['pay_time'] > 3600)){
                Db::rollback();
                $this->error('支付超过一小时,不能退诊');
            }
        }else{
            //即时模式，已付款没接的能退
            if($wenzhen_order['status'] != 10){
                Db::rollback();
                $this->error('当前订单不能退诊');
            }
        }

        //修改订单
        $nowtime = time();
        $update = [
            'status'        => 13,
            'cancel_time'   => $nowtime,
            'cancel_reason' => '用户付款后退诊',
            'finish_time'   => $nowtime,
        ];


        //退款要打折扣
        $wenzhen_refund_bili = config('site.payorder_userrefund_bili') ?: 70;
        $refund_price = bcdiv(bcmul($wenzhen_order['total_fee'],$wenzhen_refund_bili,2),100,2);

        //余额支付的直接退款
        if($wenzhen_order['pay_type'] == 'wallet'){

            //用户加钱
            $logtype = $wenzhen_order['ordertype'] == 1 ? 13 : 14;

            $rs_wallet = model('wallet')->lockChangeAccountRemain($wenzhen_order['user_id'],'money',$refund_price,$logtype,$remark='用户问诊退珍','wenzhen_order',$order_id);
            if($rs_wallet['status'] === false){
                Db::rollback();
                $this->error($rs_wallet['msg']);
            }

            //订单退款参数
            $update['refund_price']  = $refund_price;
            $update['refund_status'] = 3;
        }else{

            $update['refund_status'] = 1; //待退款

            //发起退款
            $Wenzhenorder_model = new Wenzhenorder;
            $refund_rs = $Wenzhenorder_model->old_refund($wenzhen_order,$refund_price);
            if($refund_rs === true){
                $update['refund_status'] = 3; //退款完成
            }

        }

        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->update($update);
        if(!$update_rs){
            Db::rollback();
            $this->error('退诊失败');
        }

        Db::commit();
        $this->success('退珍成功');
    }

///////////////////////////////视频即时问诊///////////////////////////

    //第一次拨打视频之前,20,25可以调用
    public function before_first_video(){

        //订单详情
        $order_id = input('order_id',0);
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }

        if($wenzhen_order['ordertype'] != 2){
            $this->error('视频问诊才能拨打视频');
        }
        if($wenzhen_order['video_model'] != 2){
            $this->error('即时视频问诊才能主动拨打视频');
        }

        if($wenzhen_order['status'] == 30){
            $this->error('订单已结束');
        }
        if($wenzhen_order['status'] == 25){
            //判断医生在线状态
            $tenim = new Tenim();
            $rs_online = $tenim->is_online('doctor'.$wenzhen_order['doctor_id']);
            if($rs_online != true){
                $this->error('医生现在不在线,请稍后拨打');
            }

            $this->success();
        }

        //20直接忽略

        if($wenzhen_order['status'] != 10){
            $this->error('订单错误,请刷新重试');
        }



        //判断患者在线状态
        $tenim = new Tenim();
        $rs_online = $tenim->is_online('doctor'.$wenzhen_order['doctor_id']);
        if($rs_online != true){
            $this->error('医生现在不在线,请稍后拨打');
        }

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

    //第一次拨打视频
    public function first_video(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

        //订单详情
        $order_id = input('order_id',0);
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }

        if($wenzhen_order['ordertype'] != 2){
            $this->error('视频问诊才能拨打视频');
        }
        if($wenzhen_order['video_model'] != 2){
            $this->error('即时视频问诊才能主动拨打视频');
        }

        if($wenzhen_order['status'] == 30){
            $this->error('订单已结束');
        }
        if($wenzhen_order['status'] == 25){
            //倒计时
            $minute = config('site.firstvideo_videoorder_autofinish_minute');
            if($wenzhen_order['comefrom'] == 2){
                $minute = config('site.tv_firstvideo_videoorder_autofinish_minute');
            }

            $rs = [
                'video_time'    => $wenzhen_order['video_time'],
                'video_endtime' => $wenzhen_order['video_time'] + $minute*60,
            ];
            $rs['seconds'] = $rs['video_endtime'] - time();

            //修改最后拨通时间
            $update = [
                'last_video_time' => time(),
            ];
            $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->update($update);

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

        //20直接忽略

        if($wenzhen_order['status'] != 10){
            $this->error('订单错误,请刷新重试');
        }

        //修改订单
        $update = [
            'status' => 25,
            'video_time' => time(),
            'last_video_time' => time(),
        ];

        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->where('status',10)->update($update);
        if(!$update_rs){
            $this->error('操作失败');
        }

        //倒计时
        $minute = config('site.firstvideo_videoorder_autofinish_minute');
        if($wenzhen_order['comefrom'] == 2){
            $minute = config('site.tv_firstvideo_videoorder_autofinish_minute');
        }

        $rs = [
            'video_time'    => $update['video_time'],
            'seconds'       => $minute*60,
            'video_endtime' => $update['video_time'] + $minute*60,
        ];

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


    //挂断，医生挂断。这个方法主要用来统计是否已满足一分钟
    public function video_end(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }
        $end_rule = input('end_rule','user'); //user 用户挂断，doctor 医生挂断。如果是医生挂断并且这个订单一次都没有接通，那就直接按拒绝接诊，结束订单

        //订单详情
        $order_id = input('order_id',0);
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }

        if($wenzhen_order['ordertype'] != 2){
            $this->error('视频问诊才能拨打视频');
        }
        if($wenzhen_order['video_model'] != 2){
            $this->error('即时视频问诊才能主动拨打视频');
        }

        if($wenzhen_order['status'] != 25 && $wenzhen_order['status'] != 10){
            $this->error('订单错误,请刷新重试');
        }

        $nowtime = time();

        //接通了
        if($wenzhen_order['status'] == 25){
            //本次不超过1分钟
            if($nowtime - $wenzhen_order['last_video_time'] < 60 ){
                $this->success('已挂断');
            }

            //如果本次挂断之前已通话超过一分钟，那自动结束
            Db::startTrans();
            $wenzhen_order = Db::name('wenzhen_order')->where('id',$order_id)->lock(true)->find();
            $update = [
                'status' => 30,
                'finish_time' => $nowtime,
            ];
            $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->update($update);
            if(!$update_rs){
                Db::rollback();
                $this->error('操作失败');
            }

            //给医生结算钱
            $logtype = $wenzhen_order['ordertype'] == 1 ? 111 : 112;
            if($wenzhen_order['comefrom'] == 1 && $wenzhen_order['total_fee'] > 0){
                $rs_wallet = model('walletdoctor')->lockChangeAccountRemain($wenzhen_order['doctor_id'],'money',$wenzhen_order['total_fee'],$logtype,$remark='问诊订单','wenzhen_order',$order_id);
                if($rs_wallet['status'] === false){
                    Db::rollback();
                    $this->error($rs_wallet['msg']);
                }
            }

            //医生接诊量
            Db::name('doctor')->where('id',$wenzhen_order['doctor_id'])->setInc('ordernum');

            Db::commit();
            $this->success('已挂断');
        }

        //没接通
        if($wenzhen_order['status'] == 10){
            if($end_rule == 'user'){
                $this->success('已挂断');
            }else{
                //如果是医生挂断并且这个订单一次都没有接通，那就直接按拒绝接诊，结束订单
                //参考医生发起退珍
                Db::startTrans();

                $wenzhen_order = Db::name('wenzhen_order')->where('id',$order_id)->lock(true)->find();

                //修改订单
                $nowtime = time();
                $update = [
                    'status' => 16,
                    'cancel_time' => $nowtime,
                    'cancel_reason' => '医生挂断未接诊',
                    'finish_time' => $nowtime,
                ];

                //余额支付的直接退款
                if($wenzhen_order['pay_type'] == 'wallet'){

                    //用户加钱
                    $logtype = $wenzhen_order['ordertype'] == 1 ? 13 : 14;
                    $rs_wallet = model('wallet')->lockChangeAccountRemain($wenzhen_order['user_id'],'money',$wenzhen_order['total_fee'],$logtype,$remark='医生挂断未接诊','wenzhen_order',$order_id);
                    if($rs_wallet['status'] === false){
                        Db::rollback();
//                        $this->error($rs_wallet['msg']);
                        $this->error('医生挂断了');
                    }

                    //订单退款参数
                    $update['refund_price']  = $wenzhen_order['total_fee'];
                    $update['refund_status'] = 3;
                }else{
                    $update['refund_status'] = 1; //待退款

                    //发起退款
                    $Wenzhenorder_model = new Wenzhenorder;
                    $refund_rs = $Wenzhenorder_model->old_refund($wenzhen_order,$wenzhen_order['total_fee']);
                    if($refund_rs === true){
                        $update['refund_status'] = 3; //退款完成
                    }
                }

                $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->update($update);
                if(!$update_rs){
                    Db::rollback();
                    $this->error('医生挂断了');
                }

                Db::commit();
                $this->success('医生挂断并取消了订单');
            }
        }

        //没用的兜底
        $this->success('订单错误,请刷新重试');
    }

}
