package com.fs.company.controller.store;

import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.his.domain.FsPatient;
import com.fs.his.service.IFsPatientService;
import com.fs.his.vo.FsPatientVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 病人Controller
 *
 * @author fs
 * @date 2023-06-07
 */
@RestController
@RequestMapping("/store/patient")
public class FsPatientController extends BaseController
{
    @Autowired
    private IFsPatientService fsPatientService;

    /**
     * 查询病人列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FsPatientVO fsPatient)
    {
        startPage();
        List<FsPatientVO> list = fsPatientService.selectFsPatientListVO(fsPatient);
        for (FsPatientVO fsPatientVO : list) {
            if (fsPatientVO.getPhone()!=null){
                fsPatientVO.setPhone(fsPatientVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            if (fsPatientVO.getIdCard()!=null){
                fsPatientVO.setIdCard(fsPatientVO.getIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2"));
            }
            if (fsPatientVO.getMobile()!=null){
                fsPatientVO.setMobile(fsPatientVO.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }


        }
        return getDataTable(list);
    }

    /**
     * 导出病人列表
     */
    @PreAuthorize("@ss.hasPermi('his:patient:export')")
    @Log(title = "病人", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsPatientVO fsPatient)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        logger.info("tc>\n【导出病人】："+ loginUser.getUser().getUserId());
        if (fsPatientService.isEntityNull(fsPatient)){
            return AjaxResult.error("请筛选数据导出");
        }
        Long count =fsPatientService.selectFsPatientListVOCount(fsPatient);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        List<FsPatientVO> list = fsPatientService.selectFsPatientListVO(fsPatient);

        ExcelUtil<FsPatientVO> util = new ExcelUtil<FsPatientVO>(FsPatientVO.class);
        return util.exportExcel(list, "病人数据");
    }

    /**
     * 获取病人详细信息
     */
    @GetMapping(value = "/{patientId}")
    public AjaxResult getInfo(@PathVariable("patientId") Long patientId)
    {
        FsPatient fsPatient = fsPatientService.selectFsPatientByPatientId(patientId);
        if (fsPatient.getIdCard()!=null){
            fsPatient.setIdCard(fsPatient.getIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1**********$2"));
        }
        if (fsPatient.getMobile()!=null){
            fsPatient.setMobile(fsPatient.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        }
        return AjaxResult.success(fsPatient);
    }
    /**
     * 获取用户信息信息
     */
    @GetMapping(value = "getPatient/{userId}")
    public AjaxResult getPatient(@PathVariable("userId") Long userId)
    {
        List<FsPatientVO> fsPatientVOS = fsPatientService.selectFsPatientByUserId(userId);
        for (FsPatientVO  fsPatientVO: fsPatientVOS) {
            if (fsPatientVO.getPhone()!=null){
                fsPatientVO.setPhone(fsPatientVO.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));

            }

        }
     return AjaxResult.success(fsPatientVOS);
    }
    /**
     * 新增病人
     */
    @PreAuthorize("@ss.hasPermi('his:patient:add')")
    @Log(title = "病人", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsPatient fsPatient)
    {
        String idCardNumber = fsPatient.getIdCard(); // 替换为要验证的身份证号码
        if (idCardNumber == null || idCardNumber.length() != 18) {
            throw new CustomException("身份证号码不合法");
        }
        String regex = "\\d{17}[0-9Xx]";
        if (!Pattern.matches(regex, idCardNumber)) {
            throw new CustomException("身份证号码不合法");
        }
        if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
            throw new CustomException("就诊人名称不合法");
        }
        String birthDateString = idCardNumber.substring(6, 14);
        LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate currentDate = LocalDate.now();
        int age = currentDate.getYear() - birthDate.getYear();
        if (currentDate.getMonthValue() < birthDate.getMonthValue()
                || (currentDate.getMonthValue() == birthDate.getMonthValue()
                && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }
        if (age < 18) {
            throw new CustomException("年龄必须大于18岁");
        }
        if (age > 200) {
            throw new CustomException("年龄超过200岁");
        }
        Date birthday = fsPatient.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String formattedBirthday = sdf.format(birthday);
        LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate currentDate2 = LocalDate.now();
        int age2 = currentDate2.getYear() - da.getYear();
        if (currentDate2.getMonthValue() < da.getMonthValue()
                || (currentDate2.getMonthValue() == da.getMonthValue()
                && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
            age2--;
        }
        if (age2 < 18) {
            throw new CustomException("年龄必须大于18岁");
        }
        if (age2 > 200) {
            throw new CustomException("年龄超过200岁");
        }
        return toAjax(fsPatientService.insertFsPatient(fsPatient));
    }

    /**
     * 修改病人
     */
    @PreAuthorize("@ss.hasPermi('his:patient:edit')")
    @Log(title = "病人", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsPatient fsPatient)
    {

        if (fsPatient.getMobile().contains("*")){
            fsPatient.setMobile(null);
        }
        if (fsPatient.getIdCard().contains("*")){
            fsPatient.setIdCard(null);
        }else {
            String idCardNumber = fsPatient.getIdCard();
            if (idCardNumber == null || idCardNumber.length() != 18) {
                throw new CustomException("身份证号码不合法");
            }
            String regex = "\\d{17}[0-9Xx]";
            if (!Pattern.matches(regex, idCardNumber)) {
                throw new CustomException("身份证号码不合法");
            }
            if (fsPatient.getPatientName().length()<2||fsPatient.getPatientName().length()>30||!fsPatient.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
                throw new CustomException("就诊人名称不合法");
            }
            String birthDateString = idCardNumber.substring(6, 14);
            LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
            LocalDate currentDate = LocalDate.now();
            int age = currentDate.getYear() - birthDate.getYear();
            if (currentDate.getMonthValue() < birthDate.getMonthValue()
                    || (currentDate.getMonthValue() == birthDate.getMonthValue()
                    && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
                age--;
            }
            if (age < 18) {
                throw new CustomException("年龄必须大于18岁");
            }
            if (age > 200) {
                throw new CustomException("年龄超过200岁");
            }

            Date birthday = fsPatient.getBirthday();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String formattedBirthday = sdf.format(birthday);
            LocalDate da = LocalDate.parse(formattedBirthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
            LocalDate currentDate2 = LocalDate.now();
            int age2 = currentDate2.getYear() - da.getYear();
            if (currentDate2.getMonthValue() < da.getMonthValue()
                    || (currentDate2.getMonthValue() == da.getMonthValue()
                    && currentDate2.getDayOfMonth() < da.getDayOfMonth())) {
                age2--;
            }
            if (age2 < 18) {
                throw new CustomException("年龄必须大于18岁");
            }
            if (age2 > 200) {
                throw new CustomException("年龄超过200岁");
            }


        }
        return toAjax(fsPatientService.updateFsPatient(fsPatient));
    }

    /**
     * 删除病人
     */
    @PreAuthorize("@ss.hasPermi('his:patient:remove')")
    @Log(title = "病人", businessType = BusinessType.DELETE)
	@DeleteMapping("/{patientIds}")
    public AjaxResult remove(@PathVariable Long[] patientIds)
    {
        return toAjax(fsPatientService.deleteFsPatientByPatientIds(patientIds));
    }
}
