package com.eitc.patient.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.core.domain.entity.SysUser;
import com.eitc.common.utils.JWTUtil;
import com.eitc.common.utils.StringUtils;
import com.eitc.patient.domain.Patient;
import com.eitc.patient.domain.PatientAppointment;
import com.eitc.patient.enums.PatientAppointmentStatusEnum;
import com.eitc.patient.enums.PatientAppointmentTypeEnum;
import com.eitc.patient.enums.PatientAppointmentVisitTypeEnum;
import com.eitc.patient.service.IPatientAppointmentService;
import com.eitc.patient.service.IPatientService;
import com.eitc.patient.vo.PatientAppointmentParamVO;
import com.eitc.patient.vo.PatientAppointmentVO;
import com.eitc.system.utils.UserCacheUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * PatientAppointmentController
 *
 * @author mtx
 * @date: 2024/05/17 15:52
 */
@Api(tags = "APP预约接口")
@RestController
@RequestMapping("/app/patient-appointment")
public class AppPatientAppointmentController extends BaseController {

    @Resource
    private IPatientAppointmentService patientAppointmentService;
    @Resource
    private IPatientService patientService;

    /**
     * 查询患者预约
     */
    @GetMapping("/list")
    @ApiOperation("查询患者预约")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appointmentPersonId", value = "患者ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "appointmentStatus", value = "预约状态（1预约，2已确定，3已到店，4治疗中，5治疗完成，6已结账，7已离开，8已失约）", dataType = "Integer", dataTypeClass = Integer.class)
    })
    public AjaxResult list(PatientAppointmentParamVO patientAppointmentParamVO) {
        String appointmentPersonId = patientAppointmentParamVO.getAppointmentPersonId();
        if (StringUtils.isEmpty(appointmentPersonId)) {
            return error("患者ID不能为空");
        }
        return success(patientAppointmentService.findList(patientAppointmentParamVO));
    }

    /**
     * 获取患者预约详细信息
     */
    @GetMapping(value = "/detail")
    @ApiOperation("获取患者预约详细信息")
    public AjaxResult detail(String id) {
        PatientAppointment appointment = patientAppointmentService.getById(id);
        return success(patientAppointmentService.getPatientAppointmentDto(appointment));
    }

    /**
     * 新增患者预约
     */
    @PostMapping
    @ApiOperation("新增患者预约")
    public AjaxResult add(@RequestBody PatientAppointmentVO entry) {
        String identificationCard = entry.getIdentificationCard();
        String attendingDoctor = entry.getAttendingDoctor();
        Date appointmentStartTime = entry.getAppointmentStartTime();
        Date appointmentEndTime = entry.getAppointmentEndTime();
        if(StringUtils.isEmpty(identificationCard)){
            return error("身份证号不能为空");
        }
        if(StringUtils.isEmpty(attendingDoctor)){
            return error("主治医生不能为空");
        }
        if(Objects.isNull(appointmentStartTime)){
            return error("预约开始时间不能为空");
        }
        if (Objects.isNull(appointmentEndTime)){
            return error("预约结束时间不能为空");
        }

        // 同一个医生同一时段不能预约
        patientAppointmentService.checkAppointmentTime(attendingDoctor, appointmentStartTime, appointmentEndTime);
        // 获取患者信息
        Patient one = patientService.getOne(Wrappers.<Patient>lambdaQuery().eq(Patient::getIdentificationCard, identificationCard));
        if (Objects.isNull(one)) {
            return error("该患者不存在");
        }
        // 保存预约信息
        long count = patientAppointmentService.count(Wrappers.<PatientAppointment>lambdaQuery().eq(PatientAppointment::getAppointmentPersonId, one.getId()));
        PatientAppointment patientAppointment = new PatientAppointment();
        SysUser user = UserCacheUtil.getSysUserById(attendingDoctor);
        patientAppointment.setAttendingDoctorId(attendingDoctor);
        patientAppointment.setAttendingDoctor(user.getNickName());
        patientAppointment.setOutpatientService(UserCacheUtil.getClinicName());
        patientAppointment.setDepartment(UserCacheUtil.getSysDeptById(user.getDeptId()).getDeptName());
        patientAppointment.setAppointmentType(PatientAppointmentTypeEnum.COMMON.getCode());
        // 有预约过，则复诊
        patientAppointment.setVisitType(count > 0 ?
                PatientAppointmentVisitTypeEnum.REVIEW.getCode() : PatientAppointmentVisitTypeEnum.INITIAL_DIAGNOSIS.getCode());
        patientAppointment.setAppointmentPersonId(one.getId());
        patientAppointment.setAppointmentPerson(one.getPatientName());
        patientAppointment.setAppointmentStartTime(appointmentStartTime);
        patientAppointment.setAppointmentEndTime(appointmentEndTime);
        patientAppointment.setAppointmentStatus(PatientAppointmentStatusEnum.RESERVATION.getCode());
        patientAppointment.setRegisterUser(JWTUtil.getAppPhoneNumber());
        patientAppointment.setRemark(entry.getRemark());
        if (StringUtils.isNotEmpty(entry.getAppointmentId())) {
            patientAppointment.setId(entry.getAppointmentId());
        }
        return toAjax(patientAppointmentService.saveOrUpdate(patientAppointment));
    }


}
