<?php


namespace App\Http\Controllers;


use App\Models\CdmsUsers;
use App\Models\CommunitySchedule;
use App\Models\Docter;
use App\Models\DocterOrganization;
use App\Models\DocterSetting;
use App\Models\Order;
use App\Models\Organization;
use App\Models\OrganizationSettings;
use App\Models\PatientRemark;
use App\Models\Payment;
use App\Models\Schedule;
use App\Models\SchedulePeriod;
use App\Models\SelfSchedule;
use App\Models\SystemConfig;
use App\Models\TimePeriod;
use App\Models\WeekSchedule;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Encore\Admin\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use mysql_xdevapi\Exception;
use phpDocumentor\Reflection\DocBlock\Description;
use PhpParser\Comment\Doc;

class ScheDuleController  extends Controller
{

    public function __construct()
    {

        // 允许 $originarr 数组内的 域名跨域访问

        header('Access-Control-Allow-Origin:*');

        // 响应类型

        header('Access-Control-Allow-Methods:POST,GET');


        // 带 cookie 的跨域访问

        header('Access-Control-Allow-Credentials: true');

        // 响应头设置

        header('Access-Control-Allow-Headers:x-requested-with,Content-Type,X-CSRF-Token');

    }

    //获取订单
    public function getDocter()
    {
        return Docter::pluck('name','id')->toArray();
    }

    //备注
    public function paitent_remark()
    {
        $data['patient_id']= request('patient_id');
        $data['org_id'] = request('org_id');
        $data['type'] = request('type');
        $is_have = PatientRemark::where($data)->first();
        $data['remark'] = request('remark');
        if(empty($data['remark'])) return redirect('/cdms/nurse_users');
        if($is_have){
            PatientRemark::where(['id'=>$is_have->id])->update(['remark'=>$data['remark']]);
        } else {
            PatientRemark::insert($data);
        }
        return redirect('/cdms/nurse_users');
    }

    //发送短信
    public function  sendmsg(){

        $config = [
//            'app_id' => 'wx1c2357232cd25f65',
//            'secret' => 'c8cab53e4e52234ed1bc2abbdeaba57d',
            'app_id' => 'wx13bedfcc62e9bab0',
            'secret' => '175e5518b6426dd12d3096f24ca68fb8',
            'response_type' => 'array'
//            oVxTzvgYlGktIDZXwfLMLQ01Tr5s
        ];

        //3LUhWGlyiljxrT3Jh8orwQZ2LSHjfRs9SIHaB40O6q0
        //开发者调用模版消息接口时需提供模版ID
        //标题
        //offer进度提醒
        //行业
        //IT科技 - 互联网|电子商务
        //详细内容
        //{{first.DATA}}
        //人才姓名：{{keyword1.DATA}}
        //联系方式：{{keyword2.DATA}}
        //入职职位：{{keyword3.DATA}}
        //入职公司：{{keyword4.DATA}}
        //报到时间：{{keyword5.DATA}}
        //{{remark.DATA}}



//        oVxTzvgYlGktIDZXwfLMLQ01Tr5s 自己 oVxTzvhu4gs4RyCt4kJDRWOgsUXw周璐 oVxTzvgu4XnI5F2aF7DcrbJIp5fI 间行 oVxTzvl8DYQblYmLCIK3UXW_8jAY 落雨桐
        $renyuan = ['o481Y5AtcbnOQef1vc4rL4TwYpDU','oVxTzvgYlGktIDZXwfLMLQ01Tr5s']; //周璐
//        $renyuan = ['oVxTzvvTnnbjEE9jsalOYj4mtp6U','oVxTzvgu4XnI5F2aF7DcrbJIp5fI']; //简行
        $app = Factory::officialAccount($config );
//        $res = $app->broadcasting->status(3147483751);
//
//  "errcode" => 0
//  "errmsg" => "send job submission success"
//  "msg_id" => 3147483751
//  "msg_data_id" => 2247484953
//        ^ array:2 [▼
//  "errcode" => 40003
//  "errmsg" => "invalid openid rid: 5fc35ef3-7f3b3ef9-14537bc7"
//]
        $user = $app->user->get('oVxTzvgYlGktIDZXwfLMLQ01Tr5s');
        $res = $app->template_message->send([
            'touser' => 'oVxTzvgYlGktIDZXwfLMLQ01Tr5s',
            'template_id' => '3LUhWGlyiljxrT3Jh8orwQZ2LSHjfRs9SIHaB40O6q0',
//            'url' => 'https://t5.9026.com',
            'data' => [
                'first'=>'社区通知',
                'keyword1' => '王海军',
                'keyword2' => 18719141830,
                'keyword3' => '开发工程师',
                'keyword4' => '思维定制',
                'keyword5' => '2020-12-12',
            ],
        ]);
        dd($res);
        $res = $app->broadcasting->sendText("测试发送，测试发送",$renyuan);

    }


