<?php

namespace app\api\controller\doctor;

use app\common\controller\Apic;
use think\Db;
use app\common\model\Wenzhenorder;
use app\common\library\Tenim;
/**
 * 问诊订单
 */
class Wenzhen extends Apic
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';



    //订单列表
    public function order_list(){

        $where = ['doctor_id'=>$this->auth->id];

        //订单状态
        $status = input('status',10);
        if($status != 'all'){
            $where['order.status'] = $status;

            if($status == 20){
                $where['order.status'] = ['IN',[20,25]];
            }
            if($status == 100){
                $where['order.status'] = ['IN',[13,16,18,22]];
            }
        }

        //问诊类型
        $ordertype = input('ordertype',0);
        if($ordertype){
            $where['order.ordertype'] = $ordertype;
        }

        //查询
        $field = [
            'order.id','order.user_id','order.doctor_id','order.order_no','order.createtime','order.status','order.ordertype','order.accept_time','order.video_time','order.book_time','order.cancel_reason','order.comefrom','order.video_model',
            'member.realname as member_realname','member.gender as member_gender','member.birthday as member_birthday','member.age as member_age',
            'member.marital_status','member.allergies_status','member.familymedical_status','member.chronicdisease_status',
        ];
        $list = Db::name('wenzhen_order')->alias('order')
            ->field($field)
            ->join('wenzhen_order_member member','order.id = member.order_id','LEFT')
            ->order('order.id desc')
            ->where($where)
            ->autopage()->select();

        if(!empty($list)){
            //循环处理
            foreach($list as $key => $val){
                //患者资料
                $gender = $val['member_gender'] == 1 ? '男' : '女';
                $age = birthtime_to_age($val['member_birthday']).'岁';
                if($val['comefrom'] == 2){
                    $age = $val['member_age'].'岁';
                }
                $marital = $val['marital_status'] == 1 ? '已婚' : '未婚';
                $val['member_info'] = $gender.'|'.$age.'|'.$marital;


                $allergies_status      = $val['allergies_status'] == 1 ? '有' : '无';
                $familymedical_status  = $val['familymedical_status'] == 1 ? '有' : '无';
                $chronicdisease_status = $val['chronicdisease_status'] == 1 ? '有' : '无';
                $val['member_remark']  = $allergies_status.'过敏史、'.$familymedical_status.'家族遗传史、'.$chronicdisease_status.'慢性病/肿瘤/手术/放射治疗';

                unset($val['member_gender']);
                unset($val['member_birthday']);
                unset($val['marital_status']);
                unset($val['allergies_status']);
                unset($val['familymedical_status']);
                unset($val['chronicdisease_status']);

                //追加
                $val = $this->orderinfo_appen($val);

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

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

    }

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


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

        //状态组合
        $status_array = [
            0  => 0,
            3  => 3,
            10 => 10,
            13 => 100, //已退珍
            16 => 100, //已退珍
            18 => 100, //已退珍
            20 => 20,             //咨询中
            22 => 100, //已退珍
            25 => 20,             //咨询中
            30 => 30
        ];
        $val['status'] = isset($status_array[$val['status']]) ? $status_array[$val['status']] : $val['status'];

        $val['feedback_images'] = empty($val['feedback_images']) ? '' : $val['feedback_images'];

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

    //订单状态备注枚举
    //状态:0=未付款,3=已失效,10=待接诊,13=用户退诊,16=医生未接诊,18=医生退诊,20=已接诊,22=超时未拨打,25=视频通话中,30=问诊完成

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

        //订单详情
        $field = [
            'id','order_no','user_id','member_id','doctor_id','ordertype','total_fee','book_time','createtime','status','cancel_time','cancel_reason','video_model',
            'pay_type','pay_time','accept_time','video_time','finish_time','feedback_time','feedback_remark','feedback_images','comefrom'
        ];
        $wenzhen_order = Db::name('wenzhen_order')->field($field)->where('doctor_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']);

        if($wenzhen_order['comefrom'] == 1){
            $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'] == 1 && $wenzhen_order['ordertype'] == 2 && $wenzhen_order['status'] == 20){  //25也可以，25倍被强制改成20了
            if(time() + 3600 >= $wenzhen_order['book_time']){ //距离预约时间1小时内就可以拨打
                $wenzhen_order['video_call_switch'] = 1;
            }
        }


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

    //退珍
    //因为存在第三方，悲观锁
    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('doctor_id',$this->auth->id)->where('id',$order_id)->lock(true)->find();
        if(empty($wenzhen_order)){
            Db::rollback();
            $this->error('不存在的订单');
        }

        if($wenzhen_order['status'] != 10){
            Db::rollback();
            $this->error('待接诊订单才能退诊');
        }

        //修改订单
        $nowtime = time();
        $update = [
            'status' => 18,
            'cancel_time' => $nowtime,
            'cancel_reason' => input('cancel_reason','医生主动退珍'),
            'finish_time' => $nowtime,
        ];


        //app用户，需要退款
        if($wenzhen_order['comefrom'] == 1){
        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']);
            }

            //订单退款参数
            $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['refund_price']  = $wenzhen_order['total_fee'];
            }
        }
        }

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

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

    }
    //接珍
    public function jiezhen(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

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

        if($wenzhen_order['video_model'] == 2){
            $this->error('即时视频问诊不需要主动接诊');
        }

        if($wenzhen_order['status'] != 10){
            $this->error('待接诊订单才能接诊');
        }

        //修改订单
        $nowtime = time();
        $update = [
            'status' => 20,
            'accept_time' => $nowtime,
        ];

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

        //发送im消息给用户
        if($wenzhen_order['ordertype'] == 1){
            $tenim = new Tenim();
            $message = [
                'businessID' => 'order_status_doctor',
                'name' => '您已接诊',
                'status' => '20',
                'id' => (string)$order_id,
                'content' => '请尽快联系患者，超时将自动取消订单',
            ];
            $rs = $tenim->sendCustomMessageToUser('user'.$wenzhen_order['user_id'],'doctor'.$wenzhen_order['doctor_id'],$message);

            $message = [
                'businessID' => 'order_status',
                'name' => '医生已接诊',
                'status' => '20',
                'id' => (string)$order_id,
                'content' => '请补充问题,便于医生更快的确认病情',
            ];
            $rs = $tenim->sendCustomMessageToUser('user'.$wenzhen_order['user_id'],'doctor'.$wenzhen_order['doctor_id'],$message);

            //发送im消息给用户，让他能输入
            $message = [
                'businessID' => 'order_status_doctor_type',
                'name' => '',
                'status' => '20',
                'id' => (string)$order_id,
                'content' => '',
            ];
            $rs = $tenim->sendCustomMessageToUser('user'.$wenzhen_order['user_id'],'doctor'.$wenzhen_order['doctor_id'],$message);
        }

        $this->success('接珍成功');
    }

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

        //订单详情
        $order_id = input('order_id',0);
        $wenzhen_order = Db::name('wenzhen_order')->where('doctor_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('user'.$wenzhen_order['user_id']);
            if($rs_online != true){
                $this->error('患者现在不在线,请稍后拨打');
            }

            $this->success();
        }
        if($wenzhen_order['status'] != 20){
            $this->error('订单未接诊');
        }

        if(time() + 3600 < $wenzhen_order['book_time']){
            $this->error('未到预约时间');
        }

        //判断患者在线状态
        $tenim = new Tenim();
        $rs_online = $tenim->is_online('user'.$wenzhen_order['user_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('doctor_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();

            $this->success('操作成功',$rs);
        }
        if($wenzhen_order['status'] != 20){
            $this->error('订单未接诊');
        }

        if(time() + 3600 < $wenzhen_order['book_time']){
            $this->error('未到预约时间');
        }

        //判断患者在线状态

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

        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->where('status',20)->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 finish(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

        //订单详情
        $order_id = input('order_id',0);
        Db::startTrans();
        $wenzhen_order = Db::name('wenzhen_order')->where('id',$order_id)->lock(true)->find();
        if(empty($wenzhen_order)){
            Db::rollback();
            $this->error('不存在的订单');
        }
        if($wenzhen_order['doctor_id'] != $this->auth->id){
            Db::rollback();
            $this->error('不存在的订单');
        }

        if($wenzhen_order['status'] == 30){
            Db::rollback();
            $this->error('订单已完成无需重复操作');
        }
        if($wenzhen_order['ordertype'] == 1){
            if($wenzhen_order['status'] != 20){
                Db::rollback();
                $this->error('已接诊订单才能完成');
            }

            $old_status = 20;
        }
        if($wenzhen_order['ordertype'] == 2){
            if($wenzhen_order['status'] != 25){
                Db::rollback();
                $this->error('尚未发起视频，不能结束');
            }

            $old_status = 25;
        }

        //修改订单
        $nowtime = time();
        $update = [
            'status' => 30,
            'finish_time' => $nowtime,
        ];

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

        //订单状态
        $update_rs = Db::name('wenzhen_order')->where('id',$order_id)->where('status',$old_status)->update($update);
        if(!$update_rs){
            Db::rollback();
            $this->error('操作失败');
        }

        //医生接诊量
        Db::name('doctor')->where('id',$this->auth->id)->setInc('ordernum');

        Db::commit();

        //发送im消息给用户，让他不能再输入
        if($wenzhen_order['ordertype'] == 1){
            $tenim = new Tenim();
            $message = [
                'businessID' => 'order_status_doctor_type',
                'name' => '',
                'status' => '30',
                'id' => (string)$order_id,
                'content' => '',
            ];
            $rs = $tenim->sendCustomMessageToUser('user'.$wenzhen_order['user_id'],'doctor'.$wenzhen_order['doctor_id'],$message);
        }

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

    //反馈
    public function feedback(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

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

        if($wenzhen_order['status'] != 30){
            //$this->error('已完成订单才能反馈');
        }

        if(in_array($wenzhen_order['status'],[0,3,10,13,16,18,22])){
            $this->error('该订单不能反馈结果');
        }

        //修改订单
        $nowtime = time();
        $update = [
            'feedback_time' => $nowtime,
            'feedback_remark' => input('feedback_remark',''),
            'feedback_images' => input('feedback_images',''),
        ];

        Db::startTrans();

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

        Db::commit();
        $this->success('反馈成功');
    }
}
