<?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_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('该医生未开通图文问诊');
            }
            $price = $doctor_info['typing_price'];
        }
        if($ordertype == 2){
            if($doctor_info['video_switch'] != 1){
                $this->error('该医生未开通视频问诊');
            }
            $price = $doctor_info['video_price'];
        }
        if($price <= 0){
            $this->error('价格为零');
        }

        //排班判断
        if($ordertype == 1){
            $book_time = 0;
        }
        if($ordertype == 2){
            //检查
            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'],//有效订单
            ];
            $order_count = Db::name('wenzhen_order')->where($map)->count();
            if($order_count >= 4){
                $this->error('该时间点已排满,请重选预约时间');
            }

        }

         //订单数据
        $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
        ];

        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',
            '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;
                }

                $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_val = $status_data[$val['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){
            $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){
            $remain_time = $val['video_time'] + (config('site.accept_videoorder_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;
            }
        }

        $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,
            ],
            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'=>'Your order has been returned for consultation',
                '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;

        $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(!in_array($wenzhen_order['status'],[10,20])){
            Db::rollback();
            $this->error('当前订单不能退诊');
        }

        //超过支付时间一小时不能退
        if( time() - $wenzhen_order['pay_time'] > 3600){
            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('退珍成功');
    }
}