<?php
/**
 * Created by PhpStorm.
 * User: Yuanhang Liu & Xiaoyun Liu
 * Date: 20-10-14
 * Time: 下午2:50
 */

namespace App\Http\Controllers\Api\V2;

use App\Http\Controllers\Api\V1\AuthController;
use App\Models\Docter;
use App\Models\Office;
use App\Models\Order;
use App\Models\OrderPack;
use App\Models\OrderPatient;
use App\Models\Patient;
use App\Models\Qualification;
use App\Models\Suggest;
use App\Models\Areas;
use App\Models\Collection as Collections;
use App\Models\Organization;
use App\Models\DocterTimes;
use App\Models\DocterOrganization;
use App\Http\Controllers\Api\V2\CommonController as Commons;
use App\Models\Team;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\ObjectId;
use PhpParser\Comment\Doc;
use App\Models\DocterUser;
use App\Models\Schedule;
use App\Models\TimePeriod;
use App\Models\SchedulePeriod;
use App\Models\DocterMessage;
use App\Models\Evaluate;
use App\Models\UserDocter;
use App\Models\ServiceApply;
use App\Models\SystemConfig;
use App\Models\WeekSchedule;
use App\Models\SelfSchedule;
use App\Models\DocterSetting;
use App\Models\DocterServiceTimes;
use App\Models\CallLog;
use App\Models\ImMessage;
use App\Models\DocterLable;


/**
 * 医生相关类
 * Auth Yuanhang Liu
 * Date 2020/10/14 15:06
 * Class DoctorController
 * @package App\Http\Controllers\Api\V2
 */
class DoctorController extends AuthController
{

    /**service_schedule
     * @return \Illuminate\Http\JsonResponse
     * 首页医生个人信息接口
     */
    public function doctorInfor()
    {
        $req = $this->user;
        $data = Docter::where('phone', $req['phone'])->first(['id', 'name', 'avatar', 'label', 'sign', 'intro', 'service_days', 'service_persons','password', 'eva_num', 'score', 'is_then', 'created_at']);

        if (!empty($data)) {

            // 获取标签
            $LabFind = [];
            if ($data['label']!='无'){
                if(count($data['label'])!=0){
                    $labstr = $data['label'];
                    $LabFind = DocterLable::whereIn('id',$labstr)->where('status',1)->select('label_name')->get();
                }
            }



            $data['label'] = $LabFind;
//            $counts = Evaluate::where('docter_id', '=', $req['id'])->count();
            $evalList = Evaluate::where('docter_id', '=', $req['id'])->get();
            $counts = count($evalList);


            $data['eva_num'] = $counts;
            $soc = 0;
            if ($counts != 0) {
                $evalList = $evalList->toArray();
                foreach ($evalList as $k => $v) {
                    $soc += $v['score'];
                }
                $data['score'] = upDecimal($soc / $counts, 1);
            }

            $data['service_days'] = numDays(date('Y-m-d', strtotime($data['created_at'])));
            return out($data);
        } else {
            return exit_out($data, 1, '参数错误，数据不存在');
        }

    }

    /**
     * 医生端个人信息修改
     * @return mixed
     */
    public function doctorInfoEdit()
    {
        $user = $this->user;
        $doctor_id = $user['id'];
        if (request()->isMethod('post')) {
            $req = request()->post();
            $this->validate(request(), [
                'avatar' => 'string',
                'sign' => 'max:255',
//            'phone|手机号不正确' => 'regex:/^1[3456789][0-9]{9}$/',
                'intro' => 'max:2555'
            ]);
            $data = [];
            if (isset($req['avatar']) && !empty($req['avatar'])) {
                $data['avatar'] = $req['avatar'];
            }
            if (isset($req['sign']) && !empty($req['sign'])) {
                $data['sign'] = $req['sign'];
            }
            if (isset($req['intro']) && !empty($req['intro'])) {
                $data['intro'] = $req['intro'];
            }

            if (empty($data)) {
                return out();
            }
            if ($doctor_id) {
                $save = Docter::where('id', $doctor_id)->update($data);
                return out();
            }
        } else {
            // get提交哈
            $list = Docter::where('id', '=', $doctor_id)->first()->toArray();
            // 头像，个人标签，服务简介展示
            $data = [
                'avatar' => !empty($list['avatar'])?$list['avatar']:'',
                'sign' => !empty($list['sign'])?$list['sign']:'',
                'intro' => !empty($list['intro'])?$list['intro']:'',
            ];
            return out($data);
        }
    }


    /**
     * 修改密码
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/4 18:19
     */
    public function passwordEdit()
    {
        $user = $this->user;
        $doctor_id = $user['id'];
        $req = request()->post();
        $this->validate(request(), [
            'lis:原密码' => 'string',
            'newpassword:新密码' => 'string',
        ]);
        $data = [];
        $data = Docter::where('id', '=', $doctor_id)->first()->toArray();
        $password = md5(md5(md5($req['newpassword'])));
        if ($data['password'] == '' || !$data['password']) {
            // 说明第一次直接跳过
            $save = Docter::where('id', $doctor_id)->update(['password' => $password]);
            return out();
        } else {
            if(isset($req['lis'])&&!empty($req['lis'])){
                $oldpassword = md5(md5(md5($req['lis'])));
                if ($oldpassword != $data['password']) {
                    return out('', '401', '旧密码错误');
                } else {
                    $save = Docter::where('id', $doctor_id)->update(['password' => $password]);
                    return out();
                }
            }else{
                return out('', '401', '请输入旧密码');

            }

        }
    }


    /**
     * 获取基本设置
     * @return mixed
     */
    public function getSettingBase(){
        $user = $this->user;
        $doctor_id = (new Commons)->getUserIdByDoctorId($user['phone']);
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
        $finds['is_chat'] = $finds['is_chat'] == 0 ? false : true;
        $finds['is_phone'] = $finds['is_phone'] == 0 ? false : true;
        $finds['is_appoint'] = $finds['is_appoint'] == 0 ? false : true;
        $finds['is_chat_status'] = $this->getStyStatus(1);
        $finds['is_phone_status'] = $this->getStyStatus(2);
        $finds['is_appoint_status'] = $this->getStyStatus(3);
        return out($finds);
    }

