<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\Controller;
use App\Services\Admin\YeWu\PlanListService;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Tools;

class PlanListController extends Controller
{
    //生成计划明细
    public function Create(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        $userInfo = DB::table('users')->where(['id' => $userid])->get();
        $department_id = $userInfo[0]->department_id;
        $dateRange = request('dateRange');
        $planModelIds = request('ids');
        $HolidayEnable = request('HolidayEnable');
        $date_type = request('date_type');
        //循环日期和勾选的模板创建明细
        if (count($dateRange) == 2 && count($planModelIds) > 0) {
            $models = DB::table('s_source_roster')->whereIn('id', $planModelIds)->get();
            //检查是否有异常状态模板
            foreach ($models as $model) {
                if ($model->status != 1 || $model->is_del != 0) {
                    return \Yz::echoError1('模板状态异常，请重新选择!异常模板Id:' . $model->id);
                }
            }
            $start_date = new DateTime($dateRange[0]);
            $end_date = new DateTime($dateRange[1]);

            //查询是否有重复插入
            $checkList = DB::table('s_source_roster_detail')
                ->where('department_id', $department_id)
                ->whereIn('roster_id', $planModelIds)
                ->where('date', '>=', $start_date->format('Y-m-d'))
                ->where('date', '<=', $end_date->format('Y-m-d'))
                ->where('is_del', 0)
                ->get();
            $msg = '</br>当前选中的';
            $msglist = '';
            $msgIds = '';
            if (count($checkList) > 0) {
                foreach ($models as $model) {
                    foreach ($checkList as $item) {
                        $msglist .= $item->date . ' ';
                        $msgIds .= $item->id . ' ';
                    }
                    if ($item->roster_id == $model->id) {
                        $msg .= " " . $model->weekname . $model->begin_time . '-' . $model->end_time . " ";

                    }


                }
                return \Yz::Return(false, '已有重复的计划明细，禁止创建！' . $msg . '已存在相同记录,</br>存在于:</br>' . $msglist . '</br>对应记录Id为：' . $msgIds . '</br>请先删除后再操作', $checkList);
            }
            //查询勾选的时间范围内所有的节假日
            $holiday_list=DB::table('s_holiday')->whereBetween('date',$dateRange)->where(['type'=>2])->pluck('date')->toArray();

            // 循环日期并判断星期
            $current_date = clone $start_date;
            DB::beginTransaction();
            $success_count = 0;//成功创建的数量
            while ($current_date <= $end_date) {
                //如果是节假日模板，则判断当前日期是否是节假日，不是则跳过
                if ($date_type == 2) {
                    if (!in_array($current_date->format('Y-m-d'),$holiday_list)){
                        // 将当前日期增加一天
                        $current_date->modify('+1 day');
                        continue;
                    }
                }
                //如果选择节假日不可用，并且当前日期是节假日，则跳过
                if($HolidayEnable==0 and in_array($current_date->format('Y-m-d'),$holiday_list)){
                    // 将当前日期增加一天
                    $current_date->modify('+1 day');
                    continue;
                }

                // 获取当前日期的星期几（0表示星期日，1表示星期一，以此类推）
                $weekday = $current_date->format('w');
                $weekname = '';
                switch ($weekday) {
                    case 0:
                        $weekname = '星期日';
                        break;
                    case 1:
                        $weekname = '星期一';
                        break;
                    case 2:
                        $weekname = '星期二';
                        break;
                    case 3:
                        $weekname = '星期三';
                        break;
                    case 4:
                        $weekname = '星期四';
                        break;
                    case 5:
                        $weekname = '星期五';
                        break;
                    case 6:
                        $weekname = '星期六';
                        break;
                }
                foreach ($models as $model) {
                    if ($date_type == 1 and $model->date_type==1) {
                        if ($model->weekname <> $weekname) continue;
                    }

                    // 插入明细表
                    $data = [
                        'roster_id' => $model->id,
                        'date' => $current_date,
                        'weekname' => $weekname,
                        'department_id' => $model->department_id,
                        'resources_id' => $model->resources_id,
                        'device_id' => $model->device_id,
                        'period_id' => $model->period_id,
                        'patient_type' => $model->patient_type,
                        'begin_time' => $model->begin_time,
                        'end_time' => $model->end_time,
                        'end_reservation_time' => $model->end_reservation_time,
                        'time_unit' => $model->time_unit,
                        'status' => 1,
                        'adduser' => $userid,
                        'is_del' => 0,
                    ];


                    $plan_id = DB::table('s_source_roster_detail')->insertGetId($data);
                    if ($plan_id) {
                        $success_count++;
                    }
                    // 插入数量表
                    $model_count_info = DB::table('s_source_roster_count')->where(['roster_id' => $model->id])->get();
                    if (count($model_count_info) > 0) {
                        foreach ($model_count_info as $info) {
                            $i_c = DB::table('s_source_roster_detail_count')->insert([
                                'roster_detail_id' => $plan_id,
                                'appointment_type_id' => $info->appointment_type_id,
                                'count' => $info->count,
                                'max_total' => $info->max_total,
                            ]);
                            if (!$i_c) {
                                DB::rollBack();
                                return \Yz::echoError1('渠道数量创建失败');
                            }
                        }
                    } else {
                        DB::rollBack();
                        return \Yz::echoError1('模板数量信息异常，请重新选择!异常模板Id:' . $model->id);
                    }
                    if (isset($model->device_id)) {
                        $device_ids = explode(",", $model->device_id);
                        foreach ($device_ids as $dv_key => $dv_value) {
                            $i_dev = DB::table('s_source_roster_detail_device')->insert([
                                'roster_detail_id' => $plan_id,
                                'device_id' => $dv_value,
                            ]);
                            if (!$i_dev) {
                                DB::rollBack();
                                return \Yz::echoError1('设备关联创建失败');
                            }
                        }

                    } else {
                        DB::rollBack();
                        return \Yz::echoError1('模板未关联设备，请重新选择!异常模板Id:' . $model->id);
                    }


                }
                // 将当前日期增加一天
                $current_date->modify('+1 day');

            }
            DB::commit();
            return \Yz::Return(true, '执行完成，范围：' . $dateRange[0] . '-' . $dateRange[1] . '，共计生成计划 ' . $success_count . ' 条', ['dateRange' => $dateRange, 'success_count' => $success_count]);
        }
    }

