<?php


namespace App\Community\Controllers;


use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\Docter;
use App\Models\DocterOrganization;
use App\Models\DocterSetting;
use App\Models\Order;
use App\Models\Organization;
use App\Models\PatientRemark;
use App\Models\Schedule;
use App\Models\SchedulePeriod;
use App\Models\SystemConfig;
use App\Models\TimePeriod;
use App\Models\WeekSchedule;
use EasyWeChat\Factory;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class ApiController 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()
    {
        $user = Admin::user();
        $where = [];
        if ($user->docter_id) {
            $where ['id'] = $user->docter_id;
        }
        return Docter::where($where)->get(['name as text', 'id'])->toArray();
    }

    /**
     * 后台上传图片
     * @return string
     */

    public function upload()
    {
        $url = "error|服务器端错误";

        foreach (request()->file() as $file) {
            $url = "upload/images/".uniqid().rand(9000,100000).'.'.$file->getClientOriginalExtension();
            file_put_contents($url,file_get_contents($file->getRealPath()));
        }
        return env('APP_URL').'/'.$url;
    }

    public function getCity()
    {
        $id  = request('q');
        return Area::where(['level'=>2,'parent_id'=>intval($id)])->get(['name as text','id']);
    }

    public function getArea()
    {
        $id  = request('q');
        return Area::where(['level'=>3,'parent_id'=>intval($id)])->get(['name as text','id']);
    }

    //备注
    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 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'));
        $role = intval(request('role'));
        if (empty($role) || empty($type)) {
            return apiReturn(604, '缺少必要参数');
        }

        //周字段映射
        $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 ($type == 1) {
            if ($role == 2 || $role == 1) {
                for ($i = 1; $i <= 7; $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, '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=1;$i<=7;$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';
//                        }
//                    }
//                }
            }
        } else {
            $docter_id = 0;
            for ($i = 1; $i <= 7; $i++) {
                for ($j = 0; $j <= 2; $j++) {
                    $is_self_have = WeekSchedule::where(['docter_id' => $docter_id, 'schedule_type' => $type, 'type' => $j + 1, 'organization_id' => $org_id, 'week' => $i])->count();
                    if ($is_self_have) {
                        $data[$j][$week_arr[$i]] = true;
                    }
                }
            }
        }

        $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'));
        $sType = intval(request('type')); //排班类型 1门诊 2 儿保 3计免
        $data = request('schedulingtime');
        if ($sType != 1) {
            $docter_id = 0;
        }
        if (empty($org_id) || empty($sType) || empty($data)) {
            return apiReturn(601, '缺少必要参数');
        }

        $docter_setting = DocterSetting::where(['docter_id' => $docter_id, 'org_id' => $org_id, 'type' => $sType])->first();
//        $serviceNum = 0;
        $times = [];
        if (!empty($docter_setting)) {
//            $serviceNum = $docter_setting->service_num;
            $time_period = object_array(json_decode($docter_setting->service_time));
            $allCount = TimePeriod::where(['docter_id' => $docter_id, 'org_id' => $org_id])->count();
            if ($allCount == 0) return apiReturn(603, '请设置时间段');
            $times[] = TimePeriod::where(['docter_id' => $docter_id, 'org_id' => $org_id, 'type' => $sType])->whereBetween('end_time_period', [intval($time_period[1]['amStartTime']), intval($time_period[1]['amEndTime'])])->pluck('id')->toArray();
            $times[] = TimePeriod::where(['docter_id' => $docter_id, 'org_id' => $org_id, 'type' => $sType])->whereBetween('end_time_period', [intval($time_period[2]['pmStartTime']), intval($time_period[2]['pmEndTime'])])->pluck('id')->toArray();
            $times[] = TimePeriod::where(['docter_id' => $docter_id, 'org_id' => $org_id, 'type' => $sType])->whereBetween('end_time_period', [intval($time_period[3]['nightStartTime']), intval($time_period[3]['nightEndTime'])])->pluck('id')->toArray();
        }
        if (count($times) < 3) {
            return apiReturn('603', '请配置时间段');
        }

        if ($sType != 1) {
            $docter_id = 0;
        }

        $week_data  ['schedule_type'] = $sType;
        $week_data  ['organization_id'] = $org_id;
        $week_data  ['docter_id'] = $docter_id;

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

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

    //设置月排班
    public function setmonthScheduel($docterId, $orgId, $sType, $timePeriods)
    {

        $today = intval(date('Ymd', time()));
        $start = time();

        //删除排班
        $schedule_ids = Schedule::where(['docter_id' => $docterId, 'schedule_type' => $sType])->where('schedule_day', '>', $today)->pluck('id')->toArray();
//        Schedule::where(['docter_id'=>$docterId])->where('schedule_day','>',$today)->delete();
        //删除具体排班
        SchedulePeriod::where('organization_id', $orgId)->where('me_sure', 0)->whereIn('schedule_id', $schedule_ids)->delete();
        $allScheduleData = [];
        //插入两个月的数据
        for ($i = 1; $i < 60; $i++) {
            $todayTimer = $start + (($i - 1) * 86400);
            $date = date('Y-m-d', $todayTimer);
            $numDate = date('Ymd', $todayTimer);

            $scheduleData['docter_id'] = $docterId;
            $scheduleData['schedule_date'] = $date;
            $scheduleData['schedule_day'] = $numDate;
            $scheduleData['schedule_type'] = $sType;
            if ($sType != 1) $scheduleData['organization_id'] = $orgId;

            $scheduleIsHave = Schedule::where($scheduleData)->count();
//            $scheduleData['per_time_num'] = $serviceNum;
            //循环外批量插入
            if (!$scheduleIsHave) $allScheduleData[] = $scheduleData;
        }
        if ($allScheduleData) Schedule::insert($allScheduleData);

//        echo '医生id '.$docterId.' 机构id '.$orgId . 'times ';
        $schedule = Schedule::where(['docter_id' => $docterId, 'schedule_type' => $sType])->where('schedule_date', '>=', date('Y-m-d', time()))
            ->distinct('schedule_date')->pluck('schedule_date', 'id')->toArray();

        $allData = [];
        for ($tType = 1; $tType <= 3; $tType++) {
            foreach ($schedule as $id => $date) {
                $week = intval(date('N', strtotime($date)));
                $real_id = WeekSchedule::where(['docter_id' => $docterId, 'organization_id' => $orgId, 'schedule_type' => $sType, 'week' => $week, 'type' => $tType])->first();
                if (!empty($real_id)) {
                    foreach ($timePeriods[$tType - 1] as $idt) {
                        $s_t = [
                            'docter_id' => $docterId,
                            'organization_id' => $orgId,
                            'type' => $tType,
                            'schedule_date' => $date,
                            'schedule_type' => $sType,
                            'schedule_id' => $id,
                            'time_period_id' => $idt
                        ];

                        $scheduleIsHave = SchedulePeriod::where($s_t)->count();
                        $s_t['order_num'] = 0;
                        $s_t['me_sure'] = 0;
                        if (!$scheduleIsHave) $allData[] = $s_t;

                    }
                }
            }

        }

        if ($allData) SchedulePeriod::insert($allData);

        //删除 Schedule里面SchedulePeriod 没有的日期
        foreach ($schedule as $date) {
            $c = SchedulePeriod::where(['docter_id' => $docterId, 'schedule_date' => $date, 'schedule_type' => $sType])->count();
            if ($c == 0) Schedule::where(['docter_id' => $docterId, 'schedule_date' => $date, 'schedule_type' => $sType])->delete();
        }
        return apiReturn('200', 'ok');

    }

    //获取月排班
    public function getMonthSchedule()
    {
        $date = request('date');
        $org_id = intval(request('org_id'));
        $docter_id = intval(request('docter_id'));
        $sType = intval(request('type')); //1门诊 2 计免 儿保
        $start_time = strtotime($date);
        $month_day = date("t", $start_time);
        $settingConfig = self::getSetting($sType, $docter_id, $org_id);
        if (empty($date) || empty($org_id) || empty($sType)) {
            return apiReturn(603, '参数错误');
        }
        if ($sType != 1) {
            $docter_id = 0;
        }
        $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 {
            $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']],
            ];
        }


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

            $scheduleList[$i - 1] = [
                'schedulelingList' => $baseData,
                'date' => $i,
                'week' => $week,
                'day' => $scheduleDate
            ];

            $newBase = $baseData;
            if ($sType === 1) {//门诊
                $today = SchedulePeriod::where(['docter_id' => $docter_id, 'schedule_date' => $scheduleDate, 'organization_id' => $org_id])->distinct('organization_id')
                    ->distinct('type')->get(['organization_id', 'type'])->GroupBy('type')->toArray();
//                    echo '周几'.$week.' 日期 '.$scheduleDate.PHP_EOL;
                if (empty($today)) {
                    $scheduleList[$i - 1] = [
                        'schedulelingList' => $baseData,
                        'date' => $i,
                        'week' => $week,
                        'day' => $scheduleDate
                    ];
                } else {
//                        echo '周几'.$week.' 日期 '.$scheduleDate.'<br>';
//                        dump($today);
                    foreach ($today as $tType => $orginfo) {
                        $orgids = array_column($orginfo, 'organization_id');
                        $idSum = array_sum($orgids);
                        if ($org_id == $idSum) $newBase[$tType - 1]['status'] = true;
                        if ($org_id != $idSum) $newBase[$tType - 1]['status'] = 'other';
                    }
//
                }

                $scheduleList[$i - 1] = [
                    'schedulelingList' => $newBase,
                    'date' => $i,
                    'week' => $week,
                    'day' => $scheduleDate
                ];
            } else {
//                echo '医生id '.$docter_id.' 机构id '.$org_id.' 周几'.$week.' 日期 '.$scheduleDate.'<br>';

                $today = SchedulePeriod::where(['docter_id' => $docter_id, 'schedule_date' => $scheduleDate, 'schedule_type' => $sType, 'organization_id' => $org_id])->distinct('organization_id')
                    ->distinct('type')->get(['organization_id', 'type'])->GroupBy('type')->toArray();
                if (empty($today)) {
                    $scheduleList[$i - 1] = [
                        '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) $newBase[$type - 1]['status'] = true;
                    }
                }

                $scheduleList[$i - 1] = [
                    'schedulelingList' => $newBase,
                    'date' => $i,
                    'week' => $week,
                    'day' => $scheduleDate
                ];
            }
        }
        return apiReturn(200, 'ok', $scheduleList);
    }


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