    //设置自己排班
    public function setSelfSchedule()
    {
        $docter_id = request('docter_id');
        $org_id = request('org_id');
        $date = request('date');
        $type = request('type','1,2'); //1 上午，2 下午，3 晚上
        $schedule_type = request('schedule_type');
        $self_setting = DocterSetting::where(['docter_id'=>$docter_id])->first();
        $times = [];
        if(!empty($self_setting)){
            $time_period = object_array(json_decode($self_setting->service_time));
            $times[1] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[0]['startTime']),intval($time_period[0]['endTime'])])->pluck('id')->toArray();
            $times[2] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[1]['startTime']),intval($time_period[1]['endTime'])])->pluck('id')->toArray();
            $times[3] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[2]['startTime']),intval($time_period[2]['endTime'])])->pluck('id')->toArray();
        }
        if(count($times) <3){
            return apiReturn(602,'请设置真确的时间段');
        }

        if(empty($docter_id) || empty($org_id) || empty('date') || empty($type) || empty($schedule_type)){
            return apiReturn(601,'缺少必要参数');
        }

        if(strtotime($date) < strtotime('tomorrow')){
            return apiReturn(602,'只能排明天以後的');
        }

        $week = date("w",strtotime($date));
        $types = explode(',',$type);
        if(!empty($types)){
            foreach ($types  as $t){
                $self_schedule = [
                    'schedule_date'=>$date,
                    'week'=>intval($week),
                    'schedule_type'=>$schedule_type,
                    'organization_id'=>$org_id,
                    'docter_id'=>$docter_id,
                    'type'=>intval($t)
                ];
                foreach ($times[intval($t)] as $id){
                    $self_schedule['time_period_id'] = $id;
                    $is_have = SelfSchedule::where(['docter_id'=>$docter_id,'organization_id'=>$org_id,'schedule_date'=>$date,'type'=>intval($t),'week'=>$week,'time_period_id'=>$id])->value('id');
                    if($is_have) continue;
                    SelfSchedule::insert($self_schedule);
                }
            }

            $cha = array_diff([1,2,3],$types);
            foreach ($cha as $t){
                SelfSchedule::where(['docter_id'=>$docter_id,'organization_id'=>$org_id,'schedule_date'=>$date,'type'=>intval($t)])->delete();
            }
        }
        return apiReturn(200,'ok');
    }


    //获取图文订单
    public function get_chat_order()
    {
        $org_id = 1;
        $docter_id = request('docter_id');
        if(empty($docter_id)){
            return json_encode(['code'=>601,'msg'=>'缺少必要参数','data'=>'']);

        }

        $list = Order::where(['organization_id'=>$org_id,'docter_id'=>$docter_id,'order_status'=>3])->with('orderUser')->distinct('user_id')->get('user_id');
        $user_list = [];
        foreach ($list as $val){
            $user_list[] = [
                'id'=>$val->user_id,
                'avatar'=>$val->orderUser->avatar,
                'name'=>$val->orderUser->nickname,
            ];
        }
        $data['docter'] =  Docter::where('id',$docter_id)->first(['id','avatar','name']);
        $data['order_list'] = $user_list;
        return  (json_encode(['code'=>200,'msg'=>'ok','data'=>$data]));
    }

    //跟新订单
    public function updateOrder(){
        $id = request('id');
        $status = request('status');
        if(empty($id) || empty($status)){
            return json_encode(['code'=>601,'msg'=>'缺少必要参数','data'=>'']);
        }
        $data = Order::where('id',$id)->update(['order_status'=>$status]);
        return  (json_encode(['code'=>200,'msg'=>'ok','data'=>$data]));

    }

    //获取周排班模板
    public function getWeekSchedule()
    {
        $docter_id = intval(request('docter_id'));
        $org_id = intval(request('org_id'));
        $type = intval(request('type'));
        if(empty($docter_id) || empty($type)){
            return apiReturn(604,'缺少必要参数');
        }

        if($type == 1){
            $role = 2;
            $setting = DocterSetting::where(['docter_id'=>$docter_id,'type'=>$type])->first();
        } else {
            $role = 1;
            $setting = OrganizationSettings::where(['org_id'=>$docter_id])->first();
        }

        //周字段映射
        $week_arr = [1=>'monday',2=>'tuesday',3=>'wednesday',4=>'thursday',5=>'friday',6=>'saturday',7=>'sunday'];
        $data = [
            [
                'date'=>"上午",
                'monday'=>false,
                'tuesday'=>false,
                'wednesday'=>false,
                'thursday'=>false,
                'friday'=>false,
                'saturday'=>false,
                'sunday'=>false,
            ],
            [
                'date'=>"下午",
                'monday'=>false,
                'tuesday'=>false,
                'wednesday'=>false,
                'thursday'=>false,
                'friday'=>false,
                'saturday'=>false,
                'sunday'=>false,
            ],
            [
                'date'=>"晚上",
                'monday'=>false,
                'tuesday'=>false,
                'wednesday'=>false,
                'thursday'=>false,
                'friday'=>false,
                'saturday'=>false,
                'sunday'=>false,
            ]
        ];
        if($role == 2){
            for ($i=0;$i<=7;$i++){
                if($i == 0) continue;
                for($j=0;$j<=2;$j++){
                    $is_self_have = WeekSchedule::where(['docter_id'=>$docter_id,'schedule_type'=>$type,'organization_id'=>$org_id,'week'=>$i,'type'=>$j+1])->count();
                    $is_other_have = WeekSchedule::where(['docter_id'=>$docter_id,'schedule_type'=>$type,'week'=>$i,'type'=>$j+1])->where('organization_id','!=',$org_id)->count();
                    if($is_self_have){
                        $data[$j][$week_arr[$i]] = true;
                    }
                    if($is_other_have){
                        $data[$j][$week_arr[$i]] = 'other';
                    }
                }
            }
        } else {
            for ($i=0;$i<6;$i++){
                for($j=0;$j<=2;$j++){
                    $is_self_have = WeekSchedule::where(['docter_id'=>$docter_id,'schedule_type'=>$type,'organization_id'=>$org_id,'week'=>$i+1])->count();
                    $is_other_have = WeekSchedule::where(['docter_id'=>$docter_id,'schedule_type'=>$type,'week'=>$i+1])->where('docter_id','!=',$docter_id)->count();
                    if($is_self_have){
                        $data[$j][$week_arr[$i]] = true;
                    }
                    if($is_other_have){
                        $data[$j][$week_arr[$i]] = 'other';
                    }
                }
            }
        }

        $name = Docter::where('id',$docter_id)->value('name');

        $shcedule_data['docter'] = $data;
        $shcedule_data['name'] = $name;

        $shcedule_data['role'] = $role;
        $shcedule_data['user_id'] = $docter_id;

        return apiReturn(200,'ok',$shcedule_data);
    }

    //设置周排班模板
    public function setWeekSchedule()
    {
        $docter_id = intval(request('docter_id'));
        $org_id = intval(request('org_id'));
        $type = intval(request('type')); //排班类型 1门诊 2 儿保 3计免
        $data = request('schedulingtime');
        if(empty($docter_id) || empty($org_id) || empty($type) || empty($data)){
            return apiReturn(601,'缺少必要参数');
        }
//        $docter_setting = [];
        if($type == 1){
            $docter_setting = DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id])->first();
        } else {
            $docter_setting = OrganizationSettings::where(['org_id'=>$org_id])->first();
        }
//        dd($docter_setting);


        $times = [];
        if(!empty($docter_setting)){
            $time_period = object_array(json_decode($docter_setting->service_time));
            $times[] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[1]['amStartTime']),intval($time_period[1]['amEndTime'])])->pluck('id')->toArray();
            $times[] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[2]['pmStartTime']),intval($time_period[2]['pmEndTime'])])->pluck('id')->toArray();
            $times[] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[3]['nightStartTime']),intval($time_period[3]['nightEndTime'])])->pluck('id')->toArray();
        }

        //沒有配置就新建