    public function GetList(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo = request('searchInfo');
        $page = request('page');
        $pageSize = request('pageSize');
        $department_id = 0;
        $department_info=false;
        $list = DB::table('s_source_roster_detail')
            ->leftJoin('s_department_resources', 's_source_roster_detail.resources_id', '=', 's_department_resources.id')
            //  ->leftJoin('s_devices', 's_source_roster_detail.device_id', '=', 's_devices.id')
            ->leftJoin('s_period', 's_source_roster_detail.period_id', '=', 's_period.id')
            ->select('s_source_roster_detail.*', 's_department_resources.department_resources_name', 's_period.period_name')
            ->where(['s_source_roster_detail.is_del' => 0]);
        if (!empty($searchInfo['department_id'])) {//以前判断的是管理员group==1 改为 (任何角色都能查看了)
            if (!empty($searchInfo['department_id'])) {
                $department_info=DB::table('s_department')->where(['id' => $searchInfo['department_id']])->first();
                $list = $list->where('s_source_roster_detail.department_id', $searchInfo['department_id']);
            }

        } else {
            $userInfo = DB::table('users')->where(['id' => $userid])->get();
            $department_id = $userInfo[0]->department_id;
            $department_info=DB::table('s_department')->where(['id' => $department_id])->first();
            $list = $list->where(['s_source_roster_detail.department_id' => $department_id]);
        }
        if (!empty($searchInfo['resources_id'])) {
            $list = $list->where('s_source_roster_detail.resources_id', $searchInfo['resources_id']);
        }
        if (!empty($searchInfo['device_id'])) {
            //$list = $list->where('s_source_roster_detail.device_id', 'like','%,'.$searchInfo['device_id'].',%'  );
            $list = $list->whereRaw("FIND_IN_SET({$searchInfo['device_id']}, s_source_roster_detail.device_id)");
        }
        if (!empty($searchInfo['xingqi'])) {
            $list = $list->where('s_source_roster_detail.weekname', $searchInfo['xingqi']);
        }
        if (isset($searchInfo['status'])) {
            $list = $list->where('s_source_roster_detail.status', $searchInfo['status']);
        }
        if (count($searchInfo['dateRange']) == 2) {
            $list = $list->whereBetween('s_source_roster_detail.date', $searchInfo['dateRange']);
        }

        $count = $list;
        $count = $count->count();
        $list = $list->orderBy('id', 'desc')->limit($pageSize)->skip(($page - 1) * $pageSize) // 跳过前9999条记录
        ->take($pageSize)->get();
        $ids = [];
        foreach ($list as $key => $value) {
            $list[$key]->department_name = !!$department_info?$department_info->department_name:'' ;
            $list[$key]->countsInfo = [];
            $ids[] = $value->id;
        }
        //匹配渠道数量
        $countsInfo = DB::table('s_source_roster_detail_count')
            ->leftJoin('s_appointment_type', 's_source_roster_detail_count.appointment_type_id', '=', 's_appointment_type.id')
            ->select('s_source_roster_detail_count.*', 's_appointment_type.name')
            ->whereIn('roster_detail_id', $ids)->get();

        if (count($countsInfo) > 0) {
            foreach ($list as $key => $value) {
                foreach ($countsInfo as $k => $v) {
                    if ($value->id == $v->roster_detail_id) {
                        $list[$key]->countsInfo[] = $v;
                    }
                }
            }
        }
        //匹配设备（服务组）
        $devices = DB::table('s_devices')->get();
        foreach ($list as $key => $value) {
            $list[$key]->devices = [];
            $array_device_id = explode(",", $value->device_id);
            foreach ($devices as $k => $v) {
                if (in_array($v->id, $array_device_id)) {
                    $list[$key]->devices[] = $v;
                }
            }
        }

        return \Yz::Return(true, '获取成功', ['list' => $list, 'count' => $count]);
    }

