<?php

namespace app\api\controller\tvuser;

use app\common\controller\Api;
use think\Db;
use app\common\library\Tenim;

/**
 * 问诊订单，使用自动注册的用户
 */
class Wenzhen extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    //添加成员
    private function add_member(){
        $field = [
            'gender',
            'age',
            'marital_status',
            'allergies_status',
            'familymedical_status',
            'chronicdisease_status',
        ];

        $data = request_post_hub($field);

        //选是，也要有点内容
        if($data['allergies_status'] == 1){
            $data['allergies_text'] = '是';
        }
        if($data['familymedical_status'] == 1){
            $data['familymedical_text'] = '是';
        }
        if($data['chronicdisease_status'] == 1){
            $data['chronicdisease_text'] = '是';
        }

        $data['user_id'] = $this->auth->id;
        $data['realname'] = $this->auth->nickname;

        return $data;
    }

    //判断是否 移动融合包的vip
    private function checkvip(){
        $is_vip = 0;

        $tv_userid = $this->auth->tv_userid;

        //跨数据库查询
        $tv_user = Db::connect('database_tv')->name('hu_user')->where('id',$tv_userid)->find();
        if(!empty($tv_user)){
            $is_vip = $tv_user['is_vip'];
        }

        return $is_vip;
    }

    //创建订单
    public function create_order(){

        //判断用户来源
        if($this->auth->comefrom != 2){
            $this->error('用户错误');
        }

        //判断是否 健康E家自己的vip
        $checkvip = $this->checkvip();
        if(!$checkvip){
            $this->error('您不是VIP用户','',402);
        }

        //检查本月是否已经下过一个有效单了
        $mouth_times = config('site.tv_wenzhen_month_times');
        $checkmap = [
            'user_id' => $this->auth->id,
            'comefrom'=> 2,
            'status'  => ['IN','10,20,25,30'],//有效订单
        ];
        $check_order = Db::name('wenzhen_order')->where($checkmap)->whereTime('createtime','month')->count();
        if($check_order >= $mouth_times){
            //$this->error('您本月的免费问诊次数已用完');
        }

        //问诊患者
        $member_data = $this->add_member();

        //医生信息
        $doctor_id = input('doctor_id',0);
        $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('不存在的医生');
        }

        if($doctor_info['video_switch'] != 1){
            $this->error('该医生未开通视频问诊');
        }
        if($doctor_info['video_model'] == 2 && $doctor['job_status'] != 1){ //即时方式，需要在上班中
            $this->error('该医生现在不在上班中');
        }

        //订单信息
        $auth_id = $this->auth->id;
        $order_no = createUniqueNo('TV',$auth_id);
        $ordertype = 2;

        //价格
        $price = 0;


        //排班判断
        if($ordertype == 2){
            if($doctor_info['video_model'] == 1){  //排班预约

                $book_time = input('book_time','');
                if(empty($book_time)){
                    $this->error('没有选择预约时间');
                }
                $book_time = strtotime($book_time);
                //检查
                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'  => 0,
            'doctor_id'  => $doctor_id,
            'ordertype'  => $ordertype,
            'total_fee'  => $price,
            'book_time'  => $book_time,
            'createtime' => time(),

            'status'     => 10,//订单状态enum
            'pay_type'     => 'tvvip',
            'pay_time'     => time(),
            'comefrom'     => 2,
            '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['order_id']       = $order_id;
        $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 order_list(){
        //判断用户来源
        if($this->auth->comefrom != 2){
            $this->error('用户错误');
        }

        $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.book_time','order.status','order.ordertype','order.accept_time','order.video_time','order.doctor_id','order.cancel_reason','order.video_model',
            'doctor.avatar as doctor_avatar','doctor.nickname as doctor_nickname','doctor.hospital as doctor_hospital',
            'keshi.name as keshi_name',
            'level.name as level_name',
        ];
        $list = Db::name('wenzhen_order')->alias('order')
            ->field($field)
            ->join('doctor','order.doctor_id = doctor.id','LEFT')
            ->join('doctor_level level','doctor.level_id = level.id','LEFT')
            ->join('keshi','doctor.keshi_id = keshi.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){

                //医生原因的退款，都直接算到退珍
                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);

    }

    //订单详情
    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('id',$order_id)->find();
        if(empty($wenzhen_order)){
            $this->error('不存在的订单');
        }
        $wenzhen_order = info_domain_image($wenzhen_order,['feedback_images']);
        $wenzhen_order['feedback_images'] = empty($wenzhen_order['feedback_images']) ? '' : $wenzhen_order['feedback_images'];

        //医生详情
        $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 tuizhen(){
        $apilimit = $this->apiLimit();
        if(!$apilimit){
            $this->error('操作频繁');
        }

        //判断用户来源
        if($this->auth->comefrom != 2){
            $this->error('用户错误');
        }

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

        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('comefrom',2)->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('当前订单不能退诊');
            }
            //没付款，所以没有支付时间限制
        }else{
            //即时模式，已付款没接的能退
            if($wenzhen_order['status'] != 10){
                Db::rollback();
                $this->error('当前订单不能退诊');
            }
        }


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


        $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(){
        //判断用户来源
        if($this->auth->comefrom != 2){
            $this->error('用户错误');
        }

        //订单详情
        $order_id = input('order_id',0);
        $wenzhen_order = Db::name('wenzhen_order')->where('user_id',$this->auth->id)->where('comefrom',2)->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('comefrom',2)->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('comefrom',2)->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('操作失败');
            }

            //给医生结算钱

            //医生接诊量
            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,
                ];

                //没有支付就没有退款


                $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('订单错误,请刷新重试');
    }
}