//        if(empty($docter_setting) || $times){
//            $docter_config = SystemConfig::get('docter_config');
//            $amCount = intval(((strtotime($docter_config['morning_end'])) - (strtotime($docter_config['morning_start']))) / ($docter_config['service_time']*60));
//            $pmCount = intval(((strtotime($docter_config['afternoon_end'])) - (strtotime($docter_config['afternoon_start']))) / ($docter_config['service_time']*60));
//            $evCount = intval(((strtotime($docter_config['evening_end'])) - (strtotime($docter_config['evening_start']))) / ($docter_config['service_time']*60));
//            $c_r = [
//                1=>['count'=>$amCount,'start_time'=>$docter_config['morning_start'],'end_time'=>$docter_config['morning_end']],
//                2=>['count'=>$pmCount,'start_time'=>$docter_config['afternoon_start'],'end_time'=>$docter_config['afternoon_end']],
//                3=>['count'=>$evCount,'start_time'=>$docter_config['evening_start'],'end_time'=>$docter_config['evening_end']]
//            ];
//
//            if($type == 1){
//                $setingData = [
//                    'docter_id'=>$docter_id,
//                    'type'=>$type,
//                    'status'=>false,
//                    'show_days'=>7,
//                    'service_time'=>json_encode($c_r),
//                    'service_times'=>30,
//                ];
//                $isHave = DocterSetting::where($setingData)->count();
//                if(!$isHave) {
//                    DocterSetting::insert($setingData);
//                }
//            } else {
//                $setingData = [
//                    'org_id'=>$docter_id,
//                    'type'=>$type,
//                    'status'=>false,
//                    'show_days'=>7,
//                    'service_time'=>json_encode($c_r),
//                    'service_times'=>30,
//                ];
//                $isHave = OrganizationSettings::where($setingData)->count();
//                if(!$isHave) {
//                    OrganizationSettings::insert($data);
//                }
//            }
//            foreach ($c_r as $key => $val){
//                self::makeTimePeriod($type,$docter_id,$org_id,$key,$val,$val['count'],$docter_config['service_time']);
//            }
//
//
//        }

        if($type == 1){
            $week_data = [
                'organization_id'=>$org_id,
                'docter_id'=>$docter_id
            ];
        } else {
            $week_data = [
                'organization_id'=>$org_id,
                'docter_id'=>0
            ];
        }
        $week_data  ['schedule_type']=$type;

        $k = 0;
        DB::beginTransaction();
        $data[0] = array_values(object_array(json_decode($data[0])));
        $data[1] = array_values(object_array(json_decode($data[1])));
        $data[2] = array_values(object_array(json_decode($data[2])));
        try {
            for($i=1;$i<=3;$i++){
                $schedule_data = $data[$i-1];
                foreach ($schedule_data as $key=>$schedule){
                    if($key == 0) continue;
                    $week_data ['type'] = $i;
                    $week_data ['week'] = $key;
                    if($schedule == true){
//                        echo '时间列类型'.($i+1).'----'.$key.'星期数'.'<br>';
                        foreach ($times[$i-1] as $id){
                            $week_data['time_period_id'] = $id;
                            if($type == 1){
                                $is_have = WeekSchedule::where(['docter_id'=>$docter_id,'schedule_type'=>$type,'type'=>$i,'week'=>$key])->where('time_period_id',$id)->value('id');
                            } else {
                                $is_have = WeekSchedule::where(['docter_id'=>0,'schedule_type'=>$type,'type'=>$i,'week'=>$key])->where('time_period_id',$id)->value('id');
                            }
                            if($is_have) continue;
                            $k++;
                            WeekSchedule::insert($week_data);
                        }
                    } else if ($schedule == false) {
                        if($type == 1){
                            $is_have = WeekSchedule::where(['docter_id' => $docter_id, 'organization_id' => $org_id, 'schedule_type' => $type,'type'=>$i,'week'=>$key])->whereIn('time_period_id', $times[$i-1])->value('id');
                            if($is_have) WeekSchedule::where(['docter_id' => $docter_id, 'organization_id' => $org_id, 'schedule_type' => $type,'type'=>$i,'week'=>$key])->whereIn('time_period_id', $times[$i-1])->delete();
                        } else {
                            $is_have = WeekSchedule::where(['docter_id' => 0, 'organization_id' => $org_id, 'schedule_type' => $type,'type'=>$i,'week'=>$key])->whereIn('time_period_id', $times[$i-1])->value('id');
                            if($is_have) WeekSchedule::where(['docter_id' => 0, 'organization_id' => $org_id, 'schedule_type' => $type,'type'=>$i,'week'=>$key])->whereIn('time_period_id', $times[$i-1])->delete();
                        }
                    }
                }
            }
            //todo 修改月视图
            DB::commit();
        } catch (\Exception $e){
            DB::rollBack();
            return apiReturn(602,$e->getLine().'行'.$e->getMessage());
        }
        return apiReturn(200,'ok',$k);
    }

    //设置月排班
    public function setmonthScheduel()
    {
        $docter_id = request('docter_id',1);
        $org_id = request('org_id',1);
        $type = request('type',2);
        $role = request('role',2);
        $date = request('date');
        if(empty($docter_id) || empty($type)){
            return apiReturn(604,'缺少必要参数');
        }
        $start_time = date('Y-m-d', strtotime($date));
        $end_time = date('Y-m-d',strtotime($date.'+1 month'));
        $docter_setting = DocterSetting::where(['docter_id'=>$docter_id])->first();

        $self_schedule = SelfSchedule::where(['docter_id'=>$docter_id,'organization_id'=>$org_id])->whereBetween('schedule_date',[$start_time,$end_time])->distinct('type')->get(['type','week'])->GroupBy('week')->toArray();
        $week_schedule = WeekSchedule::where(['docter_id'=>$docter_id,'organization_id'=>$org_id])->orderby('week')->distinct('type')->get(['type','week'])->GroupBy('week')->toArray();

        for ($i=1;$i<=7;$i++){
            $s = [];
            $w=[];
            if(!empty($self_schedule[$i])){
                $s =array_column($self_schedule[$i],'type');
            }
            if(!empty($week_schedule[$i])){
                $w =array_column($week_schedule[$i],'type');
            }
            if(!empty($s) || !empty($w)){
                $sn = $s+$w;
                $all_schedule[$i] = $sn;
            } else {
                $all_schedule[$i] = [];
            }
        }

        if(!empty($docter_setting)){
            $time_period = object_array(json_decode($docter_setting->service_time));
            $times[1] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[0]['startTime']),intval($time_period[0]['endTime'])])->pluck('id')->toArray();
            $times[2] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[1]['startTime']),intval($time_period[1]['endTime'])])->pluck('id')->toArray();
            $times[3] = TimePeriod::where(['docter_id'=>$docter_id])->whereBetween('end_time_period',[intval($time_period[2]['startTime']),intval($time_period[2]['endTime'])])->pluck('id')->toArray();
        }

        $start_time = strtotime($date);
        $month_day = date("t",strtotime($date));
        $begainDay = date("d",time()) - 1;

        DB::beginTransaction();
        try {
            for($i=$begainDay;$i<=$month_day;$i++){
                $today = $start_time + $i*86400;
                $nutoday = intval(date('Ymd',$today));
                $week = date('w',$today);
                if($week == 0){
                    $every_day = $all_schedule[7];
                } else {
                    $every_day = $all_schedule[$week];
                }
                $schedule_data = ['docter_id'=>$docter_id,'schedule_date'=>date('Y-m-d',$today),'schedule_day'=>$nutoday,'organization_id'=>$org_id];
                $is_have_schedule = Schedule::where(['docter_id'=>$docter_id,'schedule_date'=>date('Y-m-d',$today),'organization_id'=>$org_id])->first();
                dd($is_have_schedule);
                $schedule_id = Schedule::insertGetId($schedule_data);
                foreach ($every_day as $type){
                    foreach ($times[$type] as $tp){
                        $data = ['docter_id'=>$docter_id,'schedule_date'=>date('Y-m-d',$today),'organization_id'=>$org_id,'time_period_id'=>$tp,'type'=>$type,'schedule_id'=>$schedule_id];
                        SchedulePeriod::insert($data);
                    }
                }
                DB::commit();
            }
        } catch (\Exception $e){
            dd('第'.$e->getLine().'行报错： '.$e->getMessage());
            DB::rollBack();
            return apiReturn('603','插入失败');
        }


        echo '<pre>';
        print_r($self_schedule);
        echo '</pre>';

        dd($week_schedule);

    }

    //获取月排班
    public function get_month_schedule()
    {
        $date  = request('date');
        $org_id = intval(request('org_id'));
        $docter_id = intval(request('docter_id'));
        $type = intval(request('type')); //1门诊 2 计免 儿保
        $role = intval(request('role'));
        $start_time = strtotime($date);
        $month_day = date("t",$start_time);
        $end_time = ($start_time + $month_day * 86400);
        $start_date = date('Y-m-d',$start_time);
        $end_date = date('Y-m-d',$end_time);
        $types = [1=>1,2=>2,3=>3];
        $settingConfig =  self::getSetting($type,$docter_id,$org_id);

//        dump(date('Y-m-d',$start_time));
//        dd(date('Y-m-d',$end_time));
        if($type == 1){
            $schedule_data = Schedule::where(['docter_id'=>$docter_id,'organization_id'=>$org_id])
                ->whereBetween('schedule_date',[$start_date,$end_date])->pluck('schedule_date','id')->toArray();
            $serviceConfig = object_array(json_decode($settingConfig['service_time']));
        } else {
            $schedule_data = Schedule::where(['docter_id'=>0,'organization_id'=>$org_id])->
            whereBetween('schedule_date',[$start_date,$end_date])->pluck('schedule_date','id')->toArray();
            $serviceConfig = object_array(json_decode($settingConfig['service_time']));
        }
        if(!empty($settingConfig)){
            $baseData =  [
                ['status'=>false,'type'=>1,'start'=>$serviceConfig[1]['amStartTime'],'end'=>$serviceConfig[1]['amEndTime']],
                ['status'=>false,'type'=>2,'start'=>$serviceConfig[2]['pmStartTime'],'end'=>$serviceConfig[2]['pmEndTime']],
                ['status'=>false,'type'=>3,'start'=>$serviceConfig[3]['nightStartTime'],'end'=>$serviceConfig[3]['nightEndTime']],
            ];

        } else{
            $serviceConfig = '';
            $baseData =  [
                ['status'=>false,'type'=>1,'start'=>$serviceConfig[1]['amStartTime'],'end'=>$serviceConfig[1]['amEndTime']],
                ['status'=>false,'type'=>2,'start'=>$serviceConfig[2]['pmStartTime'],'end'=>$serviceConfig[2]['pmEndTime']],
                ['status'=>false,'type'=>3,'start'=>$serviceConfig[3]['nightStartTime'],'end'=>$serviceConfig[3]['nightEndTime']],
            ];

            self::baseMonthSchedule($month_day,$baseData);
            return [];
        }

        for($i=1;$i<=$month_day; $i++){
            //$startKey = date('d',time());
            $week = date('N',$start_time + ($i-1) * 86400);
            $scheduleDate = date('Y-m-d',$start_time + ($i-1) * 86400);


            if(empty($schedule_data)){
                $scheduleList[] = [
                    'schedulelingList'=>$baseData,
                    'date'=>$i,
                    'week'=>$week,
                    'day'=>$scheduleDate
                ];
            } else {


                if($type == 1){//门诊
                    $today = SchedulePeriod::where(['docter_id'=>$docter_id,'schedule_date'=>$scheduleDate])->where('organization_id','=',$org_id)->distinct('organization_id')
                        ->distinct('type')->get(['organization_id','type'])->GroupBy('type')->toArray();
                    $self = SelfSchedule::where(['schedule_date'=>$scheduleDate,'docter_id'=>$docter_id,])->where('organization_id','!=',0)->pluck('type','organization_id')->toArray();
//                    //检查排班详情
//                    self::checkDaySchedule($date,$type,$docter_id,$org_id);
//                    //检查自己排班
//                    self::checkSelfDaySchedule($date,$type,$docter_id,$org_id);
//                    echo '周几'.$week.' 日期 '.$scheduleDate.PHP_EOL;

                    if(empty($today)){
                        $scheduleList[] = [
                            'schedulelingList'=>$baseData,
                            'date'=>$i,
                            'week'=>$week,
                            'day'=>$scheduleDate
                        ];
                    } else {
//                        echo '周几'.$week.' 日期 '.$scheduleDate;
//                        dd($today);
                        foreach ($today as $type => $orginfo){
                            $newBase =$baseData;
                            $orgids = array_column($orginfo,'organization_id');
                            $idSum = array_sum($orgids);
                            if($org_id == $idSum) $newBase[$type]['status'] = true;
                            if($org_id != $idSum) $newBase[$type]['status'] = 'other';
                            if(in_array($type,$self))
                                foreach($self as $key=>$org){
                                    $newBase[$type]['status'] = true;
                                    if($org != $org_id) $newBase[$type]['status'] = 'other';
                                }
                        }
                        $scheduleList[] = [
                            'schedulelingList'=>$newBase,
                            'date'=>$i,
                            'week'=>$week,
                            'day'=>$scheduleDate
                        ];
                    }
                } else {
                    $today = SchedulePeriod::where(['docter_id'=>$docter_id,'schedule_date'=>$scheduleDate])->where('organization_id','!=',0)->distinct('organization_id')
                        ->distinct('type')->get(['organization_id','type'])->GroupBy('type')->toArray();

                    if(empty($today)){
                        $scheduleList[] = [
                            'schedulelingList'=>$baseData,
                            'date'=>$i,
                            'week'=>$week,
                            'day'=>$scheduleDate
                        ];
                    } else {
                        foreach ($today as $type => $orginfo){
                            $orgids = array_column($orginfo,'organization_id');
                            $idSum = array_sum($orgids);
                            if($org_id == $idSum) $baseData[$type]['status'] = true;
                            if($org_id != $idSum) $baseData[$type]['status'] = 'other';
                        }
                        $scheduleList[] = [
                            'schedulelingList'=>$baseData,
                            'date'=>$i,
                            'week'=>$week,
                            'day'=>$scheduleDate
                        ];
                    }
                }
            }
////            if(empty( $schedule_data[$scheduleDate])) continue;
////            $schedule_id = $schedule_data[$schedule_data];
//            if($type == 1){
//                $today = SchedulePeriod::where(['docter_id'=>$docter_id,'schedule_date'=>$scheduleDate])->get(['organization_id','type'])->GroupBy('type');
//
//                dd($today);
//            }
////            date'=>($i+1),'day'=>$now_date,'schedulelingList'=>$arr,'week'=>$week
////            dd($scheduleList);
//
//        }
//
//        $status = [1=>true,2=>'other',3=>false];
//
//        for($i=0;$i<$month_day;$i++){
//              $now_time = $start_time + $i*86400;
//              $now_date = date('Y-m-d',$now_time);
//              $week = date('N',$now_time);
//              $arr = [
//                  ['status'=>false,'type'=>1,'start'=>"09:00",'end'=>'11:30'],
//                  ['status'=>true,'type'=>2,'start'=>'13:30','end'=>'16:30'],
//                  ['status'=>false,'type'=>3,'start'=>'19:30','end'=>'21:00'],
//              ];
//              if($i%2 == 0){
//                  $arr = [
//                      ['status'=>false,'type'=>1,'start'=>"09:00",'end'=>'11:30'],
//                      ['status'=>true,'type'=>2,'start'=>'13:30','end'=>'16:30'],
//                      ['status'=>false,'type'=>3,'start'=>'19:30','end'=>'21:00'],
//                  ];
//              }
//
//            if($i%3 == 0){
//                $arr = [
//                    ['status'=>true,'type'=>1,'start'=>"09:00",'end'=>'11:30'],
//                    ['status'=>'other','type'=>2,'start'=>'13:30','end'=>'16:30'],
//                    ['status'=>true,'type'=>3,'start'=>'19:30','end'=>'21:00'],
//                ];
//            }
//
//            if($i%4 == 0){
//                $arr = [
//                    ['status'=>'other','type'=>1,'start'=>"09:00",'end'=>'11:30'],
//                    ['status'=>false,'type'=>2,'start'=>'13:30','end'=>'16:30'],
//                    ['status'=>false,'type'=>3,'start'=>'19:30','end'=>'21:00'],
//                ];
//            }
//
//            if($i == 14){
//                $arr = [
//                    ['status'=>false,'type'=>1,'start'=>"09:00",'end'=>'11:30'],
//                    ['status'=>false,'type'=>2,'start'=>'13:30','end'=>'16:30'],
//                    ['status'=>false,'type'=>3,'start'=>'19:30','end'=>'21:00'],
//                ];
//            }
//
//            $all_time[] = ['date'=>($i+1),'day'=>$now_date,'schedulelingList'=>$arr,'week'=>$week];
        }
        return apiReturn(200,'ok',$scheduleList);
    }


    //获取医生设置
    public function getDocterSetting()
    {
        $docter_id = intval(request('docter_id'));
        $org_id = intval(request('org_id'));
        $type = intval(request('type'));

        $setting = DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id])->first();
        if($type  == 2){
            $setting = OrganizationSettings::where(['org_id'=>$org_id])->first();
        }
        $docterConfig = SystemConfig::get('docter_config');
        if(!empty($setting)){
            $setting = $setting->toArray();
        } else {
            $configData = [
                'amStartTime'=>$docterConfig['morning_start'],
                'amEndTime'=>$docterConfig['morning_end'],
                'amNum'=>0,
                'pmStartTime'=>$docterConfig['afternoon_start'],
                'pmEndTime'=>$docterConfig['afternoon_start'],
                'pmNum'=>0,
                'nightStartTime'=>$docterConfig['evening_start'],
                'nightEndTime'=>$docterConfig['evening_end'],
                'nightNum'=>0,
                'serviceNum'=>1,
                'showDayNumber'=>7,
                'status'=>false,
                'timeSpan'=>30,
            ];
            return apiReturn(200,'ok',$configData);
        }
        $config = object_array(json_decode($setting['service_time']));

        $status = $setting['status'] ? true: false;
        $configData = [
            'amEndTime'=>$config[1]['amEndTime'],
            'amNum'=>$config[1]['amPerson'],
            'amStartTime'=>$config[1]['amStartTime'],
            'nightEndTime'=>$config[3]['nightEndTime'],
            'nightNum'=>$config[3]['nightPerson'],
            'nightStartTime'=>$config[3]['nightStartTime'],
            'pmEndTime'=>$config[2]['pmEndTime'],
            'pmNum'=>$config[2]['pmPerson'],
            'pmStartTime'=>$config[2]['pmStartTime'],
            'serviceNum'=>$setting['service_num'],
            'showDayNumber'=>$setting['show_days'],
            'status'=>$status,
            'timeSpan'=>$setting['service_times'],
        ];

        return apiReturn(200,'ok',$configData);

    }
    //更新用戶設置
    public function updateDocterSetting()
    {
        $docter_id = intval(request('docter_id'));
        $configData = request('configData');
        $type = intval(request('type'));//医生类型 1 门诊医生 2 计免 儿保医生
        $org_id = intval(request('org_id'));
        $configData = object_array(json_decode($configData));
        if(empty($docter_id) || empty($configData)){
            return apiReturn(604,'参数错误');
        }

        $setting  = DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id])->first();
        if($type != 1){
            $setting = OrganizationSettings::where(['org_id'=>$org_id])->first();
        }

        $self_config = object_array(json_decode($setting['service_time']));
        //改变时间段
        $changeTimer = [];
        //是否改变了服务时长
        $changeSeviceTime = false;

        $Today = date('Y-m-d',time());

        //同时服务人数
        $serviceNum = intval($configData['serviceNum']);

        //服务时长
        $serviceTime = intval($configData['timeSpan']);

        if(empty($setting) || $serviceTime != intval($setting['service_times'])){
            $changeSeviceTime = true;
            $changeTimer = [1,2,3];
        } else {

            if($configData['amStartTime'] !== $self_config[1]['amStartTime'] ||  $configData['amEndTime'] !== $self_config[1]['amEndTime']){
                $changeTimer[] = 1;

            }

            if($configData['pmStartTime'] !== $self_config[2]['pmStartTime'] ||  $configData['pmEndTime'] !== $self_config[2]['pmEndTime']){
                $changeTimer[] = 2;
            }

            if($configData['nightStartTime'] !== $self_config[3]['nightStartTime'] ||  $configData['nightEndTime'] !== $self_config[3]['nightEndTime']){
                $changeTimer[] = 3;
            }
        }
        // ToDO 算时间段个数
        //添加时间段
        $countArr = [
            1=>$configData['amNum'],
            2=>$configData['pmNum'],
            3=>$configData['nightNum'],
        ];

        $c_r = [
            1=>['count'=>$configData['amNum'],'start_time'=>$configData['amStartTime'],'end_time'=>$configData['amEndTime']],
            2=>['count'=>$configData['pmNum'],'start_time'=>$configData['pmStartTime'],'end_time'=>$configData['pmEndTime']],
            3=>['count'=>$configData['nightNum'],'start_time'=>$configData['nightStartTime'],'end_time'=>$configData['nightEndTime']]
        ];
        if(!$changeSeviceTime && empty($changeTimer)){
            return apiReturn(603,'数据为改变');
        }

        for ($i=1;$i<=3;$i++){
            $tType = $i;
            DB::beginTransaction();
            try {
                //1.删除旧时间段，并删除排班数据
//                    $type == 1 ? $id = $docter_id : $id = $org_id;
                if($type !=1 ){
                    $docter_id = 0;
                }
                //todo 暂时未删除周排班
                self::deleteScheduleInfo($docter_id,$tType,$org_id);
                $count = intval($countArr[$tType] / $serviceNum);
//                    dd($countArr);
                //2.创建新时间段
                self::makeTimePeriod($docter_id,$org_id,$tType,$c_r[$tType],$count,$serviceTime);

                if($type == 1){
                    $time_periods = TimePeriod::where(['org_id' => $org_id, 'docter_id' => $docter_id, 'type' => $tType])->pluck('id')->toArray();
                    $self_schedule = SelfSchedule::where(['docter_id' => $docter_id, 'schedule_type' => $type, 'organization_id'=>0,'type' =>1])->distinct('type')
                        ->orderBy('schedule_date')->get(['schedule_date', 'type', 'week'])->toArray();
                    $schedule = Schedule::where(['docter_id' => $docter_id, 'organization_id'=>0])->pluck('schedule_date', 'id')->toArray();
                    $week_schedule = WeekSchedule::where(['docter_id' => $docter_id, 'type' => $tType,'schedule_type'=>$type])
                        ->distinct('type')
                        ->orderBy('week')
                        ->get(['week','organization_id'])
                        ->GroupBy('week')
                        ->toArray();
                } else {
                    $time_periods = TimePeriod::where(['org_id' => $org_id, 'docter_id' => 0, 'type' => $tType])->pluck('id')->toArray();
                    $schedule = Schedule::where(['docter_id' => 0, 'organization_id'=>$org_id])->pluck('schedule_date', 'id')->toArray();
                    $self_schedule = SelfSchedule::where(['docter_id' => 0, 'schedule_type' => $type,'organization_id'=>$org_id,'type' =>$tType])->distinct('type')
                        ->orderBy('schedule_date')->where('schedule_date','>',$Today)->get(['schedule_date', 'type', 'week'])->toArray();
                    $week_schedule = WeekSchedule::where(['organization_id' =>$org_id, 'type' => $tType,'schedule_type'=>$type])
                        ->distinct('type')
                        ->orderBy('week')
                        ->pluck('type')
                        ->GroupBy('week')
                        ->toArray();
                }

                if (empty($week_schedule)) {

//                        Schedule::where(['docter_id' => $docter_id])->delete();
//                        SelfSchedule::where(['docter_id' => $docter_id])->delete();
                } else {
                    //3.以周模板添加2个月的数据
                    self::makeSchedule($docter_id,$org_id,$tType,$schedule,$time_periods);

                    //4.恢复自己设置的排班
                    self::makeSelfScheeule($docter_id,$org_id,$type,$tType,$time_periods,$self_schedule);

                    //TODO 删除周排班，插入新周排班
                    self::changeWeekSchedule($docter_id,$org_id,$type,$tType,$time_periods);
                }
                DB::commit();
            } catch (\Exception $e) {
                dd($e->getMessage());
                DB::rollBack();
            }
        }