    public function GetDetail()
    {
        $id = request('id');
        $info = DB::table('s_source_roster_detail')->where(['id' => $id, 'is_del' => 0])->first();
        $info->patientType = explode(',', $info->patient_type);
        $info->department_name = DB::table('s_department')->where('id', $info->department_id)->first()->department_name;
        $info->resources_name = DB::table('s_department_resources')->where('id', $info->resources_id)->first()->department_resources_name;
        $info->devices = DB::table('s_devices')->whereIn('id', explode(',', $info->device_id))->get();
        $info->coutsInfo = DB::table('s_source_roster_detail_count')
            ->leftJoin('s_appointment_type', 's_source_roster_detail_count.appointment_type_id', '=', 's_appointment_type.id')
            ->leftJoin('s_appointment_type_ratio', 's_appointment_type.id', '=', 's_appointment_type_ratio.appointment_type_id')
            ->select('s_source_roster_detail_count.*', 's_appointment_type.name', 's_appointment_type_ratio.ratio')
            ->where(['s_source_roster_detail_count.roster_detail_id' => $id, 's_appointment_type_ratio.department_id' => $info->department_id])->get();
        $info->max_total = 0;
        if (count($info->coutsInfo) > 0) {
            $info->max_total = $info->coutsInfo[0]->max_total;
        }
        return \Yz::Return(true, '获取成功', $info);
    }

    public function ChangeInfo(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $PlanDetaiInfo = request('PlanDetaiInfo');
        $userInfo = DB::table('users')->where(['id' => $userid])->get();
        $department_id = $userInfo[0]->department_id;
        $check = DB::table('s_source_roster_detail')->where(['id' => $PlanDetaiInfo['id']])
            ->where('department_id', $department_id)
            ->where('is_del', 0)
            ->first();
        if (!$check) return \Yz::echoError1('没有权限');
        $u1 = DB::table('s_source_roster_detail')->where(['id' => $PlanDetaiInfo['id']])->update([
            'status' => $PlanDetaiInfo['status']
        ]);
        $i = 0;
        foreach ($PlanDetaiInfo['coutsInfo'] as $key => $value) {
            $u2 = DB::table('s_source_roster_detail_count')->where(['id' => $value['id']])->update([
                'count' => $value['count'],
                'max_total' => $value['max_total'],
            ]);
            if ($u2) $i++;
        }
        if ($u1 or $i > 0) {
            return \Yz::Return(true, '保存成功', []);
        } else {
            return \Yz::echoError1('没有数据更新');
        }
    }

    public function Del(Request $request)
    {
        $userid = $request->get('userid');//中间件产生的参数
        $userInfo = DB::table('users')->where(['id' => $userid])->get();
        $department_id = $userInfo[0]->department_id;
        $ids = request('ids');
        $u1 = DB::table('s_source_roster_detail')->where(['department_id' => $department_id])->whereIn('id', $ids)->update([
            'is_del' => 1
        ]);
        if ($u1) {
            return \Yz::Return(true, '删除成功', []);
        } else {
            return \Yz::echoError1('删除失败');
        }
    }

    //获取可用的计划，用于计划占用
    public function GetEnablePlan()
    {
        $regnum = request('regnum');
        $entrustid = request('entrustid');
        $episodeid = request('episodeid');
        $appointment_type = request('appointment_type'); //预约类型
        $appointment_date = request('date'); //预约日期
        $service = new PlanListService();
        return $service->GetEnablePlan($regnum, $entrustid, $episodeid, $appointment_type, $appointment_date);
    }

