<?php

namespace app\admin\controller\medical;

use app\admin\validate\medical\DoctorValidate;
use app\controller\Curd;
use app\model\MedicalDoctor;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class DoctorController extends Curd
{
    public function __construct()
    {
        $this->model = new MedicalDoctor();
        $this->validate = true;
        $this->validateClass = new DoctorValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/2/29 14:31
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'doctor_addTime';
        $where['doctor_is_del'] = 0;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with(['dept','user']);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    protected function afterQuery($items)
    {
        foreach ($items as &$item) {
            $item['doctor_avatar'] = getenv('STORAGE_DOMAIN') . $item['doctor_avatar'];
        }

        return $items;
    }

    protected function afterInfoQuery($info)
    {
        $info->doctor_avatar = getenv("STORAGE_DOMAIN") . $info->doctor_avatar;
        // 出诊时间
        if ($info->doctor_visit_time) {
            $doctorVisitTimeArr = explode('~', $info->doctor_visit_time);
            foreach ($doctorVisitTimeArr as $key => $item) {
                $doctorVisitTimeArr[$key] = date("Y-m-d\TH:i:s\Z", strtotime(date('Y-m-d ') . $item) - 8 * 3600);
            }
            $info->doctor_visit_time = $doctorVisitTimeArr;
        }
        // 上班时间
        if ($info->doctor_work) {
            $doctorWorkArr = explode('~', $info->doctor_work);
            foreach ($doctorWorkArr as $key => $item) {
                $doctorWorkArr[$key] = date("Y-m-d\TH:i:s\Z", strtotime(date('Y-m-d ') . $item) - 8 * 3600);
            }
            $info->doctor_work = $doctorWorkArr;
        }

        return $info;
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['doctor_avatar'] = str_replace(getenv("STORAGE_DOMAIN"), '', $data['doctor_avatar']);
        // 处理时间
        if ($data['doctor_visit_time']) {
            $doctorVisitTimeStart = date('H:i', strtotime(explode(',', $data['doctor_visit_time'])[0]));
            $doctorVisitTimeEnd = date('H:i', strtotime(explode(',', $data['doctor_visit_time'])[1]));
            $data['doctor_visit_time'] = $doctorVisitTimeStart . '~' . $doctorVisitTimeEnd;
        }
        if ($data['doctor_work']) {
            $doctorWorkStart = date('H:i', strtotime(explode(',', $data['doctor_work'])[0]));
            $doctorWorkEnd = date('H:i', strtotime(explode(',', $data['doctor_work'])[1]));
            $data['doctor_work'] = $doctorWorkStart . '~' . $doctorWorkEnd;
        }
        return $data;
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        // 头像
        $data['doctor_avatar'] = str_replace(getenv("STORAGE_DOMAIN"), '', $data['doctor_avatar']);
        // 处理时间
        if ($data['doctor_visit_time']) {
            $doctorVisitTimeStart = date('H:i', strtotime(explode(',', $data['doctor_visit_time'])[0]));
            $doctorVisitTimeEnd = date('H:i', strtotime(explode(',', $data['doctor_visit_time'])[1]));
            $data['doctor_visit_time'] = $doctorVisitTimeStart . '~' . $doctorVisitTimeEnd;
        }
        if ($data['doctor_work']) {
            $doctorWorkStart = date('H:i', strtotime(explode(',', $data['doctor_work'])[0]));
            $doctorWorkEnd = date('H:i', strtotime(explode(',', $data['doctor_work'])[1]));
            $data['doctor_work'] = $doctorWorkStart . '~' . $doctorWorkEnd;
        }

        return [$id, $data];
    }

    /**
     * @Desc 软删除
     * @Author Gorden
     * @Date 2024/2/29 14:37
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doSoftDelete($ids, ['doctor_is_del' => 1]);

        return json_success('success');
    }

    public function relationUser(Request $request)
    {
        $doctorId = $request->post('doctor_id','');
        $userId = $request->post('join_doctor_user_id','');

        if (!$doctorId || !$userId){
            return json_fail("参数异常");
        }

        try {
            MedicalDoctor::where('doctor_id',$doctorId)->update(['join_doctor_user_id'=>$userId]);
        }catch (\Exception $e){
            return json_fail("关联用户失败");
        }

        return json_success("关联用户成功");
    }
}