    /**
     * 获取图文设置
     * @return mixed
     */
    public function getSettingChat(){
        $user = $this->user;
        $doctor_id = $user['id'];
        (array)$list = [];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
        $list['is_chat'] = $finds['is_chat'] == 0 ? false : true;

        // 图文咨询时间
        $pic_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 2])->first();
        if ($pic_fins) {
            $pic_fins = $pic_fins->toArray();
            $pic_fins['service_time'] = json_decode($pic_fins['service_time']);
        } else {
            $pic_fins = [];
        }
        $list['list'] = $pic_fins;
        return out($list);
    }

    /**
     * 获取电话的设置
     * @return mixed
     */
    public function getSettingPhone(){
        $user = $this->user;
        $doctor_id = $user['id'];
        (array)$list = [];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
        $list['is_phone'] = $finds['is_phone'] == 0 ? false : true;
        // 图文咨询时间
        $phone_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 1])->first();
        if ($phone_fins) {
            $phone_fins = $phone_fins->toArray();
            $phone_fins['service_time'] = json_decode($phone_fins['service_time']);
        } else {
            $phone_fins = [];
        }
        $list['list'] = $phone_fins;
        return out($list);
    }

    /**
     * 获取门诊的设置
     * @return mixed
     */
    public function getSettingSchedule(){
        $user = $this->user;
        $doctor_id = $user['id'];
        (array)$list = [];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
        $list['is_schedule'] = $finds['is_appoint'] == 0 ? false : true;

        $newLists=[];
        $men_fins = DocterSetting::where(['docter_id' => $doctor_id, 'type' => 1])->orderBy('org_id','asc')->get();
        $org = DocterOrganization::with('organization')->where(['docter_id'=>$doctor_id,'state'=>1])->orderBy('organization_id','asc')->get();
        if ($org) {
            $org = $org->toArray();
            foreach ($org as $k => $v) {
                $org_pre[$k]['id'] = $v['organization']['id'];
                $org_pre[$k]['name'] = $v['organization']['name'];
            }
        }
        if ($men_fins) {
            $men_fins = $men_fins->toArray();

            foreach ($men_fins as $k => $v) {
                $men_fins[$k]['service_time'] = json_decode($v['service_time'],true);
            }

            $org_list=[];

            foreach ($org as $k=>$v){
                $org_list[$k]['docter_id'] = $doctor_id;
                $org_list[$k]['type'] = 1;
                $org_list[$k]['status'] = 2;
                $org_list[$k]['show_days'] = '';
                $org_list[$k]['service_times'] = '';
                $org_list[$k]['service_num'] = '';
                $org_list[$k]['org_id'] = $v['organization']['id'];
                $org_list[$k]['org_name'] = $v['organization']['name'];
                $org_list[$k]['appoint_price'] = '';
                $org_list[$k]['service_time'] = [
                    1=>['amStartTime'=>'','amEndTime'=>'','amPerson'=>''],
                    2=>['pmStartTime'=>'','pmEndTime'=>'','pmPerson'=>''],
                    3=>['nightStartTime'=>'','nightEndTime'=>'','nightPerson'=>''],
                ];
            }
            foreach ($org_list as $k=>$v){
                foreach ($men_fins as $kk=>$vv){
                    if ($v['org_id']==$vv['org_id']){
                        $org_list[$k]['docter_id'] = $doctor_id;
                        $org_list[$k]['type'] = 1;
                        $org_list[$k]['status'] = 2;
                        $org_list[$k]['show_days'] = $vv['show_days'];
                        $org_list[$k]['service_times'] = $vv['service_times'];
                        $org_list[$k]['service_num'] = $vv['service_num'];
                        $org_list[$k]['org_id'] = $vv['org_id'];
                        $org_list[$k]['org_name'] = $v['org_name'];
                        $org_list[$k]['appoint_price'] = $vv['appoint_price'];
                        $org_list[$k]['service_time'] = [
                            1=>['amStartTime'=>$vv['service_time'][1]['amStartTime'],'amEndTime'=>$vv['service_time'][1]['amEndTime'],'amPerson'=>$vv['service_time'][1]['amPerson']],
                            2=>['pmStartTime'=>$vv['service_time'][2]['pmStartTime'],'pmEndTime'=>$vv['service_time'][2]['pmEndTime'],'pmPerson'=>$vv['service_time'][2]['pmPerson']],
                            3=>['nightStartTime'=>$vv['service_time'][3]['nightStartTime'],'nightEndTime'=>$vv['service_time'][3]['nightEndTime'],'nightPerson'=>$vv['service_time'][3]['nightPerson']],
                        ];
                    }
                }

            }
            $newLists = $org_list;
        } else {
            $men_fins = [];
            foreach ($org as $k=>$v){
                $newLists[$k]['docter_id'] = $doctor_id;
                $newLists[$k]['type'] = 1;
                $newLists[$k]['status'] = 2;
                $newLists[$k]['show_days'] = '';
                $newLists[$k]['service_times'] = '';
                $newLists[$k]['service_num'] = '';
                $newLists[$k]['org_id'] = $v['organization']['id'];
                $newLists[$k]['org_name'] = $v['organization']['name'];
                $newLists[$k]['appoint_price'] = '';
                $newLists[$k]['service_time'] = [
                    1=>['amStartTime'=>'','amEndTime'=>'','amPerson'=>''],
                    2=>['pmStartTime'=>'','pmEndTime'=>'','pmPerson'=>''],
                    3=>['nightStartTime'=>'','nightEndTime'=>'','nightPerson'=>''],
                ];
            }
        }
        $list['list'] = $newLists;
        return out($list);
    }



    /**
     * 获取审核状态
     * @param $type
     * @return bool
     */
    public function getStyStatus($type)
    {
        $user = $this->user;
        $doctor_id = $user['id'];
        $where['docter_id'] = $doctor_id;
        $where['service_type'] = $type;
        $statusD = ServiceApply::where($where)->first();
        if ($statusD) {
            return $statusD;
        } else {
            return false;
        }
    }


    /**
     * 修改基本设置
     * @return mixed
     */
    public function saveSettingBase(){
        $req = request()->post();
        $data = json_decode($req['data'], true);
        $user = $this->user;
        $doctor_id = $user['id'];
        $list = [];
        isset($data['is_chat']) ? $data['is_chat'] == true ? $list['is_chat'] = 1 : $list['is_chat'] = 0 : '';
        isset($data['is_phone']) ? $data['is_phone'] == true ? $list['is_phone'] = 1 : $list['is_phone'] = 0 : '';
        isset($data['is_appoint']) ? $data['is_appoint'] == true ? $list['is_appoint'] = 1 : $list['is_appoint'] = 0 : '';
        Docter::where('id', $doctor_id)->update($list);
        return out();
    }


    /**
     * 修改图文设置
     */
    public function saveSettingChat(){
        $req = request()->post();
        $data = json_decode($req['data'], true);
        $user = $this->user;
        $doctor_id = $user['id'];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first();
        Db::beginTransaction();
        try {
            // 修改更多信息
            if ($finds['is_chat'] == 0) {
                if (isset($data['is_chat']) && !empty($data['is_chat'])) {
                    return out('', 500, '您未开启图文');

                    unset($data['is_chat']);
                }
            } else {
                if (isset($data['is_chat']) && !empty($data['is_chat'])) {
                    DocterServiceTimes::where(['docter_id'=>$doctor_id,'type'=>2])->delete();
                    $save_data = $data['is_chat'];
                    $newData = [];
                    $serviceData = [];
                    $newData['base_price'] = $save_data['base_price'];
                    $newData['step_price'] = $save_data['step_price'];
                    $serviceData[0]['docter_id']=$doctor_id;
                    $serviceData[0]['type']=2;
                    $serviceData[0]['start_time_period']=$save_data['amStartTime'];
                    $serviceData[0]['end_time_period']=$save_data['amEndTime'];
                    $serviceData[0]['start_time_line']=str_replace(':','',$save_data['amStartTime']);
                    $serviceData[0]['end_time_line']=str_replace(':','',$save_data['amEndTime']);

                    $serviceData[1]['docter_id']=$doctor_id;
                    $serviceData[1]['type']=2;
                    $serviceData[1]['start_time_period']=$save_data['pmStartTime'];
                    $serviceData[1]['end_time_period']=$save_data['pmEndTime'];
                    $serviceData[1]['start_time_line']=str_replace(':','',$save_data['pmStartTime']);
                    $serviceData[1]['end_time_line']=str_replace(':','',$save_data['pmEndTime']);

                    $serviceData[2]['docter_id']=$doctor_id;
                    $serviceData[2]['type']=2;
                    $serviceData[2]['start_time_period']=$save_data['nightStartTime'];
                    $serviceData[2]['end_time_period']=$save_data['nightEndTime'];
                    $serviceData[2]['start_time_line']=str_replace(':','',$save_data['nightStartTime']);
                    $serviceData[2]['end_time_line']=str_replace(':','',$save_data['nightEndTime']);

                    $service_times = [
                        1 => ['amStartTime' => $save_data['amStartTime'], 'amEndTime' => $save_data['amEndTime']],
                        2 => ['pmStartTime' => $save_data['pmStartTime'], 'pmEndTime' => $save_data['pmEndTime']],
                        3 => ['nightStartTime' => $save_data['nightStartTime'], 'nightEndTime' => $save_data['nightEndTime']],
                    ];
                    $newData['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
                    $newData['person'] = $save_data['person'];
                    $newData['type'] = $save_data['type'];
                    $pic_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 2])->first();
                    DocterServiceTimes::insert($serviceData);
                    if (empty($pic_fins)) {
                        $newData['docter_id'] = $doctor_id;
                        DocterTimes::create($newData);
                    } else {
                        $pic_fins = $pic_fins->toArray();
                        DocterTimes::where(['id' => $pic_fins['id']])->update($newData);
                    }
                }
            }
            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
     * @throws \Exception
     */
    public function saveSettingPhone(){
        $req = request()->post();
        $data = json_decode($req['data'], true);
        $user = $this->user;
        $doctor_id = $user['id'];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first();
        Db::beginTransaction();
        try {

            if ($finds['is_phone'] == 0) {
                if (isset($data['is_phone']) && !empty($data['is_phone'])) {
                    return out('', 500, '您未开启电话');
                    unset($data['is_phone']);

                }
            } else {
                if (isset($data['is_phone']) && !empty($data['is_phone'])) {
                    // 存入状态为1的操作
                    DocterServiceTimes::where(['docter_id'=>$doctor_id,'type'=>1])->delete();

                    $save_data = $data['is_phone'];


                    $newData = [];
                    $serviceData = [];

                    $newData['base_price'] = $save_data['base_price'];
                    $newData['step_price'] = $save_data['step_price'];

                    $serviceData[0]['docter_id']=$doctor_id;
                    $serviceData[0]['type']=1;
                    $serviceData[0]['start_time_period']=$save_data['amStartTime'];
                    $serviceData[0]['end_time_period']=$save_data['amEndTime'];
                    $serviceData[0]['start_time_line']=str_replace(':','',$save_data['amStartTime']);
                    $serviceData[0]['end_time_line']=str_replace(':','',$save_data['amEndTime']);

                    $serviceData[1]['docter_id']=$doctor_id;
                    $serviceData[1]['type']=1;
                    $serviceData[1]['start_time_period']=$save_data['pmStartTime'];
                    $serviceData[1]['end_time_period']=$save_data['pmEndTime'];
                    $serviceData[1]['start_time_line']=str_replace(':','',$save_data['pmStartTime']);
                    $serviceData[1]['end_time_line']=str_replace(':','',$save_data['pmEndTime']);

                    $serviceData[2]['docter_id']=$doctor_id;
                    $serviceData[2]['type']=1;
                    $serviceData[2]['start_time_period']=$save_data['nightStartTime'];
                    $serviceData[2]['end_time_period']=$save_data['nightEndTime'];
                    $serviceData[2]['start_time_line']=str_replace(':','',$save_data['nightStartTime']);
                    $serviceData[2]['end_time_line']=str_replace(':','',$save_data['nightEndTime']);

                    $service_times = [
                        1 => ['amStartTime' => $save_data['amStartTime'], 'amEndTime' => $save_data['amEndTime']],
                        2 => ['pmStartTime' => $save_data['pmStartTime'], 'pmEndTime' => $save_data['pmEndTime']],
                        3 => ['nightStartTime' => $save_data['nightStartTime'], 'nightEndTime' => $save_data['nightEndTime']],
                    ];
                    $newData['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
                    $newData['person'] = $save_data['person'];
                    $newData['type'] = $save_data['type'];
                    // 图文咨询时间
                    $phone_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 1])->first();
                    DocterServiceTimes::insert($serviceData);
                    if (empty($phone_fins)) {
                        $newData['docter_id'] = $doctor_id;
                        DocterTimes::create($newData);
                    } else {
                        $phone_fins = $phone_fins->toArray();
                        DocterTimes::where(['id' => $phone_fins['id']])->update($newData);
                    }
                }
            }
            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
     * @throws \Exception
     */
    public function saveSettingSchedule(){
        $req = request()->post();
        $data = json_decode($req['data'], true);
        $user = $this->user;
        $doctor_id = $user['id'];
        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first();
        $flag = false;

        Db::beginTransaction();
        try {
            if ($finds['is_appoint'] == 0) {
                if (isset($data['is_appoint']) && !empty($data['is_appoint'])) {
                    return out('', 500, '您未开启门诊');

                    unset($data['is_appoint']);
                }
            } else {
                // 此时可能有两个医院，为一个数组，一个一个入库
                if (isset($data['is_appoint']) && !empty($data['is_appoint'])) {
                    $save_data = $data['is_appoint'];
                    $setting_data = [];
                    $times_data = [];
                    // 查询除本地来
                    $edutime = DocterSetting::where(['docter_id' => $doctor_id, 'type' => 1])->get();
                    if ($edutime) {
                        $newedu = [];
                        foreach ($edutime as $k => $v) {
                            $newedu[$k]['org_id'] = $v['org_id'];
                            $newedu[$k]['service_times'] = $v['service_times'];
                        }
                        $flag_arr = [];
                        foreach ($newedu as $k => $v) {
                            foreach ($save_data as $kk => $vv) {
                                if ($v['org_id'] == $vv['org_id']) {
                                    if ($v['service_times'] != $vv['service_times']) {
                                        $flag_arr[] = $vv['org_id'];
                                    }
                                }
                            }
                        }
                        $flag = !empty($flag_arr) ? $flag_arr : false;
                    }
                    foreach ($save_data as $k => $v) {
                        if (!isset($v['service_times'])||empty($v['service_times'])){
                            unset($save_data[$k]);
                        }else{
                            DocterSetting::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
                            TimePeriod::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
                            $setting_data[$k]['docter_id'] = $doctor_id;
                            $setting_data[$k]['type'] = 1;
                            $setting_data[$k]['status'] = 2;
                            $setting_data[$k]['appoint_price'] = $v['base_price'];
                            $setting_data[$k]['show_days'] = $v['show_days'];
                            $setting_data[$k]['service_times'] = $v['service_times'];
                            $setting_data[$k]['service_num'] = $v['service_num'];
                            $setting_data[$k]['org_id'] = $v['org_id'];
                            $service_times = [
                                1 => ['amStartTime' => $v['amStartTime'], 'amEndTime' => $v['amEndTime'], 'amPerson' => $v['amPerson']],
                                2 => ['pmStartTime' => $v['pmStartTime'], 'pmEndTime' => $v['pmEndTime'], 'pmPerson' => $v['pmPerson']],
                                3 => ['nightStartTime' => $v['nightStartTime'], 'nightEndTime' => $v['nightEndTime'], 'nightPerson' => $v['nightPerson']],
                            ];
                            $setting_data[$k]['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
                            $setting_data[$k]['created_at'] = date('Y-m-d H:i:s', time());
                            $setting_data[$k]['updated_at'] = date('Y-m-d H:i:s', time());
                            // 第二步， 根据时长去生成24小时的时间段，也要存id

                            $timeList = $this->getTimeHoures($v['service_times']);
                            foreach ($timeList as $kk => $vv) {

                                $times_data[$k][$kk]['type'] = 1;

                                $times_data[$k][$kk]['docter_id'] = $doctor_id;
                                $times_data[$k][$kk]['start_time_period'] = $vv[0];
                                $times_data[$k][$kk]['end_time_period'] = $vv[1];
                                $times_data[$k][$kk]['org_id'] = $v['org_id'];
                            }
                        }

                    }
                    if($times_data&&$setting_data){
                        foreach ($times_data as $k => $v) {
                            TimePeriod::insert($v);
                        }
                        DocterSetting::insert($setting_data);
                    }
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return out('', 500, $e->getMessage());
        } catch (\PDOException $e) {
            DB::rollBack();
            return out('', 500, $e->getMessage());
        }



        if ($finds['is_appoint'] != 0 && isset($data['is_appoint']) && !empty($data['is_appoint'])) {
            /*去重新更新，自定义排班表，和排班详情表，因为时间段id发生了变化！*/
            if ($flag != false) {
                Db::beginTransaction();
                try {
                    $weekList = WeekSchedule::where('docter_id', $doctor_id)->get();
                    $moth_date = $this->date_bool();
                    $Wheres['schedule_type'] = 1;
                    $Wheres['docter_id'] = $doctor_id;
                    $counts = Schedule::where($Wheres)->whereBetween('schedule_date',[date('Y-m-d',time()),end($moth_date)['date']])->get();
                    if ($weekList && $counts) {
                        $wheres['docter_id'] = $doctor_id;
                        $wheres['schedule_type'] = 1;
                        $wheres[] = ['schedule_date','>=',date('Y-m-d',time())];
                        $list = SchedulePeriod::where($wheres)->whereIn('organization_id', $flag)->orderBy('schedule_date','asc')->get();
                        SchedulePeriod::where($wheres)->delete();
                        if ($list) {
                            $list = $list->toArray();
                            $selfList = [];
                            foreach ($list as $k => $v) {
                                if (!isset($selfList[$v['schedule_date']])) {
                                    $selfList[$v['schedule_date']] = $v;
                                    if ($v['type'] == 1) {
                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
                                    } else if ($v['type'] == 2) {
                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
                                    } else {
                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
                                    }
                                } else {
                                    if ($v['type'] == 1) {
                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
                                    } else if ($v['type'] == 2) {
                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
                                    } else {
                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
                                    }
                                }
                            }

                            // 占用效率
                            $scheduleLists = [];
                            foreach ($counts as $kk => $vv) {
                                foreach ($selfList as $k => $v) {
                                    if ($vv['schedule_date'] == $v['schedule_date']) {
                                        if ($v['ident']['zao_id']) {
                                            $times = $this->num_time($v['ident']['zao_id'], 1);
                                            if (!$times) {
                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
                                            }
                                            $maf = $this->getMaf($vv['id'], $times, ['organization_id' => $v['ident']['zao_id'],'me_sure'=>$v['me_sure'],'schedule_date' => $v['schedule_date'], 'type' => 1], $doctor_id);
                                            if ($maf) {
                                                foreach ($maf as $os) {
                                                    $scheduleLists[] = $os;
                                                }
                                            }
                                        }
                                        if ($v['ident']['xia_id']) {
                                            $times = $this->num_time($v['ident']['xia_id'], 2);
                                            if (!$times) {
                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
                                            }
                                            $maf = $this->getMaf($vv['id'], $times, ['organization_id' => $v['ident']['xia_id'],'me_sure'=>$v['me_sure'],'schedule_date' => $v['schedule_date'], 'type' => 2], $doctor_id);
                                            if ($maf) {
                                                foreach ($maf as $os) {
                                                    $scheduleLists[] = $os;
                                                }
                                            }
                                        }
                                        if ($v['ident']['wan_id']) {
                                            $times = $this->num_time($v['ident']['wan_id'], 3);
                                            if (!$times) {
                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
                                            }
                                            $maf = $this->getMaf($vv['id'], $times, ['organization_id' => $v['ident']['wan_id'], 'me_sure'=>$v['me_sure'],'schedule_date' => $v['schedule_date'], 'type' => 3], $doctor_id);
                                            if ($maf) {
                                                foreach ($maf as $os) {
                                                    $scheduleLists[] = $os;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            SchedulePeriod::insert($scheduleLists);
                        }
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return out('', 500, '2' . $$e->getMessage());
                } catch (\PDOException $e) {
                    DB::rollBack();
                    return out('', 500, '2' . $e->getMessage());
                }
            }
        }
        return out();
    }


    /**
     * 计算24小时的时间区间段
     * @param $minute 分钟比如：15
     * @return array
     */
    public function getTimeHoures($minute)
    {
        // 可选10分钟，15分钟，20分钟，30分钟，1个小时
        $start = strtotime(date("Y-m-d 00:00:00"));
        $end = strtotime(date("Y-m-d 23:59:59"));
        $returnArr = [];
        for ($time = $start; $time <= $end; $time = $time + $minute * 60) {
            array_push($returnArr, date("H:i", $time));
        }
        $newList = [];
//        for($i=0;$i<count($returnArr)-1;$i++){
//            $newList[$i]['start']=$returnArr[$i];
//            $newList[$i]['end']=$returnArr[$i+1];
//        }
        $k = 0;
        for ($i = 0; $i < (count($returnArr) * 2) - 1; $i++) {
            if ($i % 2 != 0) {
                if ($i != 0) {
                    $k++;
                    $newList[$k][0] = $returnArr[$k];
                }
            } else {
                if ($i != 0) {
                    $newList[$k - 1][1] = $returnArr[$k];
                } else {
                    $newList[$k][0] = $returnArr[$k];
                }
            }
        }
        $newList[count($newList) - 1][1] = $returnArr[0];
        return $newList;
    }


    /**
     * 提交认证
     * Auth:Yuanhang-Liu
     * Date:2020/10/14 15:08 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function addthen()
    {
        $req = request()->post();

        $this->validate(request(), [
            'name|医生姓名' => 'required|max:50',
            'sex|性别' => 'required|in:男,女',
            'ID|身份证号' => 'required|min:16|max:18',
            'works|医院信息' => 'required',
            'certificate|医生照片和执业证书' => 'required|string',
            'idPhoto|身份证正反面' => 'required|string',
            'doctorQualification|照片和资格证书' => 'required|string',
        ]);
        if ($req['sex'] == '男') {
            $req['sex'] = 1;
        } else {
            $req['sex'] = 2;
        }
        // 首先获取医生姓名，性别，身份证号，照片，身份证，资格证去补全医生表
        // 入库organization_ids这个数据是一条字符串，先分割成数组，如果只有一条则医生只选择了一个医院，机构id和医生id入库docter_organization(医生机构关联表)
        $user = $this->user;
        $doctor_id = $user['id'];
        if (!$doctor_id) {
            return out(null, 500, '医生信息错误！');
        }
        $data = [];
        $data['name'] = $req['name'];
        $data['sex'] = $req['sex'];
        $data['card_id'] = $req['ID'];
        $data['practice'] = $req['certificate'];
        $data['card_photo'] = $req['idPhoto'];
        $data['is_quail'] = $req['doctorQualification'];
        //处理医院机构id
        $work = json_decode($req['works'], true);
        if (!$work) {
            return out('', '', '缺少医院');
        }
        $off_then = DocterOrganization::where('docter_id', '=', $doctor_id)->get('id')->toArray();
        $is_del = false;
        if ($off_then) {
            $newids = [];
            foreach ($off_then as $k => $v) {
                $newids[$k] = $v['id'];
            }
            $is_del = true;
        }
        $org_list = [];
        foreach ($work as $k => $v) {
            if ($v['hospital']) {
                $org_list[$k]['docter_id'] = $doctor_id;
                $org_list[$k]['organization_id'] = $v['hospital'];
                $org_list[$k]['offices_id'] = $v['department'];
                $org_list[$k]['qualifications_id'] = $v['qualifications'];
                $org_list[$k]['state'] = $v['state'];
            }
        }

        DB::beginTransaction();//开启事务
        try {
            //补全医生表
            Docter::where('id', $doctor_id)->update($data);
            if ($is_del) {
                foreach ($newids as $k => $v) {
                    DocterOrganization::where('id', $v)->delete();
                }
            }
            // 提交消息；
            DocterMessage::create([
                'docter_id' => $doctor_id,
                'status' => 1,
                'type' => 8,
                'content' => '您已提交医生资质认证审核材料 '
            ]);
            DocterOrganization::insertOrIgnore($org_list);
            DB::commit();//提交至数据库
            return out();
        } catch (\Exception $e) {
            DB::rollback();
            return out(null, 500, $e->getMessage());
        }
    }


    /**
     * Auth:Yuanhang-Liu
     * Date:2020/10/14 17:17 *
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_city_id()
    {
        // 查询机构！
        $req = request()->post();

        $this->validate(request(), [
            'level_type' => 'required|in:4',
            'province|省或直辖市id' => 'required_if:level_type,==,4',
            'city|市' => 'required_if:level_type,==,4',
            'area|区' => 'required_if:level_type,==,4',
        ]);
        // 查找下医院
//            $ids_string = explode(',',$req['organizations_ids']);
        $province = trim($req['province']);
        $city = trim($req['city']);
        $area = trim($req['area']);


        $where['province_id'] = $province;
        $where['city_id'] = $city;
        $where['area_id'] = $area;
        $where['type'] = 1;
        $Organization = Organization::with('offices')->where($where)->get()->toArray();
        $qulire = Qualification::where('status', 1)->get();
        $newList = [];

        if ($Organization) {

            foreach ($Organization as $k => $v) {
                $newList[$k]['value'] = $v['id'];
                $newList[$k]['label'] = $v['name'];
                if ($v['offices']) {
                    foreach ($v['offices'] as $kk => $vv) {
                        $newList[$k]['children'][$kk]['value'] = $vv['id'];
                        $newList[$k]['children'][$kk]['label'] = $vv['name'];
                        if ($qulire) {
                            foreach ($qulire as $p => $c) {
                                $newList[$k]['children'][$kk]['children'][$p]['value'] = $c['id'];
                                $newList[$k]['children'][$kk]['children'][$p]['label'] = $c['name'];
                            }
                        } else {
                            unset($Organization[$k], $newList[$k]);
                        }
                    }
                } else {
                    unset($Organization[$k], $newList[$k]);
                }
            }
        }
        return out($newList);
    }

    /**
     * 获取城市联动
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/4 19:35
     */
    public function getCityList()
    {
        // 查询机构！
        $req = request()->post();
        $where['status'] = 1;
        $data = Areas::where($where)->get(['id', 'name', 'level', 'parent_id'])->toArray();
        $newData = [];
        foreach ($data as $k => $v) {
            $newData[$k]['value'] = $v['id'];
            $newData[$k]['label'] = $v['name'];
            $newData[$k]['pid'] = $v['parent_id'];
        }
        $list = $this->getTrees($newData);
        $list = $this->getTree($list);
        return out($list);
    }

    /**
     * 获取城市树
     * @param $data
     * @return array
     */
    protected function getTrees($arr, $pid = 0)
    {
        static $list = [];

        foreach ($arr as $key => $value) {
            if ($value["pid"] == $pid) {
                $list[] = $value;
                unset($arr[$key]); //删除已经排好的数据为了减少遍历的次数，当然递归本身就很费神就是了
                $this->getTrees($arr, $value["value"]);
            }
        }
        return $list;
    }

    /**
     * 整合树🌲
     * @param $data
     * @param $pId
     * @return string
     */
    protected function getTree($data, $pId = 0)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pId) {         //父亲找到儿子
                $chid = $this->getTree($data, $v['value']);
                if ($chid) {
                    $v['children'] = $chid;
                }
                $tree[] = $v;
                unset($data[$k]);
            } else {
                unset($data[$k]);

            }
        }
        return $tree;
    }

    /**
     * 获取科室和资质
     * @return mixed
     */
    public function getOfferList()
    {
        // 查询机构！
        $req = request()->post();
        $this->validate(request(), [
            'type' => 'required|in:1,2',
        ]);//1=科室，2=资质
        $type = $req['type'];
        if ($type == 1) {
            $List = Office::get(['id', 'name'])->toArray();
        } else if ($type == 2) {
            $List = Qualification::get(['id', 'name'])->toArray();
        } else {
            return out('', '', '错误请求');
        }
        return out($List);
    }


    /**
     * 获取我的患者列表
     * Auth:Yuanhang-Liu
     * Date:2020/10/17 13:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'userId' => 'integer',
            'userType|用户类型' => 'integer|in:1,2,3,4,5,6,7',
        ]);
        $user = $this->user;
        $doctor_id = $user['id'];
        if (!$doctor_id) {
            return out(null, 500, '医生信息错误！');
        }

        $returnList = [];
        $orderList = Order::with(['user'])->where('docter_id', '=', $doctor_id)->groupBy('id', 'product_type', 'user_id')->get()->toArray();
        $collections = DocterUser::with('user')->where('docter_id', '=', $doctor_id)->groupBy('user_id')->get()->toArray();
        $newList = [];
        foreach ($orderList as $k => $v) {
            $newList[$k]['order_id'] = $v['id'];
            $newList[$k]['user_id'] = $v['user_id'];
            $newList[$k]['order_sn'] = $v['order_sn'];
            $newList[$k]['nickname'] = $v['user']['nickname'];
            $save = UserDocter::where('user_id', '=', $v['user']['id'])->first();
            if ($save) {
                $newList[$k]['remark'] = $save['remark'];
            } else {
                $newList[$k]['remark'] = '';
            }
            $newList[$k]['avatar'] = $v['user']['avatar'];
            $newList[$k]['product_type'] = $v['product_type'];
        }
        $newcoll = [];
        foreach ($collections as $k => $v) {
            $newcoll[$k]['id'] = $v['id'];
            $newcoll[$k]['user_id'] = $v['user_id'];
            $newcoll[$k]['nickname'] = $v['user']['nickname'];
            $save = UserDocter::where('user_id', '=', $v['user_id'])->first();
            if ($save) {
                $newList[$k]['remark'] = $save['remark'];
            } else {
                $newList[$k]['remark'] = '';
            }
            $newcoll[$k]['avatar'] = $v['user']['avatar'];
        }
        $user_pic = [];
        $user_relation = [];
        $user_vaccines = [];
        $user_guar = [];
        $user_pack = [];


        foreach ($newList as $k => $v) {
            if ($v['product_type'] == 1 || $v['product_type'] == 2) {
                // 咨询患者
                if (!$this->putusers($user_pic, $v['user_id'])) {
                    array_push($user_pic, $v);
                }
            }
            if ($v['product_type'] == 3) {
                // 门诊患者
                if (!$this->putusers($user_relation, $v['user_id'])) {
                    array_push($user_relation, $v);
                }

            }
            if ($v['product_type'] == 4) {
                // 疫苗患者
                if (!$this->putusers($user_vaccines, $v['user_id'])) {
                    array_push($user_vaccines, $v);
                }


            }
            if ($v['product_type'] == 5) {
                // 儿保预约
                if (!$this->putusers($user_guar, $v['user_id'])) {
                    array_push($user_guar, $v);
                }
            }
            if ($v['product_type'] == 6) {
                // 服务包
                $OrderPacks = OrderPack::where('order_id', '=', $v['order_id'])->first();
                if ($OrderPacks) {
                    $teams = Team::with('docter')->where('id', '=', $OrderPacks['team_id'])->first();
                    if ($teams) {
                        $teams = $teams->toArray();
                        if ($teams['docter']) {
                            foreach ($teams['docter'] as $kk => $vv) {
                                if ($vv['id'] == $doctor_id) {
                                    array_push($user_pack, $v);
                                }
                            }
                        }
                    }
                }
            }
        }
        $returnList['user_pic']['data'] = $user_pic;
        $returnList['user_relation']['data'] = $user_relation;
        $returnList['user_vaccines']['data'] = $user_vaccines;
        $returnList['user_guar']['data'] = $user_guar;
        $returnList['user_pack']['data'] = $user_pack;
        if (empty($newcoll)) {
            // 关注患者
            $returnList['user_collection']['data'] = [];
        } else {
            $returnList['user_collection']['data'] = $newcoll;
        }


        $returnList['user_pic']['count'] = count($user_pic);
        $returnList['user_relation']['count'] = count($user_relation);
        $returnList['user_vaccines']['count'] = count($user_vaccines);
        $returnList['user_guar']['count'] = count($user_guar);
        $returnList['user_pack']['count'] = count($user_pack);
        $returnList['user_collection']['count'] = count($returnList['user_collection']['data']);
        return out($returnList);
    }


    /**
     * 升级版 in_array
     * @param $data1
     * @param $data2
     * @return bool
     * @author Liu-Yh
     * Create By 2020/11/27 16:18
     */
    protected function putusers($data1, $data2)
    {
        if (empty($data1)) {
            return false;
        }

        $list = [];
        foreach ($data1 as $k => $v) {
            array_push($list, $v['user_id']);
        }
        if (in_array($data2, $list)) {
            return true;
        } else {
            return false;
        }

    }


    /**
     * 上备注
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/27 16:16
     */
    public function remacks()
    {
        $req = request()->post();
        $this->validate(request(), [
            'remak|备注' => 'required',
            'id|id' => 'required',
        ]);
        $user = $this->user;
        $user_id = $user['id'];
        $wheres['docter_id'] = $user_id;
        $wheres['user_id'] = $req['id'];
        $save = UserDocter::where($wheres)->first();

        if ($save) {
            UserDocter::where('id', '=', $save['id'])->update([
                'remark' => $req['remak']
            ]);
        } else {
            UserDocter::create([
                'docter_id' => $user_id,
                'user_id' => $req['id'],
                'remark' => $req['remak']
            ]);
        }
        return out([]);


    }

    /**
     * 评价列表
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/17 17:41
     */
    public function evaluate()
    {
        $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'];
        $wheres['docter_id'] = $doctor_id;
        $wheres['status'] = 2;
        $data = Evaluate::with(['order', 'user'])->where($wheres)->skip($pageSize)->take($req['pageSize'])->groupBy('id')->get()->toArray();;
        if ($data) {
            $newList = [];
            foreach ($data as $k => $v) {
                $newList[$k]['order_id'] = $v['order']['order_sn'];
                $newList[$k]['user'] = $v['user']['nickname'];
                $newList[$k]['lv'] = $v['score'];
                $newList[$k]['time'] = $v['created_at'];
                $newList[$k]['evaluate'] = $v['content'];
            }
            return out($newList);
        } else {
            return out([]);
        }
    }


    /**
     * 我的列表进入详情
     * Auth:Yuanhang-Liu
     * Date:2020/10/18 15:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function userListDetile()
    {
        $req = request()->post();
        $this->validate(request(), [
            'user_id|用户ID' => 'required|integer',
            'userType|用户类型' => 'integer|in:1,2,3,4,5,6,7',
        ]);
        $user = $this->user;
        // 查询详情;
        $finds_patient = User::with('patients')->where('id', '=', $req['user_id'])->first();
        $remarks = UserDocter::where('user_id', '=', $req['user_id'])->first();


        $finds_order = Order::with('orderPatient')->where('user_id', '=', $req['user_id'])->orderBy('created_at', 'desc')->limit(3)->get();
        if ($finds_order) {
            $finds_order = $finds_order->toArray();
        }
        $userArr = $patientsArr = $orderArr = $fuwArr = [];
        $patientsArr = [];
        $ws['user_id'] = $req['user_id'];
        $ws['product_type'] = 6;
        $fuw_order = Order::with('orderPack')->where($ws)->orderBy('created_at', 'desc')->get();
        if ($fuw_order) {
            $fuw_order = $fuw_order->toArray();

            foreach ($fuw_order as $kk => $vv) {
                $fuwArr[$kk]['order_id'] = $vv['id'];
                if ($vv['order_pack']) {
                    foreach ($vv['order_pack'] as $k => $v) {
                        $fuwArr[$kk]['id'] = $v['id'];
                        $fuwArr[$kk]['pack_name'] = $v['pack_name'];
                        $fuwArr[$kk]['pack_intro'] = $v['pack_intro'];
                        $fuwArr[$kk]['pack_price'] = $v['pack_price'];
                        $fuwArr[$kk]['effective_days'] = $v['effective_days'];
                        $fuwArr[$kk]['start_time'] = date('Y-m-d,H:i', $v['start_time']);
                        $fuwArr[$kk]['end_time'] = date('Y-m-d,H:i', $v['end_time']);
                    }
                }

            }
        }


        if ($finds_patient) {
            $finds_patient = $finds_patient->toArray();
            $userArr['id'] = $finds_patient['id'];
            if ($remarks) {
                $userArr['remark'] = $remarks['remark']; //用户备注
            } else {
                $userArr['remark'] = ''; //用户备注
            }
            $userArr['nickname'] = $finds_patient['nickname'];
            $userArr['avatar'] = $finds_patient['avatar'];
            if ($finds_patient['patients']) {
                foreach ($finds_patient['patients'] as $kk => $vv) {
                    $patientsArr[$kk]['id'] = $vv['id'];
                    $patientsArr[$kk]['avatar'] = $vv['avatar'];
                    $patientsArr[$kk]['name'] = $vv['name'];
                    if ($vv['sex'] == 0) {
                        $patientsArr[$kk]['sex'] = '未知';
                    } elseif ($vv['sex'] == 1) {
                        $patientsArr[$kk]['sex'] = '男';
                    } else {
                        $patientsArr[$kk]['sex'] = '女';
                    }
                    $patientsArr[$kk]['age'] = numBirthday($vv['birthday']);
                }
            }
        }


        if ($finds_order) {
            foreach ($finds_order as $k => $v) {
                $orderArr[$k]['id'] = $v['id'];
                $orderArr[$k]['order_sn'] = $v['order_sn'];
                if ($v['order_status'] >= 4) {
                    $orderArr[$k]['receiving_time'] = date('Y-m-d H:i', $v['receiving_time']);
                    $orderArr[$k]['outtime'] = date('Y-m-d H:i', $v['end_time']);
                } else {
                    $orderArr[$k]['receiving_time'] = '';
                    $orderArr[$k]['outtime'] = '';
                }
                $orderArr[$k]['order_status'] = $v['order_status'];
                $orderArr[$k]['product_type'] = $v['product_type'];
                $orderArr[$k]['created_at'] = $v['created_at'];
                $orderArr[$k]['name'] = $v['order_patient']['name'];
                $orderArr[$k]['birthday'] = numBirthday($v['order_patient']['birthday']);
            }
        }


        // 拼接服务消息
        $wh['user_id'] = $req['user_id'];
        $wh['order_status'] = ['>', 3];
        $wh['product_type'] = 6;
        $fuwuList = [];
        $fuwuInfo = Order::where($wh)->get();
        $fuwuList['fuwu_num'] = count($fuwuInfo);
        $whs['user_id'] = $req['user_id'];
        $whs['order_status'] = ['>', 3];
        $order_nums = Order::where($whs)->get();

        $fuwuList['order_num'] = count($order_nums);
        $pati_nums = Patient::where('user_id', '=', $req['user_id'])->get();
        $fuwuList['pati_num'] = count($pati_nums);


        $returnArr = [
            'user_arr' => $userArr,
            'patients_arr' => $patientsArr,//患者档案
            'order_arr' => $orderArr, //历史问诊
            'fuwu_arr' => $fuwArr, //已购服务
            'nums' => $fuwuList,
        ];
        return out($returnArr);
    }


    /**
     * 我的列表进入详情
     * Auth:Yuanhang-Liu
     * Date:2020/10/20 23:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function patientsDetile()
    {
        $req = request()->post();
        $this->validate(request(), [
            'patient_id|患者ID' => 'required|integer',
        ]);
        $user = $this->user;
        $finds = Patient::where('id', '=', $req['patient_id'])->first();
        if ($finds) {
            $finds = $finds->toArray();
        }
        if ($finds['sex'] == 0) {
            $finds['sex'] = '中性';
        } elseif ($finds['sex'] == 1) {
            $finds['sex'] = '男';
        } else {
            $finds['sex'] = '女';
        }

        switch ($finds['relationship_type']) {
            case 1:
                $finds['relationship_type'] = '父亲';
                break;
            case 2:
                $finds['relationship_type'] = '母亲';
                break;
            case 3:
                $finds['relationship_type'] = '祖父';
                break;
            case 4:
                $finds['relationship_type'] = '祖母';
                break;
            case 5:
                $finds['relationship_type'] = '外祖父';
                break;
            case 6:
                $finds['relationship_type'] = '外祖母';
                break;
            case 7:
                $finds['relationship_type'] = '叔侄';
                break;
            default:
                $finds['relationship_type'] = '其他';
        }
        $finds['age'] = numBirthday($finds['birthday']);
        // 患者单子
        $patient_list = OrderPatient::with('order')->where('patient_id', '=', $req['patient_id'])->groupBy('id', 'order_id')->get();
        $patient_arr = [];
        if ($patient_list) {
            $patient_list = $patient_list->toArray();
            foreach ($patient_list as $k => $v) {
                switch ($v['order']['product_type']) {
                    case 1:
                        $patient_arr[$k]['product_type'] = '电话咨询';
                        break;
                    case 2:
                        $patient_arr[$k]['product_type'] = '图文咨询';
                        break;
                    case 3:
                        $patient_arr[$k]['product_type'] = '门诊';
                        break;
                    case 4:
                        $patient_arr[$k]['product_type'] = '疫苗接种预约';
                        break;
                    case 5:
                        $patient_arr[$k]['product_type'] = '儿保预约';
                        break;
                    case 6:
                        $patient_arr[$k]['product_type'] = '服务包';
                        break;
                    case 7:
                        $patient_arr[$k]['product_type'] = '充值';
                        break;
                    default:
                        $patient_arr[$k]['product_type'] = '错误';
                }
                switch ($v['order']['order_status']) {
                    case 1:
                        $patient_arr[$k]['order_status'] = '未支付';
                        break;
                    case 2:
                        $patient_arr[$k]['order_status'] = '待接单';
                        break;
                    case 3:
                        $patient_arr[$k]['order_status'] = '进行中';
                        break;
                    case 4:
                        $patient_arr[$k]['order_status'] = '已完成';
                        break;
                    case 5:
                        $patient_arr[$k]['order_status'] = '已取消';
                        break;
                    default:
                        $patient_arr[$k]['order_status'] = '未知';
                }
                $patient_arr[$k]['created_at'] = $v['created_at'];
            }
        }

        $returnArr = [
            'patient' => $finds,
            'patientOrder' => $patient_arr,
        ];
        return out($returnArr);
    }

    /**
     * 关注用户
     * Auth:Yuanhang-Liu
     * Date:2020/10/21 00:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function userFollow()
    {
        $req = request()->post();
        $this->validate(request(), [
            'user_id|用户ID' => 'required|integer',
            'is_ley' => 'required',
        ]);
        // 如果ley==false说明要取消关注，反之添加关注
        $user = $this->user;
        $docter_id = $user['id'];

        if ($req['is_ley'] == 1) {
            DocterUser::where('user_id', '=', $req['user_id'])->delete();
        } else {
            DocterUser::create([
                'user_id' => $req['user_id'],
                'docter_id' => $user['id'],
            ]);
        }
        return out();
    }

    /**
     * 是否关注用户
     * Auth:Yuanhang-Liu
     * Date:2020/10/21 00:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function getFollows()
    {
        $req = request()->post();
        $this->validate(request(), [
            'user_id|用户ID' => 'required|integer',
        ]);
        $user = $this->user;
        $docter_id = $user['id'];
        $where['docter_id'] = $docter_id;
        $where['user_id'] = $req['user_id'];
        $find = DocterUser::where($where)->first();

        if ($find) {
            $find = $find->toArray();
            return out(true);
        } else {
            return out(false);
        }
    }

    /**
     * 获取医生所在机构列表
     * Auth:Yuanhang-Liu
     * Date:2020/10/21 00:21
     * @return \Illuminate\Http\JsonResponse
     */
    public function organizationList()
    {

        $user = $this->user;
        $doctor_id = $user['id'];
        $where['docter_id'] = $doctor_id;
        $where['state'] = 1;
        $orgList = DocterOrganization::with('organization')->where($where)->get()->toArray();
        $newList = [];
        foreach ($orgList as $k => $v) {
            $newList[$k]['value'] = $v['organization']['id'];
            $newList[$k]['label'] = $v['organization']['name'];
        }
        return out($newList);
    }


    /**
     * 获取医院的服务时间
     * @return mixed
     */
    public function getOrgTimes()
    {
        $req = request()->post();
        $this->validate(request(), [
            'org_id|医院id' => 'required',
        ]);
        $user = $this->user;
        $doctor_id = $user['id'];
        $where['docter_id'] = $doctor_id;
        $orgList = DocterSetting::where(['docter_id'=>$doctor_id,'type'=>1,'org_id'=>$req['org_id']])->first();
        $newList = [];

        if($orgList){
            $time = json_decode($orgList['service_time'],true);
            $newList['zao']['amStartTime'] = isset($time[1])?$time[1]['amStartTime']:'';
            $newList['zao']['amEndTime'] = isset($time[1])?$time[1]['amEndTime']:'';
            $newList['zao']['amPerson'] = isset($time[1])?$time[1]['amPerson']:'';

            $newList['zhong']['pmStartTime'] = isset($time[2])?$time[2]['pmStartTime']:'';
            $newList['zhong']['pmEndTime'] = isset($time[2])?$time[2]['pmEndTime']:'';
            $newList['zhong']['pmPerson'] = isset($time[2])?$time[2]['pmPerson']:'';

            $newList['wan']['nightStartTime'] = isset($time[3])?$time[3]['nightStartTime']:'';
            $newList['wan']['nightEndTime'] = isset($time[3])?$time[3]['nightEndTime']:'';
            $newList['wan']['nightPerson'] = isset($time[3])?$time[3]['nightPerson']:'';
        }

        return out($newList);
    }

    /**
     * 获取历史排班时间列表
     */
    public function getLinsList()
    {
        $user = $this->user;
        $doctor_id = $user['id'];
        $newData = [];
        $strim = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
        $wheres['docter_id'] = $doctor_id;
        $data = Schedule::select(['id', 'schedule_date'])->where($wheres)->whereDate('schedule_date', '>', $strim)->orderBy('schedule_date', 'desc')->get();
        if ($data) {
            $data = $data->toArray();
        } else {
            return out($newData);
        }

        $newData = array_values($data);
        $lab = [];
        $p = 0;
        for ($i = count($newData); $i > 0; $i--) {
//            if ($i%7==0||$i==1){
//
//                if ($p>=1){
//                    $lab[$p-1]['end_time'] = $arr[$i-1];
//                    $lab[$p]['start_time'] = $arr[$i-1];
//                    if(isset($arr[$i-7])){
//                        $lab[$p]['end_time'] = isset($arr[$i-7])?$arr[$i-7]:'error';
//
//                    }else{
//                        unset($lab[$p]);
//                    }
////                    $lab[$p]['end_time'] = isset($arr[$i-7])?$arr[$i-7]:'error';
//                }else{
//                    $lab[$p]['start_time'] = $arr[$i-1];
//                }
//                ++$p;
//            }else{
//                continue;
//            }
            if ($i % 7 == 0 || $i == 1) {
                if ($p >= 1) {
                    $lab[$p - 1]['end_time'] = $newData[$i - 1];
                    if (isset($newData[$i - 7])) {
                        $lab[$p]['start_time'] = $newData[$i - 1];
                        $lab[$p]['end_time'] = $newData[$i - 7];
                    } else {
                        unset($lab[$p]);
                    }
                } else {
                    $lab[$p]['start_time'] = $newData[$i - 1];
                }
                ++$p;
            } else {
                continue;
            }
        }
        // 审核通过时间拿出来
        $wh['docter_id'] = $doctor_id;
        $wh['service_type'] = 3;
        $wh['status'] = 2;
        $service = ServiceApply::where($wh)->first();
        if ($service) {
            $service = $service;
        } else {
            $service = 0;
        }
        $rtuenList = [
            'list' => $lab,
            'service' => $service,
        ];
        return out($rtuenList);
    }

    /**
     * 获取周模板详情
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/12/16 12:09
     */
    public function getLinsDetailnew($flag = false)
    {
        $user = $this->user;
        $doctor_id = $user['id'];
        $newData = [];
        $data = WeekSchedule::with('organization')->where('docter_id', '=', $doctor_id)->groupBy('type', 'week')->orderBy('week', 'asc')->get();
        if ($data) {
            $data = $data->toArray();
        } else {
            return out($newData);
        }
        $lab = [];
        foreach ($data as $k => $v) {
            $lab[$k]['id'] = $v['id'];
            $lab[$k]['type'] = $v['type']; // 1=早上，2=下午，3=晚上
            $lab[$k]['organization_id'] = $v['organization_id']; // 1=早上，2=下午，3=晚上
            $lab[$k]['flag'] = $v['week'];

            switch ($v['week']) {
                case "7":
                    $lab[$k]['week'] = '周日';
                    break;
                case "1":
                    $lab[$k]['week'] = '周一';
                    break;
                case "2":
                    $lab[$k]['week'] = '周二';
                    break;
                case "3":
                    $lab[$k]['week'] = '周三';
                    break;
                case "4":
                    $lab[$k]['week'] = '周四';
                    break;
                case "5":
                    $lab[$k]['week'] = '周五';
                    break;
                default:
                    $lab[$k]['week'] = '周六';
            }
            $lab[$k]['name'] = $v['organization']; // 所在医院
        }
        $weekList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

        try {
            $newReturn = [];

            foreach ($lab as $k => $v) {
                if (!isset($newReturn[$v['flag']])) {
                    $newReturn[$v['flag']] = $v;
                    if ($v['type'] == 1) {
                        $newReturn[$v['flag']]['ident']['zao_id'] = $v['name']['id'];
                        $newReturn[$v['flag']]['ident']['xia_id'] = 0;
                        $newReturn[$v['flag']]['ident']['wan_id'] = 0;
                    } else if ($v['type'] == 2) {
                        $newReturn[$v['flag']]['ident']['zao_id'] = 0;
                        $newReturn[$v['flag']]['ident']['xia_id'] = $v['name']['id'];
                        $newReturn[$v['flag']]['ident']['wan_id'] = 0;
                    } else {
                        $newReturn[$v['flag']]['ident']['zao_id'] = 0;
                        $newReturn[$v['flag']]['ident']['xia_id'] = 0;
                        $newReturn[$v['flag']]['ident']['wan_id'] = $v['name']['id'];
                    }
                    $newReturn[$v['flag']]['week'] = $v['week'];
                    $newReturn[$v['flag']]['name'] = $v['name'];
                } else {
                    if ($v['type'] == 1) {

                        $newReturn[$v['flag']]['ident']['zao_id'] = $v['name']['id'];
                    } else if ($v['type'] == 2) {

                        $newReturn[$v['flag']]['ident']['xia_id'] = $v['name']['id'];

                    } else {

                        $newReturn[$v['flag']]['ident']['wan_id'] = $v['name']['id'];
                    }
                }
                unset($newReturn[$v['flag']]['name']);

            }
        } catch (\Exception $e) {
            var_dump($e->getMessage() . $e->getFile() . $e->getLine());
        }


        $returnLists['list'] = array_values($newReturn);

        return out($returnLists);
    }

    /**
     * 生成时间段
     * @param int $org_id 机构id
     * @param int $type 时间段，1=早上，2=下午，3=晚上
     * @return array|bool
     * @author Liu-Yh
     * Create By 2020/12/15 18:47
     */
    protected function num_time($org_id = 0, $type = 1)
    {


        $user = $this->user;
        $doctor_id = $user['id'];
        $zaoTimes = [];
        $zhongTimes = [];
        $wanTimes = [];
        $where['docter_id'] = $doctor_id;
        $where['type'] = 1;
        $where['org_id'] = $org_id;
        $configs = DocterSetting::where($where)->first();



        if ($configs) {
            $list = json_decode($configs['service_time'], true);


            if (isset($list[1]['amStartTime']) && !empty($list[1]['amStartTime'])) {
                $zaoTimes[0] = $list[1]['amStartTime'];
            } else {
                $zaoTimes[0] = "08:00";
            }
            if (isset($list[1]['amEndTime']) && !empty($list[1]['amEndTime'])) {
                $zaoTimes[1] = $list[1]['amEndTime'];
            } else {
                $zaoTimes[1] = "12:00";
            }
            if (isset($list[2]['pmStartTime']) && !empty($list[2]['pmStartTime'])) {
                $zhongTimes[0] = $list[2]['pmStartTime'];
            } else {
                $zhongTimes[0] = "13:00";
            }
            if (isset($list[2]['pmEndTime']) && !empty($list[2]['pmEndTime'])) {
                $zhongTimes[1] = $list[2]['pmEndTime'];
            } else {
                $zhongTimes[1] = "18:00";
            }
            if (isset($list[3]['nightStartTime']) && !empty($list[3]['nightStartTime'])) {
                $wanTimes[0] = $list[3]['nightStartTime'];
            } else {
                $wanTimes[0] = "19:00";
            }
            if (isset($list[3]['nightEndTime']) && !empty($list[3]['nightEndTime'])) {
                $wanTimes[1] = $list[3]['nightEndTime'];
            } else {
                $wanTimes[1] = "21:00";
            }
        } else {
            return false;
        }
        if ($type == 1) {
            $morningWhere[] = ['start_time_period', '>=', $zaoTimes[0]];
            $morningWhere[] = ['end_time_period', '<=', $zaoTimes[1]];
            $morningWhere['docter_id'] = $doctor_id;
            $morningWhere['org_id'] = $org_id;
            $morningd = TimePeriod::where($morningWhere)->get()->toArray();
            if (count($morningd)>1){
                array_pop($morningd);
            }
            $morning = array_column($morningd, 'id');

            return $morning;
        } elseif ($type == 2) {
            $afternoondWhere[] = ['start_time_period', '>=', $zhongTimes[0]];
            $afternoondWhere[] = ['end_time_period', '<=', $zhongTimes[1]];
            $afternoondWhere['docter_id'] = $doctor_id;
            $afternoondWhere['org_id'] = $org_id;
            $afternoond = TimePeriod::where($afternoondWhere)->get()->toArray();
            if (count($afternoond)>1){
                array_pop($afternoond);
            }
            $afternoon = array_column($afternoond, 'id');
            return $afternoon;

        } elseif ($type == 3) {
            $nightWhere[] = ['start_time_period', '>=', $wanTimes[0]];
            $nightWhere[] = ['end_time_period', '<=', $wanTimes[1]];
            $nightWhere['docter_id'] = $doctor_id;
            $nightWhere['org_id'] = $org_id;
            $nightd = TimePeriod::where($nightWhere)->get()->toArray();
            if (count($nightd)>1){
                array_pop($nightd);
            }

            $night = array_column($nightd, 'id');
            return $night;

        } else {
            $morningWhere[] = ['start_time_period', '>=', $zaoTimes[0]];
            $morningWhere[] = ['end_time_period', '<=', $zaoTimes[1]];
            $morningWhere['docter_id'] = $doctor_id;
            $morningWhere['org_id'] = $org_id;
            $morningd = TimePeriod::where($morningWhere)->get()->toArray();
            if (count($morningd)>1){
                array_pop($morningd);
            }
            $morning = array_column($morningd, 'id');

            $afternoondWhere[] = ['start_time_period', '>=', $zhongTimes[0]];
            $afternoondWhere[] = ['end_time_period', '<=', $zhongTimes[1]];
            $afternoondWhere['docter_id'] = $doctor_id;
            $afternoondWhere['org_id'] = $org_id;
            $afternoond = TimePeriod::where($afternoondWhere)->get()->toArray();
            if (count($afternoond)>1){
                array_pop($afternoond);
            }
            $afternoon = array_column($afternoond, 'id');

            $nightWhere[] = ['start_time_period', '>=', $wanTimes[0]];
            $nightWhere[] = ['end_time_period', '<=', $wanTimes[1]];
            $nightWhere['docter_id'] = $doctor_id;
            $nightWhere['org_id'] = $org_id;
            $nightd = TimePeriod::where($nightWhere)->get()->toArray();
            if (count($nightd)>1){
                array_pop($nightd);
            }
            $night = array_column($nightd, 'id');
            return [$morning, $afternoon, $night];
        }
    }


    /**
     * 获取俩月日期
     * @return array
     */
    protected function date_bool($start_time = false, $end_time = false)
    {
        $weekarray = array(7, 1, 2, 3, 4, 5, 6);
        $monthDays = [];

        if ($start_time && $end_time) {
            $firstDay = $start_time;
            $lastDay = $end_time;
        } else {
            $firstDay = date('Y-m-01', time());
            $lastDay = date('Y-m-d', strtotime("$firstDay +2 month -1 day"));
        }

        $i = 0;
        while (date('Y-m-d', strtotime("$firstDay +$i days")) <= $lastDay) {
            $monthDays[$i]['date'] = date('Y-m-d', strtotime("$firstDay +$i days"));
            $monthDays[$i]['week'] = $weekarray[date("w", strtotime("$firstDay +$i days"))];
            $i++;
        }
        return $monthDays;
    }


    /**
     * 新版门诊排班(排班周模板)
     * @return mixed
     * @throws \Exception
     */
    public function week_scheduling()
    {
        $req = request()->post();
        $this->validate(request(), [
            'data|数据' => 'required',
        ]);
        $user = $this->user;
        $doctor_id = $user['id'];
        $data = json_decode($req['data'], true);
        // 查询自定义排班
        $Wheres['docter_id'] = $doctor_id;
        $Wheres['me_sure'] = 1;
        $Wheres['schedule_type'] = 1;
        $Wheres[] = ['schedule_date','>=',date('Y-m-d',time())];
        $meSureList = SchedulePeriod::where($Wheres)->get();
        $moth_date = $this->date_bool();
        $delDate = [];
        $delDate2 = [];
        $schedule_ids = [];
        $schedule = [];
        foreach ($data as $k=>$v){
            if ($v['identifi']['zao']==0&&$v['identifi']['zhong']==0&&$v['identifi']['wan']==0){
                $delDate[] = $v['week'];
            }
        }
        if ($meSureList){
            foreach ($meSureList as $k=>$v){
                $delDate2[] = $v['schedule_date'];
            }
        }
        foreach ($moth_date as $k=>$v){
            if (in_array($v['week'],$delDate)){
                unset($moth_date[$k]);
            }
            if (in_array($v['date'],$delDate2)){
                unset($moth_date[$k]);
            }
        }

        DB::beginTransaction();
        try {
            WeekSchedule::where('docter_id', '=', $doctor_id)->where('schedule_type', '=', 1)->delete();
            $delWhere['docter_id'] = $doctor_id;
            $delWhere['me_sure'] = 0;
            $delWhere['schedule_type'] = 1;
            $delWhere[] = ['schedule_date','>=',date('Y-m-d',time())];
            SchedulePeriod::where($delWhere)->delete();
            Schedule::where('docter_id', '=', $doctor_id)->whereNotIn('schedule_date',$delDate2)->delete();
            foreach ($moth_date as $kk => $vv) {
                $schedule[$kk]['schedule_type'] = 1;
                $schedule[$kk]['schedule_date'] = $vv['date'];
                $schedule[$kk]['schedule_day'] = str_replace('-', '', $vv['date']);
                $schedule[$kk]['docter_id'] = $doctor_id;
                $schedule[$kk]['organization_id'] = 0;
                $schedule[$kk]['week'] = $vv['week'];
                $schedule[$kk]['per_time_num'] = 0;
                $schedule_ids[$kk] = Schedule::insertGetId($schedule[$kk]);
            }

            foreach ($data as $k => $v) {
                // 插入详情
                if ($v['identifi']['zao']!=0) {
                    $maf[$k]['schedule_type'] = 1;
                    $maf[$k]['docter_id'] = $doctor_id;
                    $maf[$k]['week'] = $v['week'];
                    $maf[$k]['type'] = 1;
                    $maf[$k]['organization_id'] = $v['identifi']['zao'];
                    $weekList[] = $maf[$k];
                }
                if ($v['identifi']['zhong']!=0) {
                    $maf[$k]['schedule_type'] = 1;
                    $maf[$k]['docter_id'] = $doctor_id;
                    $maf[$k]['week'] = $v['week'];
                    $maf[$k]['type'] = 2;
                    $maf[$k]['organization_id'] = $v['identifi']['zhong'];
                    $weekList[] = $maf[$k];
                }
                if ($v['identifi']['wan']!=0) {
                    $maf[$k]['schedule_type'] = 1;
                    $maf[$k]['docter_id'] = $doctor_id;
                    $maf[$k]['week'] = $v['week'];
                    $maf[$k]['type'] = 3;
                    $maf[$k]['organization_id'] = $v['identifi']['wan'];
                    $weekList[] = $maf[$k];
                }
            }

            $scheduleLists = [];
            foreach ($schedule_ids as $kk => $vv) {
                foreach ($data as $k => $v) {
                    if ($schedule[$kk]['week'] == $v['week']) {
                        //检查有没有设置时间
                        if ($v['identifi']['zao']) {
                            $times = $this->num_time($v['identifi']['zao'], 1);
                            if (!$times) {
                                return out('', 500, "请先在排班设置中填写本机构的早上时间段");
                            }
                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['zao'],'me_sure'=>0, 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 1], $doctor_id);
                            if ($maf) {
                                foreach ($maf as $os) {
                                    $scheduleLists[] = $os;
                                }
                            }
                        }
                        if ($v['identifi']['zhong']) {
                            $times = $this->num_time($v['identifi']['zhong'], 2);
                            if (!$times) {
                                return out('', 500, "请先在排班设置中填写本机构的下午时间段");
                            }
                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['zhong'],'me_sure'=>0, 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 2], $doctor_id);
                            if ($maf) {
                                foreach ($maf as $os) {
                                    $scheduleLists[] = $os;
                                }
                            }
                        }
                        if ($v['identifi']['wan']) {
                            $times = $this->num_time($v['identifi']['wan'], 3);
                            if (!$times) {
                                return out('', 500, "请先在排班设置中填写本机构的晚上时间段");
                            }
                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['wan'],'me_sure'=>0, 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 3], $doctor_id);
                            if ($maf) {
                                foreach ($maf as $os) {
                                    $scheduleLists[] = $os;
                                }
                            }
                        }
                    }
                }
            }
            SchedulePeriod::insert($scheduleLists);
            WeekSchedule::insert($weekList);
            DB::commit();
            return out();
        } catch (\Exception $e) {
            DB::rollBack();
            return out('', 500, $e->getFile() . '中的第：' . $e->getLine() . '行报错：' . $e->getCode(), $e->getMessage());
        } catch (\PDOException $e) {
            DB::rollBack();
            return out('', 500, $e->getFile() . '中的第：' . $e->getLine() . '行报错：' . $e->getCode(), $e->getMessage());
        }
    }





    /**
     * 修改某一天的数据
     * @author Liu-Yh
     * Create By 2020/12/16 18:46
     */
    public function saveDay($data = [])
    {
        $flag = false;
        if (empty($data)) {
            $req = request()->post();
            $this->validate(request(), [
                'schedule_date|日期' => 'required',
                'week|周' => 'required',
                'type|类型' => 'required',
                'organization_id|日期' => 'required',
            ]);
            $req['schedule_date'] = date('Y-m-d',strtotime($req['schedule_date']));
        } else {
            $flag = true;
            $req = $data;
        }
        $user = $this->user;
        $doctor_id = $user['id'];
        $save_data = [];
        DB::beginTransaction();
        try {
            $type_data = json_decode($req['type'],true);
            $where = [];
            $where['schedule_date'] = $req['schedule_date'];
            $where['docter_id'] = $doctor_id;
            $where['schedule_type'] = 1;
            $where['organization_id'] = $req['organization_id'];
            if ($type_data['mon']==0&&$type_data['aft']==0&&$type_data['nig']==0){
                // 进行删除
                unset($where['organization_id']);
                SchedulePeriod::where($where)->delete();
                Schedule::where($where)->delete();
                return out();
            }
            SchedulePeriod::where($where)->delete();
            $save_data=[];
            if($type_data['mon']!=0) {
                $mon_times = $this->num_time($type_data['mon'], 1);
                $mf1 = $this->arrangeDay($mon_times, ['organization_id' => $type_data['mon'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 1], $doctor_id);
                if($mf1){
                    foreach ($mf1 as $v){
                        $save_data[] = $v;
                    }
                }
            }
            if($type_data['aft']!=0){
                $aft_times = $this->num_time($type_data['aft'], 2);

                $mf2 = $this->arrangeDay($aft_times, ['organization_id' => $type_data['aft'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 2], $doctor_id);
                if($mf2){
                    foreach ($mf2 as $v){
                        $save_data[] = $v;
                    }
                }
            }
            if($type_data['nig']!=0) {
                $nig_times = $this->num_time($type_data['nig'], 3);
                $mf3 = $this->arrangeDay($nig_times, ['organization_id' => $type_data['nig'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 3], $doctor_id);
                if($mf3){
                    foreach ($mf3 as $v){
                        $save_data[] = $v;
                    }
                }
            }


            if (!$flag){
                $lists = Schedule::where(['docter_id'=>$doctor_id,'schedule_date'=>$req['schedule_date']])->first();
                if($lists){
                    if($save_data){
                        $chong = [];
                        foreach ($save_data as $k => $v) {
                            $chong[$k]['schedule_id'] = $lists['id'];
                            $chong[$k]['docter_id'] = $v['docter_id'];
                            $chong[$k]['order_num'] = 0;
                            $chong[$k]['organization_id'] = $v['organization_id'];
                            $chong[$k]['time_period_id'] = $v['time_period_id'];
                            $chong[$k]['type'] = $v['type'];
                            $chong[$k]['me_sure'] = 1;
                            $chong[$k]['schedule_date'] = $v['schedule_date'];
                        }
                        SchedulePeriod::insert($chong);
                    }

                }
            }

            DB::commit();
            if ($flag) {
                return true;
            } else {
                return out();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            if ($flag) {
                return false;
            } else {
                return out('', 500, $e->getFile() . '中的第：' . $e->getLine() . '行报错：' . $e->getCode(), $e->getMessage());
            }
        } catch (\PDOException $e) {
            DB::rollBack();
            if ($flag) {
                return false;
            } else {
                return out('', 500, $e->getFile() . '中的第：' . $e->getLine() . '行报错：' . $e->getCode(), $e->getMessage());
            }
        }
    }

    /**
     * 整理单个修改排班的数据
     * @param $time
     * @param $req
     * @param $doctor_id
     * @return array
     * @author Liu-Yh
     * Create By 2020/12/16 19:00
     */
    protected function arrangeDay($time, $req, $doctor_id)
    {

        $save_data = [];
        foreach ($time as $k => $v) {
            $save_data[$k]['schedule_date'] = $req['schedule_date'];
            $save_data[$k]['week'] = $req['week'];
            $save_data[$k]['schedule_type'] = 1;
            $save_data[$k]['type'] = $req['type'];
            $save_data[$k]['organization_id'] = $req['organization_id'];
            $save_data[$k]['docter_id'] = $doctor_id;
            $save_data[$k]['time_period_id'] = $v;
        }

        return $save_data;
    }


    /**
     * 查看月视图
     * @author Liu-Yh
     * Create By 2020/12/16 19:20
     */
    public function monthDetail()
    {
        $req = request()->post();
        $this->validate(request(), [
            'start_day|日期' => 'required',
            'end_day|日期' => 'required',
        ]);
        //格式化日期
        $req['start_day'] = date('Y-m-d',strtotime($req['start_day']));
        $req['end_day'] = date('Y-m-d',strtotime($req['end_day']));

        $user = $this->user;
        $doctor_id = $user['id'];
        $Wheres['docter_id'] = $doctor_id;
        $Wheres['schedule_type'] = 1;
        $list = SchedulePeriod::where($Wheres)->whereBetween('schedule_date',[$req['start_day'],$req['end_day']])->select(['schedule_date','id','organization_id','type'])->orderBy('schedule_date','asc')->get();
        // 定义数组整合数据
        if ($list){
            $list = $list->toArray();
        }else{
            return out([]);
        }
        $dateFlag = [];
        foreach ($list as $k=>$v){
            if (!isset($dateFlag[$v['schedule_date']])) {
                $dateFlag[$v['schedule_date']] = $v;
                if ($v['type'] == 1) {
                    $dateFlag[$v['schedule_date']]['ident']['zao'] = $v['organization_id'];
                    $dateFlag[$v['schedule_date']]['ident']['xia'] = 0;
                    $dateFlag[$v['schedule_date']]['ident']['wan'] = 0;
                } else if ($v['type'] == 2) {
                    $dateFlag[$v['schedule_date']]['ident']['zao'] = 0;
                    $dateFlag[$v['schedule_date']]['ident']['xia'] = $v['organization_id'];
                    $dateFlag[$v['schedule_date']]['ident']['wan'] = 0;
                } else {
                    $dateFlag[$v['schedule_date']]['ident']['zao'] = 0;
                    $dateFlag[$v['schedule_date']]['ident']['xia'] = 0;
                    $dateFlag[$v['schedule_date']]['ident']['wan'] = $v['organization_id'];
                }
                $dateFlag[$v['schedule_date']]['date'] = $v['schedule_date'];

            } else {
                if ($v['type'] == 1) {
                    $dateFlag[$v['schedule_date']]['ident']['zao'] = $v['organization_id'];
                }
                if ($v['type'] == 2) {
                    $dateFlag[$v['schedule_date']]['ident']['xia'] = $v['organization_id'];
                }
                if ($v['type'] == 3){
                    $dateFlag[$v['schedule_date']]['ident']['wan'] = $v['organization_id'];
                }
            }

        }
        return out(array_values($dateFlag));
    }


    /**
     * 获取早中下午的id
     * @param $sid
     * @param $time
     * @param $req
     * @param $doctor_id
     * @return array
     * @author Liu-Yh
     * Create By 2020/11/6 16:27
     */
    protected function getMaf($sid, $time, $req, $doctor_id)
    {
        $maf = [];
        foreach ($time as $k => $v) {
            $maf[$k]['schedule_id'] = $sid;
            $maf[$k]['organization_id'] = $req['organization_id'];
            $maf[$k]['time_period_id'] = $v;
            $maf[$k]['schedule_date'] = $req['schedule_date'];
            $maf[$k]['docter_id'] = $doctor_id;
            $maf[$k]['type'] = $req['type'];
            $maf[$k]['order_num'] = 0;
            $maf[$k]['me_sure'] = $req['me_sure'];
        }
        return $maf;
    }


    /**
     * 周模板添加数据
     * @param $time
     * @param $req
     * @param $doctor_id
     * @return array
     */
    protected function week_getMaf($time, $req, $doctor_id)
    {

        $maf = [];
        foreach ($time as $k => $v) {
//            $maf[$k]['schedule_id']=$sid;
//            $maf[$k]['schedule_date']=$req['schedule_date'];
            $maf[$k]['type'] = $req['type'];
            $maf[$k]['schedule_type'] = 1;
            $maf[$k]['organization_id'] = $req['organization_id'];
            $maf[$k]['docter_id'] = $doctor_id;
            $maf[$k]['time_period_id'] = $v;
            $maf[$k]['week'] = $req['week'];
        }

        return $maf;
    }


    /**
     * 获取会话列表
     * @return \Illuminate\Http\JsonResponse
     * @author Liu-Yh
     * Create By 2020/11/6 17:11
     */
    public function getUserListMsg()
    {
        $req = request()->post();
        $user = $this->user;
        $doctor_id = $user['id'];
        $where[] = ['product_type', 2];
        $where[] = ['order_status', '>', 2];
        $where[] = ['payment_status', 2];
        $where[] = ['docter_id', $doctor_id];
        $list = Order::with('user')->where($where)->orderBy('receiving_time', 'desc')->get();
        $newList = [];
        if ($list) {
            $list = $list->toArray();
            foreach ($list as $k => $v) {
                $messages = ImMessage::where(['senderId'=>'doctor_'.$doctor_id,'receiverId'=>'member_'.$v['user_id']])->orWhere(function ($query) use ($req,$doctor_id,$v){
                    $query->where(['senderId'=>'member_'.$v['user_id'],'receiverId'=>'doctor_'.$doctor_id]);
                })->orderBy('id','desc')->first();
                if($messages){
                    if($messages['type']=='text'){
                        $newList[$v['user_id']]['out_message'] = $messages['payload'];
                    }else if ($messages['type'] == 'audio'){
                        $newList[$v['user_id']]['out_message'] = "[语音消息]";
                    }else{
                        $newList[$v['user_id']]['out_message'] = "[图片消息]";
                    }
                    if (empty($messages['create_time'])){
                        $newList[$v['user_id']]['out_time'] = "";

                    }else{
                        $newList[$v['user_id']]['out_time'] = date('m-d',$messages['create_time']);
                    }
                }else{
                    $newList[$v['user_id']]['out_message'] = '';
                    $newList[$v['user_id']]['out_time'] = '';
                }

                $newList[$v['user_id']]['flag'] = 'member_' . $v['user_id'];
                $newList[$v['user_id']]['order_status'] = $v['order_status'];
                $newList[$v['user_id']]['nickname'] = $v['user']['nickname'];
                $newList[$v['user_id']]['avatar'] = $v['user']['avatar'];
                $newList[$v['user_id']]['remark'] = !empty($v['user']['remark'])?$v['user']['remark']:'';
            }
            $newList = array_values($newList);
        }
        return out($newList);
    }


    /**
     * 获取认证信息
     * @return mixed
     */
    public function getRenInfo()
    {
        $req = request()->post();
        $user = $this->user;
        $doctor_id = $user['id'];
        // 获取本人认证信息
        $returnRes = [];
        $docter = Docter::where('id', '=', $doctor_id)->first();
        if ($docter) {
            $docter = $docter->toArray();
        } else {
            return $docter;
        }
        $returnRes['info'] = $docter;
        // 获取申请的认证机构
        $org = DocterOrganization::with(['organization'])->where('docter_id', '=', $doctor_id)->get();
        $oqf = DocterOrganization::with(['office', 'qualification'])->where('docter_id', '=', $doctor_id)->get();
        foreach ($org as $k => $v) {
            $org[$k]['province'] = Areas::where('id', '=', $v['organization']['province_id'])->select('name')->first()['name'];
            $org[$k]['city'] = Areas::where('id', '=', $v['organization']['city_id'])->select('name')->first()['name'];
            $org[$k]['area'] = Areas::where('id', '=', $v['organization']['area_id'])->select('name')->first()['name'];
            $org[$k]['name'] = $v['organization']['name'];
        }
        $returnRes['orgList'] = $org;
        $returnRes['oqf'] = $oqf;
        return out($returnRes);
    }

    /**
     * 获取通话记录
     * @return mixed
     */
    public function callLog(){
        $req = request()->post();
        $user = $this->user;
        $doctor_id = $user['id'];
        $where =[];
        if(isset($req['order_id'])&&!empty($req['order_id'])){
            $where['order_id'] = $req['order_id'];
        }
        $where['docter_id'] = $doctor_id;
        $list = CallLog::where($where)->get();
        return out($list);
    }


    /**
     * 通话列表
     * @return mixed
     */
    public function user_call(){
        $req = request()->post();
        $user = $this->user;
        $doctor_id = $user['id'];
        $list=[];
//        var_dump($doctor_id);
//die();
        if(isset($req['user_id'])&&!empty($req['user_id'])){
            $ids = [];
            $orderList = Order::where(['user_id'=>$req['user_id'],'product_type'=>1,'payment_status'=>2])->select('id')->get();
            if($orderList){
                foreach ($orderList as $k=>$v){
                    $ids[$k] = $v['id'];
                }
            }
            $lists = CallLog::with('orders')->whereIn('order_id',$ids)->orderBy('call_time', 'desc')->get();
            if ($lists){
                foreach ($lists as $k=>$v){
                    $list[$k]['time'] = $v['call_time'];
                    $list[$k]['talk_time'] = $v['talk_time'];
                    $list[$k]['order_sn'] = $v['orders']['order_sn'];
                }
            }
        }else{
            $orderList = Order::with(['user','calllog'])->where(['docter_id'=>$doctor_id,'product_type'=>1,'payment_status'=>2])->groupBy(['user_id'])->get();

            if ($orderList){
                foreach ($orderList as $k=>$v){
                    $list[$k]['user'] = $v['user'];
                    $calls = CallLog::where('docter_id',$doctor_id)->orderBy('id','desc')->first();
                    if ($calls){

                        $list[$k]['user']['dates'] = $calls['call_time'];
                    }else{
                        $list[$k]['user']['dates'] = '无';
                    }

                    $save = UserDocter::where(['user_id'=>$v['user']['id'],'docter_id'=>$doctor_id])->first();

                    if ($save) {
                        $list[$k]['user']['remark'] = $save['remark'];
                    } else {
                        $list[$k]['user']['remark'] = '';
                    }

                    $list[$k]['user']['log'] = $v['calllog'];
//                    $list[$k]['log']['date'] = date('m/d',strtotime(end($v['calllog'])['call_time']));
                }
            }

        }

        return out($list);
    }

    /**
     * 获取聊天记录
     * @return mixed
     */
    public function getImList(){
        $req = request()->post();
        $user = $this->user;
        $doctor_id = $user['id'];
        $where =[];
        if(!isset($req['flag'])||empty($req['flag'])){
            return out("",500,'用户flag不能为空');
        }
        $list = ImMessage::where(['senderId'=>'doctor_'.$doctor_id,'receiverId'=>$req['flag']])->orWhere(function ($query) use ($req,$doctor_id){
            $query->where(['senderId'=>$req['flag'],'receiverId'=>'doctor_'.$doctor_id]);
        })->get();

        $newList=[];
        if ($list){
            foreach ($list as $k=>$v){
                $decode = json_decode($v['text'],true);
//               $newList[$k]['id']=$decode['id'];
                $newList[$k]['messageId']=$decode[0]['messageId'];
                $newList[$k]['type']=$decode[0]['type'];
                $newList[$k]['senderId']=$decode[0]['senderId'];
                $newList[$k]['receiverId']=$decode[0]['receiverId'];
                $newList[$k]['timestamp']=$decode[0]['timestamp'];
                $newList[$k]['payload']= json_decode($decode[0]['payload'],true);
            }

        }
        return out($newList);
    }
}