    //获取最近可用的，计划 日期
    public function NearestEnablePlanDate()
    {
        $dateRange=config('app.globals.可用号源查询范围');
        $regnum = request('regnum');
        $entrustids = request('entrustid');
        $episodeid = request('episodeid');
        $appointment_type = request('appointment_type'); //预约类型
        $appointment_date = request('date'); //预约日期
        $service = new PlanListService();

        $date_arr = [];


        $startDate = new DateTime();
        // 设定结束日期为当前日期加7天
        $endDate = new DateTime();
        $endDate->modify('+' . $dateRange . ' day');
        // 循环遍历每一天
        $currentDate = $startDate;
        while ($currentDate <= $endDate) {
            $nowdate = $currentDate->format('Y-m-d');
            $s = $service->GetEnablePlan($regnum, $entrustids, $episodeid, $appointment_type, $nowdate);
            if ($s['status']) {
                $list = $s['data']['plan_list'];
                if (count($list) > 0) {
                    $date_arr[] = $s['data']['appointment_date'];
                }
            }
            if (count($date_arr) >= 2) {
                break;
            }
            // 每次循环增加一天
            $currentDate->modify('+1 day');
        }
        return \Yz::Return(true, '查询完成', ['list' => $date_arr]);


    }

    //开始预约占用名额
    public function YuYue()
    {
        date_default_timezone_set('PRC');
        $nowdatetime = date("Y-m-d H:i:s");
        $planid = request('planid');
        $appointment_type = request('appointment_type');//渠道id
        $mainlistid = request('mainlistid');//主表id
        $do_type = request('dotype');//操作类型,1预约，2改约
        if (!isset($do_type)) return \Yz::echoError1('参数：操作类型 不能为空');

        $service = new PlanListService();
        return $service->YuYue($planid, $appointment_type, $mainlistid, $do_type);
    }
    //自动预约
    public function AutoYuYue()
    {
        $dateRange=config('app.globals.可用号源查询范围');
        $regnum = request('regnum');
        $entrustids = request('entrustid');
        $episodeid = request('episodeid');
        $appointment_type = request('appointment_type'); //预约类型
        $TodayDateTime = date("Y-m-d H:i:s");
        $service = new PlanListService();

        $startDate = new DateTime();
        // 设定结束日期为当前日期加7天
        $endDate = new DateTime();
        $endDate->modify('+' . $dateRange . ' day');
        // 循环遍历每一天
        $currentDate = $startDate;
        $enable_plan=false;
        while ($currentDate <= $endDate) {
            $nowdate = $currentDate->format('Y-m-d');
            $s = $service->GetEnablePlan($regnum, $entrustids, $episodeid, $appointment_type, $nowdate);
            if ($s['status']) {
                $list = $s['data']['plan_list'];
                if (count($list) > 0) {
                   foreach ($list as $k => $v) {
                       if($v->count-$v->used_count>0 and $TodayDateTime< $v->date.' '.$v->end_reservation_time){
                           $enable_plan=$v;
                           break;
                       }
                   }
                   if(!!$enable_plan){
                       break;
                   }
                }
            }

            // 每次循环增加一天
            $currentDate->modify('+1 day');
        }
        if(!!$enable_plan){
            $mainlistids=DB::table('s_list')->whereIn('entrust_id',$entrustids)->pluck('id')->toArray();
            $service = new PlanListService();
            return $service->YuYue($enable_plan->id, $appointment_type, $mainlistids, 1);
        }else{
            return \Yz::echoError1('最近'.$dateRange.'日无可用号源');
        }
    }

    public function CancelYuYue(Request $request)
    {
        $MainListId = request('MainListId');
        $reg_num = request('reg_num');
        $password = request('password');
        $userid = $request->get('userid');//中间件产生的参数
        $query = DB::table('users')->where(['id' => $userid])->get();
        if (password_verify($password, $query[0]->pwd)) {
            $service = new PlanListService();
            return $service->CancelYuYue($MainListId, $reg_num);
        } else {
            return \Yz::echoError1('密码不正确');
        }
    }

    //查询已预约明细
    public function GetUsedList()
    {
        $planid = request('planid');
        $qudaoid = request('qudaoid');
        $list = DB::table('s_list')
            ->leftJoin('s_department_resources', 's_list.reservation_sources', '=', 's_department_resources.id')
            ->select('s_list.*', 's_department_resources.department_resources_name')
            ->where(['s_list.roster_id' => $planid, 's_list.is_del' => 0, 's_list.is_nullify' => 0])->whereIn('s_list.list_status', [1, 2, 3]);
        if (!empty($qudaoid)) {
            $list = $list->where(['s_list.appointment_type_id' => $qudaoid]);
        }
        $list = $list->get();
        $qudao = DB::table('s_appointment_type')->get();
        foreach ($list as $key => $item) {
            foreach ($qudao as $q) {
                if ($q->id == $item->appointment_type_id) {
                    $item->qudao_name = $q->name;
                }
            }

        }
        return \Yz::Return(true, '查询完成', $list);
    }
}
