<?php
/**
 * Created by PhpStorm.
 * User: Yuanhang Liu
 * Date: 20-10-15
 * Time: 下午8:46
 */

namespace App\Http\Controllers\Api\V2;

use App\Models\Docter;
use App\Models\Order;
use App\Models\Patient;
use App\Models\CallLog;
use App\Models\OrderPatient;
use App\Models\DocterOrganization;
use App\Models\Suggest;
use App\Models\User;
use App\Models\UserMessages;
use App\Models\Organization;
use App\Http\Controllers\Api\V2\CommonController as Commons;
use Illuminate\Support\Facades\DB;
use App\Models\Axb;
use App\Models\CallPhone;

/**
 * 咨询订单用户类
 * Class PatientController
 * @package App\Http\Controllers\Api\V2
 */
class PatientController extends AuthController
{
    protected $relationSearch = true;
    /**
     * @return mixed
     * 患者咨询列表
     * @author Yuanhang Liu & Xiaoyun Liu
     */
    public function orderPatientList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'curPage' => 'required|integer',
            'pageSize' => 'required|integer',
        ]);
        $pageSize = ($req['curPage']-1)*$req['pageSize'];
        $user = $this->user;
        $doctor_id = $user['id'];
        $where = [];
        $order=['created_at','desc'];

        $where['docter_id'] = $doctor_id;
        if (isset($req['appointment']) && $req['appointment']==1){
            // 门诊预约
            $where['product_type'] = 3;
            if (isset($req['timeSort']) && $req['timeSort']=='0') {
                $order = ['order_patients.appoint_start_time','asc']; //预约时间正序
            }
            if (isset($req['timeSort']) && $req['timeSort']=='1') {
                $order= ['order_patients.appoint_start_time','desc']; //预约时间倒叙
            }
            if (isset($req['timeSort']) && $req['timeSort']=='2') {
                $order = ['created_at','asc']; //下单时间正序
            }
            if (isset($req['timeSort']) && $req['timeSort']=='3') {
                $order = ['created_at','desc']; //下单时间倒叙
            }

            if (isset($req['comStatus']) && $req['comStatus']=='0') {
                $comstatus = [1,2,3];
                $where[] = [function($query) use ($comstatus){
                    $query->whereIn('order_status', $comstatus);//处理中
                }];
            }
            if (isset($req['comStatus']) && $req['comStatus']=='1') {
                $where['order_status'] = 4; //已完成

            }
        }else{
            // 图文和电话的
            $ids = [1,2];
            $where[] = [function($query) use ($ids){
                $query->whereIn('product_type', $ids);
            }];
            if(isset($req['typeAll']) && $req['typeAll']==1){
                $where['product_type']=2;//图文咨询
            }
            if(isset($req['typeAll']) && $req['typeAll']==2){
                $where['product_type']=1;//电话咨询
            }
            if(isset($req['processing']) && $req['processing']==0){
                $status = [1,2,3];
                $where[] = [function($query) use ($status){
                    $query->whereIn('order_status', $status);//处理中
                }];
            }
            if(isset($req['processing']) && $req['processing']==1){
                $where['order_status'] = 4; //历史记录，已完成订单
            }
        }


//        $data = Order::With(['orderPatient'=>function($query) use ($orders){
//            $query->orderBy($orders[0],$orders[1]);
//        }])->where($where)->orderBy($order[0],$order[1])->skip($pageSize)->take($req['pageSize'])->groupBy('id')->get()->toArray();
        $data = DB::table('orders')
                ->leftJoin('order_patients','order_patients.order_id','=','orders.id')
                ->select(['orders.*','order_patients.birthday as obirthday','order_patients.appoint_start_time','order_patients.name as oanme'])
                ->where($where)->orderBy($order[0],$order[1])
                ->skip($pageSize)->take($req['pageSize'])
                ->groupBy('id')
                ->get()->toArray();

