<?php
namespace app\admin\server\medical;

use app\admin\model\MedicalCareDoctor;
use app\admin\model\MedicalCareDoctorAppointment;
use app\admin\model\Package;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemMenu;
use app\admin\model\SystemRole;
use http\Exception;

class DoctorServer
{
    /**
     * Notes:获取医生列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: QJF
     * Date: 2022/9/17
     */
    public static function getDoctorList( $page, int $limit, $keywords)
    {
        [$list, $count] =  MedicalCareDoctor::getDoctorList($page, $limit, $keywords);
        if(!empty($list))
        {
            foreach ($list as $k => $item)
            {
                $list[$k]['doctor_create_time'] = date("Y-m-d H:i:s", $item['doctor_create_time']);
            }
        }
        return compact('list', 'page', 'limit', 'count');
    }

    /**
     * Notes:添加医生
     * @param array $param
     * @param int $admin_id
     * @return int
     * @throws \Exception
     * User: yym
     * Date: 2022/9/26
     */
    public static function insertDoctor(array $param, int $admin_id)
    {
        MedicalCareDoctor::affairBegin();
        try {
            //检测同一医生是否存在
            if(MedicalCareDoctor::checkDoctorName($param['doctor_name'], $param['doctor_mobile']))
            {
                throw new \Exception($param['doctor_name'] . '医生已存在');
            }
            $param['doctor_create_time'] = time();
            $result =  MedicalCareDoctor::insertGetId($param);
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加医生: ' . $param['doctor_name'] . $result;
                plog('medical-doctor-create', '医疗-医生-创建医生', $msg);
                MedicalCareDoctor::affairCommit();
                return $result;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            MedicalCareDoctor::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }
    /**
     * Notes:修改角色
     * @param array $param
     * @param int $admin_id
     * @return int
     * User: QJF
     * Date: 2022/9/19
     */
    public static function updateDoctor(array $param, int $admin_id)
    {
        MedicalCareDoctor::affairBegin();
        try {
            $info = MedicalCareDoctor::getDoctorInfo($param['doctor_id']);
            if(empty($info) || $info === false)
            {
                throw new \Exception('医生信息不存在');
            }
            if(MedicalCareDoctor::checkDoctorCount($param['doctor_name'], $param['doctor_mobile'], $param['doctor_id']))
            {
                throw new \Exception($param['doctor_name'] . '医生已存在');
            }
            $where = [];
            $where['doctor_id'] = $param['doctor_id'];
            $result = MedicalCareDoctor::where($where)->update($param);
            if ($result !== false){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '编辑医生-编号: ' . $param['doctor_id'];
                plog('medical-doctor-update', '医疗-医生-编辑医生', $msg);
                MedicalCareDoctor::affairCommit();
                return true;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            MedicalCareDoctor::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:删除医生
     * @param int $doctor_id
     * @param int $admin_id
     * @return bool
     * @throws \Exception
     * User: yym
     * Date: 2022/9/26
     */
    public static function deleteDoctor(int $doctor_id, int $admin_id)
    {
        MedicalCareDoctor::affairBegin();
        try {
            $info = MedicalCareDoctor::getDoctorInfo($doctor_id);
            if(empty($info) || $info === false)
            {
                throw new \Exception('医生信息不存在');
            }
            $result = MedicalCareDoctor::updateDoctor($doctor_id, ['doctor_del' => MedicalCareDoctor::DEL_YES]);
            if ($result === false){
                throw new \Exception('删除失败');
            }
            $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '删除医生-编号: ' . $doctor_id;
            plog('medical-doctor-delete', '医疗-医生-删除医生', $msg);
            MedicalCareDoctor::affairCommit();
            return true;
        }catch (\Exception $exception){
            MedicalCareDoctor::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取医生详情
     * @param int $doctor_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws \Exception
     * User: yym
     * Date: 2022/9/26
     */
    public static function getDoctorInfo(int $doctor_id)
    {
        try {
            $info = MedicalCareDoctor::getDoctorInfo($doctor_id);
            if(empty($info) || $info === false)
            {
                throw new \Exception('医生信息不存在');
            }
            $info['doctor_create_time'] = date("Y-m-d H:i:s", $info['doctor_create_time']);
            return $info;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:医生每日工作接纳人数设置----目前按照每半小时时间段设置
     * @param int $doctor_id
     * @param int $admin_id
     * @param string $work_time
     * @param string $morning_start
     * @param string $morning_end
     * @param string $afternoon_start
     * @param string $afternoon_end
     * @param int $appointment_sum
     * @return bool
     * @throws \Exception
     * User: yym
     * Date: 2022/9/27
     */
    public static function setAppointment(int $doctor_id, int $admin_id, string $work_time, string $morning_start, string $morning_end, string $afternoon_start, string $afternoon_end, int $appointment_sum)
    {
        MedicalCareDoctorAppointment::affairBegin();
        try {
            if(!empty($morning_start) && !empty($morning_end))
            {
                if(strtotime(date("Y-m-d", time()) . $morning_start) > strtotime(date("Y-m-d", time()) . $morning_end))
                {
                    throw new \Exception('上午开始时间不能大于上午结束时间');
                }
            }
            if(!empty($afternoon_start) && !empty($afternoon_end))
            {
                if(strtotime(date("Y-m-d", time()) . $afternoon_start) > strtotime(date("Y-m-d", time()) . $afternoon_end))
                {
                    throw new \Exception('下午开始时间不能大于下午结束时间');
                }
            }

            if(!empty($morning_end) && !empty($afternoon_start))
            {
                if(strtotime(date("Y-m-d", time()) . $morning_end) > strtotime(date("Y-m-d", time()) . $afternoon_start))
                {
                    throw new \Exception('上午结束时间不能大于下午开始时间');
                }
            }

            if(!in_array($work_time, MedicalCareDoctorAppointment::WORK_TIME_ARR))
            {
                throw new \Exception('设置日期错误');
            }
            //上午时间处理
            $morning_time_data = array();
            if(!empty($morning_start) && !empty($morning_end))
            {
                $morning_time_data = timeDifference($morning_start, $morning_end);
                if(empty($morning_time_data))
                {
                    throw new \Exception('上午设置时间存在问题');
                }
                foreach ($morning_time_data as $k => $row)
                {
                    $morning_time_data[$k] = $appointment_sum;
                }
            }

            //下午时间处理
            $afternoon_time_data = array();
            if(!empty($afternoon_start) && !empty($afternoon_end))
            {
                $afternoon_time_data = timeDifference($afternoon_start, $afternoon_end);
                if(empty($afternoon_time_data))
                {
                    throw new \Exception('下午设置时间存在问题');
                }
                foreach ($afternoon_time_data as $k => $row)
                {
                    $afternoon_time_data[$k] = $appointment_sum;
                }
            }

            $content = array(
                'morning_time_data' => $morning_time_data,
                'afternoon_time_data' => $afternoon_time_data
            );
            $log_msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time());
            //检测医生是否已经设置
            if(MedicalCareDoctorAppointment::getDoctorAppointment($doctor_id))
            {
                $log_type = 'doctor-appointment-update';
                $log_name = '医生-工作设置-修改';
                $log_msg .= '修改医生：' . $doctor_id . '工作信息周' . $work_time;
                $update = array(
                    MedicalCareDoctorAppointment::WORK_TIME[$work_time] => json_encode($content),
                    'appointment_update_time' => time()
                );
                $result = MedicalCareDoctorAppointment::updateData($doctor_id, $update);
            }else{
                $log_type = 'doctor-appointment-insert';
                $log_name = '医生-工作设置-新增';
                $log_msg .= '新增医生：' . $doctor_id . '工作信息周' . $work_time;
                $insert = array(
                    'appointment_doctor_id' => $doctor_id,
                    MedicalCareDoctorAppointment::WORK_TIME[$work_time] => json_encode($content),
                    'appointment_create_time' => time()
                );
                $result = MedicalCareDoctorAppointment::insertData($insert);
            }
            if($result !== false)
            {
                plog($log_type, $log_name, $log_msg);
                MedicalCareDoctorAppointment::affairCommit();
                return true;
            }
            throw new \Exception('操作失败');
        }catch (\Exception $exception){
            MedicalCareDoctorAppointment::affairRollback();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }

    /**
     * Notes:获取设置详情
     * @param int $doctor_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * User: yym
     * Date: 2022/10/13
     */
    public static function getAppointment(int $doctor_id)
    {
        $info = MedicalCareDoctorAppointment::getDoctorAppointment($doctor_id);
        if(!empty($info))
        {
            $info = $info->toArray();
            $info['appointment_monday']    = appointment_data($info, 'appointment_monday');
            $info['appointment_tuesday']   = appointment_data($info, 'appointment_tuesday');
            $info['appointment_wednesday'] = appointment_data($info, 'appointment_wednesday');
            $info['appointment_thursday']  = appointment_data($info, 'appointment_thursday');
            $info['appointment_friday']    = appointment_data($info, 'appointment_friday');
            $info['appointment_saturday']  = appointment_data($info, 'appointment_saturday');
            $info['appointment_sunday']    = appointment_data($info, 'appointment_sunday');
        }
        return $info;
    }
}