//        {"1":{"amStartTime":"08:00","amEndTime":"12:00","amPerson":3},"2":{"pmStartTime":"14:00","pmEndTime":"18:00","pmPerson":5},"3":{"nightStartTime":"18:00","nightEndTime":"23:00","nightPerson":4}}
        $config = [
            1=>['amStartTime'=>$configData['amStartTime'],"amEndTime"=>$configData['amEndTime'],'amPerson'=>$configData['amNum']],
            2=>["pmStartTime"=>$configData['pmStartTime'],"pmEndTime"=>$configData['pmEndTime'],'pmPerson'=>$configData['pmNum']],
            3=>["nightStartTime"=>$configData['nightStartTime'],"nightEndTime"=>$configData['nightEndTime'],'nightPerson'=>$configData['nightNum']]
        ];
        $setting = [
            'docter_id'=>$docter_id,
            'type'=>$type,
            'status'=>$configData['status'],
            'show_days'=>$configData['showDayNumber'],
            'service_num'=>$configData['serviceNum'],
            'service_times'=>$configData['timeSpan'],
            'service_time'=>json_encode($config)
        ];



        //更新配置
        if($type == 1){
            $is_have = DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id])->value('id');
            if($is_have){
                DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id])->update($setting);
            } else {
                $setting['org_id'] = $org_id;
                DocterSetting::insert($setting);
            }
        } else {
            $setting['docter_id'] = 0 ;
            $setting['org_id'] = $org_id;
            $is_have = OrganizationSettings::where(['org_id'=>$org_id])->value('id');
            if($is_have){
                OrganizationSettings::where(['org_id'=>$org_id])->update($setting);
            } else {
                OrganizationSettings::insert($setting);
            }
        }
        return  apiReturn(200,'ok');
    }

    //获取用户信息
    public function getScheduleInfo()
    {
        $id = intval(request('id'));
        $isDocter = CdmsUsers::where('docter_id',$id)->first();
        $isOrg = CdmsUsers::where('org_id',$id)->first();

        $org_id = null;
        $role = 1;

        if(empty($id)){
            return json_encode(['status'=>601,'msg'=>'缺少必要参数','data'=>'']);
        }

        if($isDocter){
            $org_id = $isDocter->org_id;
            $docter = Docter::where(['id'=>$id])->first();
            $role = 2;
        } else {
            if(!empty($isOrg->org_id)){
                $org_id = $isOrg->org_id;
            } else {
                $role = 0;
            }
        }

        $lists =[];
        if($role == 1){
            $ids = DocterOrganization::where(['organization_id'=>$org_id])->pluck('docter_id')->toArray();
            $list = Docter::whereIn('id',$ids)->distinct('id')->get(['id','name']);
            foreach ($list as $val){
                $lists[] = ['value'=>$val->id,'label'=>$val->name];
            }
            $name = Organization::where('id',$org_id)->value('name');
        } else if($role == 2){
            $ids = DocterOrganization::where(['docter_id'=>$id])->distinct('docter_id')->pluck('organization_id')->toArray();
            $list = Organization::whereIn('id',$ids)->get(['id','name']);
            foreach ($list as $val){
                $lists[] = ['value'=>$val->id,'label'=>$val->name];
            }
            $name = Docter::where('id',$id)->value('name');
        } else {
            $name = '';
        }


        $type = 1;
        $data['user_id'] = $id;
        $data['name'] = $name;
        $data['org_id'] = $org_id;
        $data['docter_type'] = 0;
        $data['list'] = [];

        if(!empty($docter)){
            $data['docter_type'] = $docter->type;
            if($docter->type == 1){
                $data['list'] = $lists;
            } else {
                $organization = Organization::where(['id'=>$org_id])->first();
                $data['list'] = ['value'=>$organization->id,'label'=>$organization->name];
            }
        }
        $data['docter_type'] = 2;

        $data['role'] = $role;
        return (json_encode(['code'=>200,'msg'=>'ok','data'=>$data]));
    }

    /*
     * @param
     * $id int 医生或社区id
     * $type int 排班类型
     * @descript 删除排班数据
     */
    public static function deleteScheduleInfo($docter_id,$timeType,$orgId=0){
        if($docter_id != 0){
            TimePeriod::where(['docter_id'=>$docter_id,'type'=>$timeType])->where('org_id','=',$orgId)->delete();
            SchedulePeriod::where(['docter_id'=>$docter_id,'type'=>$timeType])->where('organization_id','=',$orgId)->delete();
        } else {
            TimePeriod::where(['org_id'=>$orgId,'type'=>$timeType])->where('docter_id',0)->delete();
            SchedulePeriod::where(['organization_id'=>$orgId,'type'=>$timeType])->where('docter_id',0)->delete();
        }
        return true;
    }

    //插入时间段
    public static function makeTimePeriod($docterId,$orgId,$timeType,$timeConfig,$timerCount,$serviceTime)
    {
        for($i=1;$i<=$timerCount;$i++){
            $timePreiod = [
                'org_id'=>$orgId,
                'docter_id'=>$docterId,
                'type'=>$timeType,
                'start_time_period'=> date('H:i',strtotime($timeConfig['start_time']) + ($i-1)*$serviceTime*60),
                'end_time_period'=> date('H:i',strtotime($timeConfig['start_time']) + $i*$serviceTime*60),
            ];
//            if($scheduleType == 1){
//                $timePreiod['org_id'] = $orgId;
//                $timePreiod['docter_id'] = $docterId;
//            }  else {
//                $timePreiod['docter_id'] = 0;
//                $timePreiod['org_id'] = $orgId;
//            }
            $isHave = TimePeriod::where($timePreiod)->count();
            if($isHave) continue;
            TimePeriod::insert($timePreiod);
        }
        return true;
    }

    //以周模板进行排班
    public static function makeSchedule ($docterId,$orgId,$tType,$schedule,$timePeriods){

        if(empty($schedule) || count($schedule) < 58){
            $start = strtotime(date('Y-m-1',time()));
            $today = date('j',time());
            $allDay = date('t',time());

            //第一个月
            for ($i=$today;$i<=$allDay;$i++){
                $todayTimer = $start + (($i - 1) *86400);
                $week = date('N',$todayTimer);

                $date = date('Y-m-d',$todayTimer);
                $numDate = date('Ymd',$todayTimer);
                $scheduleData['schedule_date'] = $date;
                $scheduleData['schedule_day'] = $numDate;

                $scheduleIsHave = Schedule::where($scheduleData)->count();
                if ($scheduleIsHave) continue;
                Schedule::insertGetId($scheduleData);
            }
            $nextStart = strtotime(date('Y-m-1',strtotime('next month')));
            $nextAllDay = date('t',strtotime('nex month'));


            //第二个月
            for($j=1;$j<=$nextAllDay;$j++){
                $todayTimer = $nextStart + (($j-1)*86400);
                $week = date('N',$todayTimer);
                $date = date('Y-m-d',$todayTimer);
                $numDate = date('Ymd',$todayTimer);
                $scheduleData['schedule_date'] = $date;
                $scheduleData['schedule_day'] = $numDate;
                $scheduleIsHave = Schedule::where($scheduleData)->count();
                if ($scheduleIsHave) continue;
                Schedule::insertGetId($scheduleData);
            }
            $schedule = Schedule::where(['docter_id'=>$docterId,'organization_id'=>$orgId])->where('schedule_date','>',date('Y-m-d',time()))
                ->distinct('schedule_date')->pluck('schedule_date','id')->toArray();
            if($docterId == 0){
                $schedule = Schedule::where(['docter_id'=>0,'organization_id'=>$orgId])->where('schedule_date','>',date('Y-m-d',time()))
                    ->distinct('schedule_date')->pluck('schedule_date','id')->toArray();
            }
        }

        foreach ($schedule as $id => $date) {
            $week = intval(date('N', strtotime($date)));
//            echo '医生id '.$docterId.' 机构id '.$orgId.' 周几 '.$week;
            $real_id = WeekSchedule::where(['docter_id'=>$docterId,'organization_id'=>$orgId,'week'=>$week])->first();
            if (!empty($real_id)) {
//                    dump($schedule);

                foreach ($timePeriods as $idt) {

                    if($docterId != 0){//门诊
                        $s_t = [
                            'docter_id' => $docterId,
                            'organization_id' => $orgId,
                            'type' => $tType,
                            'schedule_date' => $date,
                            'schedule_id' => $id,
                            'time_period_id' => $idt
                        ];
                        $scheduleIsHave = SchedulePeriod::where($s_t)->where('docter_id','!=',0)->count();
                        if ($scheduleIsHave) continue;
                    } else {
                        $s_t = [
                            'docter_id' => 0,
                            'organization_id' => $orgId,
                            'type' => $tType,
                            'schedule_date' => $date,
                            'schedule_id' => $id,
                            'time_period_id' => $idt
                        ];
                        $scheduleIsHave = SchedulePeriod::where($s_t)->where('docter_id','=',0)->count();
                        if ($scheduleIsHave) continue;
                    }
                    $res = SchedulePeriod::insert($s_t);

                }
            }
        }
        return true;
    }

    //自己排班
    public static function makeSelfScheeule($docterId,$orgId,$scheduleType,$timeType,$timesPeriods,$selfSchedule){

        $date = date('Y-m-d',time());
        //删除自己排班数据
        SelfSchedule::where(['type'=>$timeType,'docter_id'=>$docterId,'organization_id'=>$orgId,'schedule_type'=>$scheduleType])->where('schedule_date','>',$date)->delete();
        foreach ($selfSchedule as $val) {
            $self_data = $val;
            $self_data['organization_id'] = $orgId;
            $self_data['docter_id'] = $docterId;
            foreach ($timesPeriods as $id) {
                $self_data['time_period_id'] = $id;
                $is_self_have = SelfSchedule::where($self_data)->count();
                if ($is_self_have) continue;
                SelfSchedule::insert($self_data);
            }
        }
    }


    public function setDaySchedule()
    {

        //todo 上线取消默认值
        $schdule_data = request('schedule_data');
        $docter_id = intval(request('docter_id'));
        $type = intval(request('type'));
        $org_id = intval(request('org_id'));
        $date = request('date');
        //判断排班类型

        if(empty($schdule_data) || empty($docter_id) || !isset($org_id) || empty($type)){
            return apiReturn(601,'缺少必要参数');
        }
        //获取医生排班配置
        $schedule = object_array(json_decode($schdule_data));
        //默认为门诊排班医生配置
        $setting = self::getSetting($type,$docter_id,$org_id);
        if(empty($setting)){
            self::setDefultSetting($type,$docter_id,$org_id);
            $setting = self::getSetting($type,$docter_id,$org_id);
        }


        $schdule_data = [
            ['status'=>true,'type'=>1,'start'=>"09:00",'end'=>'11:30','date'=>15,'week'=>1],
            ['status'=>true,'type'=>2,'start'=>'13:30','end'=>'16:30','date'=>15,'week'=>1],
            ['status'=>false,'type'=>3,'start'=>'19:30','end'=>'21:00','date'=>15,'week'=>1],
        ];

        DB::beginTransaction();
        try {
            foreach ($schdule_data as $t=>$v){

                $today = date('Y-m-d',(strtotime($date) + (intval($v['date'])-1) *86400) );
                $week = $schdule_data[0]['week'];
                $num_date = intval(str_replace('-','',$today));

                if($v['status'] == true){
                    $sche_data = ['organization_id'=>$org_id,'schedule_date'=>$today,'schedule_day'=>$num_date];

                    //判断是否有排班信息
                    $s_id = Schedule::where($sche_data)->value('id');
                    if(!$s_id){
                        $s_id = Schedule::insertGetId($sche_data);
                    }

                    //获取时间段
                    $timeperiods = TimePeriod::where(['docter_id'=>intval($docter_id),'org_id'=>intval($org_id),'type'=>intval($v['type'])])->pluck('id')->toArray();
                    if($type == 2){
                        $timeperiods = TimePeriod::where(['docter_id'=>intval($docter_id),'org_id'=>0,'type'=>intval($v['type'])])->pluck('id')->toArray();
                    }

                    if(empty($timeperiods)){
                        return apiReturn(603,'没有时间段');
                        self::setTimeperiod($type,$docter_id,$org_id);
                        $timeperiods = self::getTypeTimeperiod($type,$docter_id,$org_id,intval($v['type']));
                    }
                    foreach ($timeperiods as $id){
                        $data = [
                            'organization_id'=>$org_id,
                            'time_period_id'=>$id,
                            'week'=>$week,
                            'type'=>$v['type'],
                            'schedule_date'=>$today,
                            'docter_id'=>$docter_id,
                        ];

                        //检查是否已经有数据
                        $self_count = SelfSchedule::where($data)->value('id');
                        if($self_count) continue;
                        SelfSchedule::insert($data);
                    }

                } else if($v['status'] == false){
                    $data = [
                        'organization_id'=>$org_id,
                        'week'=>$week,
                        'type'=>$v['type'],
                        'docter_id'=>$docter_id,
                        'schedule_date'=>$today
                    ];
                    //判断是否有自己的排班
                    $self_count = SelfSchedule::where($data)->count();
                    if($self_count) SelfSchedule::where($data)->delete();

                    //检查是否是有周排班
                    $week_schedule = WeekSchedule::where(['week'=>$week,'docter_id'=>$docter_id,'type'=>intval($v['type']),'organization_id'=>$org_id])->count();
                    if(!$week_schedule) continue;

                    //获取排班id
                    $s_id = Schedule::where(['schedule_date'=>$today,'docter_id'=>$org_id])->value('id');
                    if(!$s_id) continue;

                    //删除排班和详细排班数据
                    Schedule::where(['id'=>$s_id])->delete();
                    TimePeriod::where(['docter_id'=>$docter_id,'org_id'=>$org_id,'type'=>$t,'schedule_id'=>$s_id])->delete();
                }
            }
            DB::commit();
        } catch (\Exception $e){
            dd($e->getMessage());
            DB::rollBack();
            return apiReturn(603,'操作失败');
        }
        return apiReturn(200,'操作成功');
    }

    public static function setTimeperiod($type,$docterId,$orgId)
    {
        $setting = self::getSetting($type,$docterId,$orgId);
        $serviceTime = $setting['service_times'];
        $serviceConfig = object_array(json_decode($setting->service_time));
        $fieldArr = [1=>'am',2=>'pm',3=>'night'];
        foreach ($serviceConfig as $t =>$service){
            $p = $fieldArr[$t];
            for($i=1;$i<=$service[$p.'Person'];$i++){
                $start_time = strtotime($service[$p.'StartTime']);
                if($type == 1){
                    $timePreiod['org_id'] = $orgId;
                    $timePreiod['docter_id'] = $docterId;
                }  else {
                    $timePreiod['docter_id'] = 0;
                    $timePreiod['org_id'] = $orgId;
                }
                $timePreiod = [
                    'type'=>$t,
                    'start_time_period'=> date('H:i',$start_time+ ($i-1)*$serviceTime*60),
                    'end_time_period'=> date('H:i',$start_time + $i*$serviceTime*60),
                ];
                $isHave = TimePeriod::where($timePreiod)->count();
                if($isHave) continue;
                TimePeriod::insert($timePreiod);
            }
        }
        return true;

    }

    public static  function setDefultSetting($type,$docterId,$orgId)
    {

        $configData = [
            'amEndTime'=>"11:30",
            'amNum'=>5,
            'amStartTime'=>"09:00",
            'nightEndTime'=>"20:30",
            'nightStartTime'=>"19:00",
            'nightNum'=>3,
            'pmEndTime'=>"16:00",
            'pmNum'=>5,
            'pmStartTime'=>"13:30",
            'showDayNumber'=>7,
            'serviceNum'=>2,
            'status'=>false,
            'timeSpan'=>30,
        ];

        $config = [
            1=>['amStartTime'=>$configData['amStartTime'],"amEndTime"=>$configData['amEndTime'],'amPerson'=>$configData['amNum']],
            2=>["pmStartTime"=>$configData['pmStartTime'],"pmEndTime"=>$configData['pmEndTime'],'pmPerson'=>$configData['pmNum']],
            3=>["nightStartTime"=>$configData['nightStartTime'],"nightEndTime"=>$configData['nightEndTime'],'nightPerson'=>$configData['nightNum']]
        ];

        $setting = [
            'type'=>$type,
            'org_id'=>$orgId,
            'status'=>$configData['status'],
            'show_days'=>$configData['showDayNumber'],
            'service_num'=>$configData['serviceNum'],
            'service_times'=>$configData['timeSpan'],
            'service_time'=>json_encode($config)
        ];

        if($type == 1){
            $is_have = DocterSetting::where(['docter_id'=>$docterId,'org_id'=>$orgId])->count();
            if(!$is_have){
                $setting['docter_id'] = $docterId;
                DocterSetting::insert($setting);
            } else {
                DocterSetting::where(['docter_id'=>$docterId,'org_id'=>$orgId])->update($setting);
            }
            return true;
        }

        $is_have = OrganizationSettings::where(['org_id'=>$orgId])->count();
        if(!$is_have){
            OrganizationSettings::insert($setting);
        } else {
            $setting['docter_id'] = $docterId;
            OrganizationSettings::where(['org_id'=>$orgId])->update($setting);
        }
        return true;
    }

    public static function getSetting($type,$docterId,$orgId){
        //默认为门诊排班医生配置
        $setting = DocterSetting::where(['docter_id'=>$docterId,'org_id'=>$orgId])->first();
        //获取社区排班设置
        if($type == 2) $setting = OrganizationSettings::where(['org_id'=>$orgId])->first();
        if(empty($setting)){
            self::setDefultSetting($type,$docterId,$orgId);
            self::getSetting($type,$docterId,$orgId);
        }
        return $setting;
    }
    public static function getTypeTimeperiod($type,$docterId,$orgId,$scType){
        //获取时间段
        $timeperiods = TimePeriod::where(['docter_id'=>$docterId,'org_id'=>$orgId,'type'=>$scType])->pluck('id')->toArray();
        if($type == 2){
            $timeperiods = TimePeriod::where(['docter_id'=>0,'org_id'=>$orgId,'type'=>$scType])->pluck('id')->toArray();
        }
        if(empty($timeperiods)){
            self::setTimeperiod($type,$docterId,$orgId);
            self::getTypeTimeperiod($type,$docterId,$orgId,$scType);
        }
        return $timeperiods;
    }

    //更新周排班时间段
    public static function changeWeekSchedule($docterId,$orgId,$scheduleType,$timeType,$timePeriod)
    {
        //获取旧的周排班
        $oldWeekSchedule = WeekSchedule::where(['docter_id'=>$docterId,'organization_id'=>$orgId,'schedule_type'=>$scheduleType,'type'=>$timeType])->orderBy('week')->distinct('week')->get(['organization_id','docter_id','schedule_type','week','type'])->toArray();

        //删除老周排班
        WeekSchedule::where(['docter_id'=>$docterId,'organization_id'=>$orgId,'schedule_type'=>$scheduleType,'type'=>$timeType])->delete();

        //更新时间段
        foreach ($oldWeekSchedule as $daySchedule){
            foreach ($timePeriod as $id){
                $daySchedule['time_period_id'] = $id;
            }
            WeekSchedule::insert($daySchedule);
        }
        return true;
    }

}