//        $data = Order::with('orderPatient')->where($where)->skip($pageSize)->take($req['pageSize'])->groupBy('id')->toSql();
//        $data = OrderPatient::with("order")->where('id', $user['id'])->orderBy('id', 'desc')->limit($pageSize,$req['pageSize'])->get()->toarray();
        $list = [];
        try {

            foreach ($data as $k=>$v){
                $v = get_object_vars($v);
                if (!$v['obirthday']){
                    unset($list[$k]);
                }else{
                    $list[$k]['id'] = $v['id'];
                    $list[$k]['user_id'] = $v['user_id'];
                    $list[$k]['order_sn'] = $v['order_sn'];
                    $list[$k]['zl'] = $v['product_type'];
                    $list[$k]['zt'] = $v['order_status'];
                    unset($list[$k]['order_status'],$list[$k]['product_type']);
                    $list[$k]['created_at'] = $v['created_at'];
                    $list[$k]['appoint_time'] = empty($v['appoint_start_time'])?'---':date('Y-m-d H:i:s',$v['appoint_start_time']);
                    $list[$k]['name'] = $v['oanme'];
                    $list[$k]['birthday'] = numBirthday($v['obirthday']);
                }

            }

            return out($list);
        }catch (\Exception $e){
            return out($e->getFile().'中第 '.$e->getLine().'行发生了 '.$e->getMessage().'错误');
        }
        return out($list);
    }


    public function mzPutOrder(){

    }
    /**
     * @return mixed
     * 完成订单
     * @author Yuanhang Liu & Xiaoyun Liu
     */
    public function orderPatientok(){
        $req = request()->post();
        $this->validate(request(), [
            'order_id|订单id' => 'required|integer',
            'pathogen|病因' => 'required',
            'suggest|建议' => 'required',
            'patient_id|患者ID' => 'required',

        ]);
        $user = $this->user;
        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
        if (!$find){
            return out('',500,'订单错误！');
        }
        if ($find['order_status']>3){
            return out('',500,'此订单不可操作！');

        }
        $lable = '';
        switch ($find['product_type']){
            case 1:
                $lable = '电话咨询';
                break;
            case 2:
                $lable = '图文咨询';
                break;
            case 3:
                $lable = '门诊预约';
                break;
            case 4:
                $lable = '疫苗接种预约';
                break;
            case 5:
                $lable = '儿保预约';
                break;
            case 6:
                $lable = '服务包';
                break;
            default:
                $lable ='参数错误！';
        }
        $relation_id = '';
        if ($find['product_type']==1 || $find['product_type']==2){
            // 需要有意见单的
            $suggests = Suggest::create([
                'order_id'=> $find['id'],
                'user_id'=> $find['user_id'],
                'symptoms'=> $req['symptoms'],
                'pathogen'=> $req['pathogen'],
                'suggest'=> $req['suggest'],
                'patient_id'=> $req['patient_id']
            ]);
            $suggests = $suggests->toArray();
            $relation_id= $suggests['id'];
        }else{
            $relation_id= 0;
        }


        $status = $find['product_type'];
        $lab='';
        $mesid = $relation_id;
        if ($status==1){
            $lab = '电话咨询';
        }else if ($status==2){
            $lab = '图文咨询';
        }else if($status==3){
            $mesid = $find['id'];
            $lab = '门诊预约';
        }
        $order_sn = $find['order_sn'];
        $doctername = $user['name'];


        DB::beginTransaction();
        try {
            Order::where('id','=',$req['order_id'])->update(['order_status'=>4,'updated_at'=>date('Y-m-d H:i:s',time()),'end_time'=>time()]);
            Docter::where('id','=',$user['id'])->increment('service_persons');
            // 添加到用户记录中！
            UserMessages::create([
                'user_id'=>$find['user_id'],
                'docter_id'=>$user['id'],
                'status'=>1,
                'type'=>2,
                'relation_id'=>$mesid,
                'content'=>"您的 ".$lab." 订单，订单号".$order_sn."，医生".$doctername."已经确认完成（点击查看意见单）",
            ]);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return out('',500,$e->getMessage());
        }catch (\PDOException $e){
            DB::rollBack();
            return out('',500,$e->getMessage());
        }

        $axbwhere['docter_id'] = $user['id'];
        $axbwhere['user_id'] = $req['user_id'];
        $finds = Axb::where($axbwhere)->orderBy('id','desc')->first();

        if ($status==1 && $finds){
            $unlok = (new Commons())->unLokPhone($finds['xphone'],$finds['subs_id']);
            Axb::where(['subs_id'=>$finds['subs_id']])->delete();
        }

        return out();

    }


    /**
     * 门诊预约完成订单
     * @return mixed
     * @throws \Exception
     */
    public function mzPatientok(){
        $req = request()->post();
        $this->validate(request(), [
            'order_id|订单id' => 'required|integer',
        ]);
        $user = $this->user;
        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
        if (!$find){
            return out('',500,'订单错误！');
        }
        if ($find['order_status']>3){
            return out('',500,'此订单不可操作！');

        }
        $lable = '';
        switch ($find['product_type']){
            case 1:
                $lable = '电话咨询';
                break;
            case 2:
                $lable = '图文咨询';
                break;
            case 3:
                $lable = '门诊预约';
                break;
            case 4:
                $lable = '疫苗接种预约';
                break;
            case 5:
                $lable = '儿保预约';
                break;
            case 6:
                $lable = '服务包';
                break;
            default:
                $lable ='参数错误！';
        }
        $relation_id= 0;
        $status = $find['product_type'];
        $lab='';
        $mesid = $relation_id;
        if ($status==1){
            $lab = '电话咨询';
        }else if ($status==2){
            $lab = '图文咨询';
        }else if($status==3){
            $mesid = $find['id'];
            $lab = '门诊预约';
        }
        $order_sn = $find['order_sn'];
        $doctername = $user['name'];
        DB::beginTransaction();
        try {
            Order::where('id','=',$req['order_id'])->update(['order_status'=>4,'updated_at'=>date('Y-m-d H:i:s',time()),'end_time'=>time()]);
            Docter::where('id','=',$user['id'])->increment('service_persons');
            // 添加到用户记录中！
            UserMessages::create([
                'user_id'=>$find['user_id'],
                'docter_id'=>$user['id'],
                'status'=>1,
                'type'=>2,
                'relation_id'=>$mesid,
                'content'=>"您的 ".$lab." 订单，订单号".$order_sn."，医生".$doctername."已经确认完成（点击查看订单）",
            ]);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return out('',500,$e->getMessage());
        }catch (\PDOException $e){
            DB::rollBack();
            return out('',500,$e->getMessage());
        }

        return out();
    }

    /**
     * @return mixed
     * 接单
     * @author Yuanhang Liu & Xiaoyun Liu
     */
    public function putOrderPatient(){
        $req = request()->post();
        $this->validate(request(), [
            'order_id|订单id' => 'required|integer',
        ]);
        $user = $this->user;

        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
        $status = $find['product_type'];
        $lab='';
        if ($status==1){
            $lab = '电话咨询';
        }else if ($status==2){
            $lab = '图文咨询';
        }else if($status==3){
            $lab = '门诊预约';
        }
        $order_sn = $find['order_sn'];
        $order_id = $find['id'];
        $doctername = $user['name'];
//        1.电话咨询 2.图文咨询 3.门诊预约 4.疫苗接种预约 5.儿保预约 6.服务包 7.充值

        if (!$find){
            return out('',500,'订单错误！');
        }
        if ($find['order_status']!=2){
            return out('',500,'此订单已被接单或未付款！');
        }
        if ($find['payment_status']>=4){
            return out('',500,'此订单可能已完成！');
        }
        DB::beginTransaction();
        try {
            Order::where('id','=',$req['order_id'])->update(['order_status'=>3,'updated_at'=>date('Y-m-d H:i:s',time()),'receiving_time'=>time()]);
            // 添加到用户记录中！
            UserMessages::create([
                'user_id'=>$find['user_id'],
                'docter_id'=>$user['id'],
                'status'=>1,
                'type'=>1,
                'relation_id'=>$order_id,
                'content'=> "您的 ".$lab." 订单，订单号".$order_sn."，医生".$doctername."已经确认接单（点击查看订单详情）",
            ]);
            DB::commit();
            return out();
        }catch (\Exception $e){

            DB::rollBack();
            return out('',500,$e->getMessage());
        }catch (\PDOException $e){

            DB::rollBack();
            return out('',500,$e->getMessage());
        }
    }

    /**
     * @return mixed
     * 患者咨询详情
     * @author Yuanhang Liu & Xiaoyun Liu
     */
    public function orderPatientDetail()
    {
        $req = request()->post();
        $this->validate(request(), [
            'patient_id' => 'required|integer',
        ]);
        $data = [];
        // 订单查询
        $data = Order::with(['orderPatient','user','calllog'])->where('id', $req['patient_id'])->first()->toArray();

        // 通话记录查询
        $datas = CallLog::where('order_id', $req['patient_id'])->get();

        // 机构查询
        $user = $this->user;
        $doctor_id = (new Commons)->getUserIdByDoctorId($user['phone']);
        // 返回数组
        $res_patient = [];
        //电话咨询

        if($data['product_type']==1){

            $res_patient['patient_id'] = $data['order_patient']['id'];
            $res_patient['user_id'] = $data['user_id'];
            $res_patient['order_sn'] = $data['order_sn'];
            $res_patient['patient_id'] = $data['patient_id'];
            $res_patient['product_type'] = $data['product_type'];
            $res_patient['name']=$data['order_patient']['name'];//患者姓名
            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']);//年龄
            $res_patient['card_number']=$data['order_patient']['card_number'];//身份证号
            $res_patient['created_at']=$data['created_at'];//下单时间
            $res_patient['nickname']=$data['user']['nickname'];//下单用户
            $res_patient['receiving_time']=!empty($data['receiving_time'])?date('Y-m-d H:i:s',$data['receiving_time']):'---';//接单时间
            $res_patient['order_status']=$data['order_status'];//订单状态
            $res_patient['call_list']=[];//通话记录
            $res_patient['one_call'] = '';
            if ($data['calllog']){
                $res_patient['one_call'] = $data['calllog'][0]['call_time'];
                $res_patient['secret_no']=$data['calllog'][count($data['calllog'])-1]['secret_no'];//X号码
                foreach ($data['calllog'] as $ks=>$vs){
                    $res_patient['call_list'][$ks]['frequency']='通话'.($ks+=1);//拨打电话开始时间
                    $res_patient['call_list'][$ks]['start']=$vs['call_time'];//拨打电话开始时间
                    $res_patient['call_list'][$ks]['end']=$vs['ring_time'];//拨打电话结束时间
                    $res_patient['call_list'][$ks]['duration']=gmdate('i:s',$vs['talk_time']);//拨打电话结束时间

                }
            }
        }

        //图文咨询
        if($data['product_type']==2){
            $res_patient['order_sn'] = $data['order_sn'];
            $res_patient['patient_id'] = $data['patient_id'];
            $res_patient['user_id'] = $data['user_id'];
            $res_patient['user_name'] = $data['user']['nickname'];
            $res_patient['user_avatar'] = $data['user']['avatar'];
            $res_patient['product_type'] = $data['product_type'];
            $res_patient['name']=$data['order_patient']['name'];
            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']);
            $res_patient['card_number']=$data['order_patient']['card_number'];
            $res_patient['symptoms']=$data['order_patient']['symptoms'];//病情描述
            $res_patient['medical_imgs']=json_decode($data['order_patient']['medical_imgs'],true);//病情照片
            $res_patient['created_at']=$data['created_at'];//下单时间
            $res_patient['nickname']=$data['user']['nickname'];//下单用户
            $res_patient['receiving_time']=!empty($data['receiving_time'])?date('Y-m-d H:i:s',$data['receiving_time']):'---'; //接单时间
            $res_patient['order_status']=$data['order_status'];//接单时间
        }

        //门诊预约
        if($data['product_type']==3){
            $res_patient['order_sn'] = $data['order_sn'];
            $res_patient['patient_id'] = $data['patient_id'];
            $res_patient['product_type'] =$data['product_type'];
            $res_patient['name']=$data['order_patient']['name']; // 患者
            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']); //年龄
            $res_patient['card_number']=$data['order_patient']['card_number']; // 证件号
            $res_patient['appoint_time'] = date('Y年m月d日 H:i',$data['order_patient']['appoint_start_time']);// 预约时间
            $res_patient['order_status'] = $data['order_status'];// 订单状态
            $organization = Organization::where('id','=',$data['organization_id'])->first();
            if($organization){
                $organization = $organization->toArray();
                $res_patient['organization']= $organization['name']; // 门诊机构
            }else{
                $res_patient['organization']= ''; // 门诊机构

            }
            $res_patient['order_sn']=$data['order_sn'];//订单号
            $res_patient['created_at']=$data['created_at'];//下单时间
            $res_patient['nickname']=$data['user']['nickname'];//下单用户
        }

        return out($res_patient);
    }


    /**
     * 拨打电话/绑定电话
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/24 19:19
     */
    public function callPhones(){
        $req = request()->post();
        $user = $this->user;
        $this->validate(request(), [
            'order_id' => 'required',
            'user_id' => 'required|integer',
        ]);
        $docter_id = $user['id'];
        $docter_phone = $user['phone'];
        if(!$docter_phone){
            return out('',500,'医生电话不存在！');
        }
        $find = Order::with('orderPatient')->where('order_sn',$req['order_id'])->first()->toArray();
        if (empty($find['order_patient'])){
            return out('',500,'患者电话不存在');
        }
        $phone = $find['order_patient']['phone'];

        if($docter_phone==$phone){
            return out('',500,'医生和患者电话号不能一样！');

        }
        $wheres['docter_id'] = $docter_id;
        $wheres['user_id'] = $req['user_id'];
        $commons = new Commons();
        $finds = Axb::where($wheres)->orderBy('id','desc')->first();

        if ($finds){
            $querylok = $commons->QuerySubsId($finds['xphone']);
            if ($querylok['Code']=='OK'){
                // 可能是数组
                $new_arr = explode(',',$querylok['SubsId']);
                foreach ($new_arr as $v){
                    $queryCallStatus = $commons->QuerySubscriptionDetail($finds['xphone'],$v);
                    if ($queryCallStatus['Code']=='OK'){
                        if ($queryCallStatus['Code']=="OK"){
                            if ($queryCallStatus['SecretBindDetailDTO']['PhoneNoA']==$docter_phone&&$queryCallStatus['SecretBindDetailDTO']['PhoneNoB']==$phone){
                                return out($finds['xphone']);
                            }else{
                                if ($phone){
                                    $callModel = $commons->BindAxb($docter_phone,$phone);
                                    if ($callModel['Code']=="OK"){
                                        Axb::create([
                                            'docter_id'=>$docter_id,
                                            'user_id'=>$req['user_id'],
                                            'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
                                            'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
                                            'createtime'=>time(),
                                        ]);
                                        return out($callModel['SecretBindDTO']['SecretNo']);
                                    }
                                }else{
                                    return out('',500,'患者电话不存在');
                                }
                            }
                        }else{
                            if ($phone){
                                $callModel = $commons->BindAxb($docter_phone,$phone);
                                if ($callModel['Code']=="OK"){
                                    Axb::create([
                                        'docter_id'=>$docter_id,
                                        'user_id'=>$req['user_id'],
                                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
                                        'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
                                        'createtime'=>time(),
                                    ]);
                                    return out($callModel['SecretBindDTO']['SecretNo']);
                                }
                            }else{
                                return out('',500,'患者电话不存在');
                            }
                        }
                    }
                }


            }

        }else{
            if ($phone){
                $callModel = $commons->BindAxb($docter_phone,$phone);

                if ($callModel['Code']=="OK"){
                    Axb::create([
                        'docter_id'=>$docter_id,
                        'user_id'=>$req['user_id'],
                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
                        'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
                        'createtime'=>time(),
                    ]);
                    return out($callModel['SecretBindDTO']['SecretNo']);
                }else{
                    return out($callModel);
                }
            }else{
                return out('',500,'患者电话不存在');
            }
        }

    }


    /**
     * 电话随访
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/24 19:19
     */
    public function callPhoneSure(){
        $req = request()->post();
        $user = $this->user;
        $this->validate(request(), [
            'user_id' => 'required|integer',
        ]);
        $docter_id = $user['id'];
        $docter_phone = $user['phone'];
        if(!$docter_phone){
            return out('',500,'医生电话不存在！');
        }
        $find = User::where('id',$req['user_id'])->first()->toArray();
        $phone = $find['phone'];
        $wheres['docter_id'] = $docter_id;
        $wheres['user_id'] = $find['id'];
        $commons = new Commons();
        $finds = Axb::where($wheres)->orderBy('id','desc')->first();
        if ($finds){
            $querylok = $commons->QuerySubsId($finds['xphone']);
            if ($querylok['Code']=='OK'){
                $queryCallStatus = $commons->QueryCallStatus($phone,$querylok['SubsId']);
                if ($queryCallStatus['Code']=='OK'){
                    if ($queryCallStatus['SecretCallStatusDTO']!=4){
                        return out($finds['xphone']);
                    }else{
                        if ($phone){
                            $callModel = $commons->BindAxb($docter_phone,$phone);
                            if ($callModel['Code']=="OK"){
                                return out($callModel['SecretBindDTO']['SecretNo']);
                            }
                        }else{
                            return out('',500,'患者电话不存在');
                        }
                    }
                }
            }

        }else{
            if ($phone){
                $callModel = $commons->BindAxb($docter_phone,$phone);
                if ($callModel['Code']=="OK"){
                    Axb::create([
                        'docter_id'=>$docter_id,
                        'user_id'=>$req['user_id'],
                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
                        'createtime'=>time(),
                    ]);
                    return out($callModel['SecretBindDTO']['SecretNo']);
                }else{
                    return out($callModel);
                }
            }else{
                return out('',500,'患者电话不存在');
            }
        }

    }


}