//        $setting = DocterSetting::where(['docter_id'=>$docter_id,'org_id'=>$org_id,'type'=>$sType])->first();
        $setting = self::getSetting($sType, $docter_id, $org_id);

        $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'] == 2 ? 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');
        $sType = intval(request('type'));//医生类型 1 门诊医生 2 计免 儿保医生
        $org_id = intval(request('org_id'));
        $configData = object_array(json_decode($configData));
        if (empty($configData)) {
            return apiReturn(604, '参数错误');
        }

        $setting = DocterSetting::where(['docter_id' => $docter_id, 'org_id' => $org_id, 'type' => $sType])->first();
        if ($sType != 1) {
            $docter_id = 0;
        }
        $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 算时间段个数
        $amCount = self::getTimeCount($configData['amStartTime'], $configData['amEndTime'], $serviceTime);
        $pmCount = self::getTimeCount($configData['pmStartTime'], $configData['pmEndTime'], $serviceTime);
        $nightCount = self::getTimeCount($configData['nightStartTime'], $configData['nightEndTime'], $serviceTime);

        //添加时间段
        $countArr = [
            1 => $amCount,
            2 => $pmCount,
            3 => $nightCount,
        ];

        $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']]
        ];

        $times = [
            1 => [$configData['amStartTime'], $configData['amEndTime']],
            2 => [$configData['pmStartTime'], $configData['pmEndTime']],
            3 => [$configData['nightStartTime'], $configData['nightEndTime']],
        ];

        if (!$changeSeviceTime && empty($changeTimer) && empty($serviceNum) && empty($configData['showDayNumber'])) {
            return apiReturn(603, '数据未改变');
        }

        TimePeriod::where(['org_id' => $org_id, 'type' => $sType, 'docter_id' => $docter_id])->delete();

        for ($i = 1; $i <= 3; $i++) {
            $tType = $i;
            DB::beginTransaction();
            try {
                //1.删除旧时间段，并删除排班数据

                //todo 暂时未删除周排班
                self::deleteScheduleInfo($docter_id, $sType, $tType, $org_id);
                $count = $countArr[$i];
                //2.创建新时间段
                self::makeTimePeriod($docter_id, $org_id, $sType, $c_r[$tType], $count, $serviceTime);

                //检测时间段
//                $timeCount = TimePeriod::where(['org_id' => $org_id, 'docter_id' => $docter_id])->count();
//                if($timeCount == 0) return apiReturn(603,'请设置时间段');

                $time_periods = TimePeriod::where(['org_id' => $org_id, 'docter_id' => $docter_id, 'type' => $sType])->whereBetween('end_time_period', $times[$tType])->pluck('id')->toArray();
                $schedule = Schedule::where(['docter_id' => $docter_id, 'schedule_type' => $sType])->pluck('schedule_date', 'id')->toArray();
//                $self_schedule = SelfSchedule::where(['docter_id' => 0, 'schedule_type' => $sType,'organization_id'=>$org_id,'type' =>$tType])->distinct('type')
//                    ->orderBy('schedule_date')->where('schedule_date','>',$Today)->get(['schedule_date', 'type', 'week'])->toArray();

                if ($sType == 1) {
                    $week_schedule = WeekSchedule::where(['docter_id' => $docter_id, 'type' => $tType, 'schedule_type' => $sType]);
                } else {
                    $week_schedule = WeekSchedule::where(['organization_id' => $org_id, 'type' => $tType, 'schedule_type' => $sType]);
                }
                $week = $week_schedule->count();

                if ($week != 0) {
                    //3.以周模板添加2个月的数据
                    self::makeSchedule($sType, $docter_id, $org_id, $tType, $schedule, $time_periods);
                    //TODO 删除周排班，插入新周排班
                    self::changeWeekSchedule($docter_id, $org_id, $sType, $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']]
        ];
        $status = $configData['status'];
        $real_status = 2;
        if ($status == false) $real_status = 1;
        $setting = [
            'docter_id' => $docter_id,
            'org_id' => $org_id,
            'type' => $sType,
            'status' => $real_status,
            'show_days' => $configData['showDayNumber'],
            'service_num' => $configData['serviceNum'],
            'service_times' => $configData['timeSpan'],
            'service_time' => json_encode($config)
        ];


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

    //获取用户信息
    public function getScheduleInfo()
    {
        //排班类型 1门诊 2儿保 3计免
        $sType = intval(request('id'));
        if (empty($sType)) {
            return apiReturn(603, '參數错误');
        }
        $user = Admin::user();
        $role = 1;
        $docter_id = 0;
        if ($user->docter_id && $user->org_id) {
            $role = 2;
            if ($sType == 1) $docter_id = $user->docter_id;
        } else if (!$user->docter_id && $user->org_id) {
            $role = 1;
        } else if (!$user->docter_id && !$user->org_id) {
            $role = 0;
        }
        $org_id = intval($user->org_id);

        $list = [];
        if ($role == 1) {
            $ids = DocterOrganization::where(['organization_id' => $org_id])->pluck('docter_id')->toArray();
            $docters = Docter::whereIn('id', $ids)->distinct('id')->get(['id', 'name'])->toArray();
            if (!empty($docters)) {
                //机构默认取第一个医生id
                $docter_id = $docters[0]['id'];
                foreach ($docters as $val) {
                    $list[] = ['value' => $val['id'], 'label' => $val['name']];
                }
            }
            $name = Organization::where('id', $org_id)->value('name');

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

        $data['user_id'] = $docter_id;
        $data['name'] = $name;
        $data['org_id'] = $org_id;
        $data['list'] = $list;
        $data['docter_type'] = $sType;

        $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, $sType, $timeType, $orgId = 0)
    {
        if ($docter_id != 0) {
            SchedulePeriod::where(['docter_id' => $docter_id, 'type' => $timeType, 'me_sure' => 0])->where('organization_id', '=', $orgId)->delete();
        } else {
            SchedulePeriod::where(['organization_id' => $orgId, 'type' => $timeType, 'me_sure' => 0])->where('docter_id', 0)->delete();
        }
        return true;
    }

    //插入时间段
    public static function makeTimePeriod($docterId, $orgId, $sType, $timeConfig, $timerCount, $serviceTime)
    {
        for ($i = 1; $i <= $timerCount; $i++) {
            $timePreiod = [
                'org_id' => $orgId,
                'docter_id' => $docterId,
                'type' => $sType,
                '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),
            ];
            $isHave = TimePeriod::where($timePreiod)->count();
//            dump($timePreiod);
//            dump($isHave);

            if ($isHave == 0) $allData[] = $timePreiod;
        }
//        dump($allData);
        TimePeriod::insert($allData);
        return true;
    }

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

//        if(empty($schedule) || count($schedule) < 58){

        $today = date('j', time());
        $allDay = date('t', time());
        //
        $allData = [];
        $allMesure = [];
        $start = time();


        for ($i = 1; $i < 60; $i++) {
            $todayTimer = $start + (($i - 1) * 86400);
            $date = date('Y-m-d', $todayTimer);
            $week = intval(date('N', strtotime($date)));

            //更新自已定义排班
            $mesure = SchedulePeriod::where(['docter_id' => $docterId, 'organization_id' => $orgId, 'schedule_date' => $date, 'type' => $tType, 'schedule_type' => $sType, 'me_sure' => 1]);
            $mesureIds = $mesure->pluck('id')->toArray();
            $mesure->delete();
            foreach ($timePeriods as $idt) {
                if (!empty($mesureIds)) {
                    $scheduleId = Schedule::where(['docter_id' => $docterId, 'schedule_type' => $sType])->where('schedule_date', $date)->value('id');
                    if ($scheduleId == 0) {
                        $numDate = date('Ymd', $todayTimer);
                        $scheduleData['docter_id'] = $docterId;
                        $scheduleData['schedule_date'] = $date;
                        $scheduleData['schedule_day'] = $numDate;
                        $scheduleData['schedule_type'] = $sType;
                        if ($sType != 1) $scheduleData['organization_id'] = $orgId;
//                        dd($scheduleData);
                        $scheduleId = Schedule::insertGetId($scheduleData);
                    }
                    $s_t = [
                        'me_sure' => 1,
                        'docter_id' => $docterId,
                        'organization_id' => $orgId,
                        'type' => $tType,
                        'schedule_date' => $date,
                        'schedule_type' => $sType,
                        'schedule_id' => $scheduleId,
                        'time_period_id' => $idt
                    ];
                    $allMesure[] = $s_t;
                }
            }


//            echo '医生id '.$docterId.' 机构id '.$orgId.' 周几 '.$week;
            $real_id = WeekSchedule::where(['docter_id' => $docterId, 'organization_id' => $orgId, 'week' => $week, 'type' => $tType, 'schedule_type' => $sType])->first();
            if (!empty($real_id)) {

                foreach ($timePeriods as $idt) {
                    $scheduleId = Schedule::where(['docter_id' => $docterId, 'schedule_type' => $sType])->where('schedule_date', $date)->value('id');
                    if ($scheduleId == 0) {
                        $numDate = date('Ymd', $todayTimer);
                        $scheduleData['docter_id'] = $docterId;
                        $scheduleData['schedule_date'] = $date;
                        $scheduleData['schedule_day'] = $numDate;
                        $scheduleData['schedule_type'] = $sType;
                        if ($sType != 1) $scheduleData['organization_id'] = $orgId;
//                        dd($scheduleData);
                        $scheduleId = Schedule::insertGetId($scheduleData);
                    }
                    $s_t = [
                        'me_sure' => 0,
                        'docter_id' => $docterId,
                        'organization_id' => $orgId,
                        'type' => $tType,
                        'schedule_date' => $date,
                        'schedule_type' => $sType,
                        'schedule_id' => $scheduleId,
                        'time_period_id' => $idt
                    ];


                    $scheduleIsHave = SchedulePeriod::where($s_t)->count();
                    $s_t['order_num'] = 0;
                    if ($scheduleIsHave == 0) $allData [] = $s_t;


                }
            }
        }
        if (!empty($allData)) SchedulePeriod::insert($allData);
        if (!empty($allMesure)) SchedulePeriod::insert($allMesure);


        return true;
    }

    public function setDaySchedule()
    {

        //todo 上线取消默认值
        $schdule_data = request('schedule_data');
        $docter_id = intval(request('docter_id'));
        $sType = intval(request('type'));//排班类型 1门诊 2...
        $org_id = intval(request('org_id'));
        $date = request('date');
        if ($sType != 1) {
            $docter_id = 0;
        }
        //判断排班类型

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

        $self_config = object_array(json_decode($setting['service_time']));

        $times = [
            [$self_config[1]['amStartTime'], $self_config[1]['amEndTime']],
            [$self_config[2]['pmStartTime'], $self_config[2]['pmEndTime']],
            [$self_config[3]['nightStartTime'], $self_config[3]['nightEndTime']],
        ];

//        $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],
//        ];
        $time_t = [];
//        echo '社区id  '.$org_id.' 医生id  '.$docter_id;
        DB::beginTransaction();
        try {
            foreach ($schedule['schedulelingList'] as $t => $v) {


                $today = $schedule['day'];
                $week = intval($schedule['week']);

                if ($v['status'] == true) { //设置
                    $num_date = intval(date('Ymd', strtotime($today)));
                    $sche_data = ['docter_id' => intval($docter_id), 'schedule_type' => $sType, 'schedule_date' => $today, 'schedule_day' => $num_date];
                    //判断是否有排班信息
                    $s_id = Schedule::where($sche_data)->value('id');
                    if (!$s_id) {
                        if ($sType != 1) $scheduleData['organization_id'] = $org_id;
                        $s_id = Schedule::insertGetId($sche_data);
                    }
                    //获取时间段
                    $timeperiods = TimePeriod::where(['docter_id' => intval($docter_id), 'org_id' => intval($org_id), 'type' => $sType])->whereBetween('end_time_period', $times[$t])->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']));
                    }

//                    dump($timeperiods);
                    foreach ($timeperiods as $id) {
                        $data = [
                            'organization_id' => $org_id,
                            'time_period_id' => $id,
                            'me_sure' => 1,
                            'type' => $v['type'],
                            'schedule_date' => $today,
                            'schedule_id' => $s_id,
                            'schedule_type' => $sType,
                            'docter_id' => $docter_id,
                        ];

//                        dump($data);
                        //检查是否已经有数据
//                        $self_count = SelfSchedule::where($data)->count();
//                        if(!$self_count) SelfSchedule::insert($data);

//                        unset($data['week']);
                        $is_schedule_period = SchedulePeriod::where($data)->count();
                        if (!$is_schedule_period) SchedulePeriod::insert($data);

                    }

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


//                    unset($data['week']);
                    //删除详细排班
                    $count_period = SchedulePeriod::where($data)->count();
                    if ($count_period) SchedulePeriod::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;
//
//                    //删除排班日期
                    $s_id = Schedule::where(['schedule_date' => $today, 'schedule_type' => $sType, 'docter_id' => $docter_id])->value('id');
                    unset($data['type']);
//                        $scount = SelfSchedule::where($data)->count();
                    $pcount = SchedulePeriod::where($data)->count();


                    if ($s_id && $pcount == 0) {
                        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)
    {
        if ($type != 1) {
            $docterId = 0;
        }

        $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,
            'docter_id' => $docterId,
            'org_id' => $orgId,
            'status' => $configData['status'],
            'show_days' => $configData['showDayNumber'],
            'service_num' => $configData['serviceNum'],
            'service_times' => $configData['timeSpan'],
        ];

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

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

        return true;
    }

    public static function getSetting($type, $docterId, $orgId)
    {
        if ($type != 1) $docterId = 0;
        //默认为门诊排班医生配置
        $setting = DocterSetting::where(['docter_id' => $docterId, 'org_id' => $orgId, 'type' => $type])->first();
        //获取社区排班设置
        if ($type != 1) $setting = DocterSetting::where(['org_id' => $orgId, 'type' => $type, 'docter_id' => $docterId])->first();
        if (empty($setting)) {
            self::setDefultSetting($type, $docterId, $orgId);
            $setting = 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('type')->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;
    }

    //计算时间段
    public static function getTimeCount($startTime, $endTime, $serviceTime)
    {
        if (empty($startTime) || empty($endTime) || empty($serviceTime)) return 0;
        return intval((strtotime($endTime) - strtotime($startTime)) / ($serviceTime * 60));
    }

}
