package com.fs.app.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.app.param.FsPatientAddEditParam;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.StringUtils;
import com.fs.his.config.StoreConfig;
import com.fs.his.domain.FsPatient;
import com.fs.his.enums.FsUserIntegralLogTypeEnum;
import com.fs.his.param.FsUserAddIntegralTemplateParam;
import com.fs.his.service.IFsPatientService;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.his.utils.IdCardUtil;
import com.fs.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
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;

import static com.fs.his.utils.PhoneUtil.*;


@Api("患者")
@RestController
@RequestMapping(value="/app/patient")
public class PatientController extends  AppBaseController {

    @Autowired
    private IFsPatientService patientService;
    @Autowired
    private IFsUserIntegralLogsService userIntegralLogsService;
    @Autowired
    private ISysConfigService configService;

    @Login
    @ApiOperation("获取病人列表")
    @GetMapping("/getPatientList")
    public R getPatientList(HttpServletRequest request){
        try {
            FsPatient map=new FsPatient();
            map.setUserId(Long.parseLong(getUserId()));
            map.setIsDel(0);
            map.setStatus(1);
            List<FsPatient> list=patientService.selectFsPatientList(map);
            for (FsPatient fsPatient : list) {
                if (fsPatient.getMobile()!=null&&fsPatient.getMobile().length()>11&&!fsPatient.getMobile().matches("\\d+")){
                    fsPatient.setMobile(decryptPhoneMk(fsPatient.getMobile()));
                }
            }
            return R.ok().put("data",list);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }
    @Login
    @ApiOperation("获取病人详情")
    @GetMapping("/getPatientById")
    public R getPatientById(@RequestParam("patientId")Long patientId, HttpServletRequest request){
        FsPatient data=patientService.selectFsPatientByPatientId(patientId);
        if (data.getMobile()!=null&&data.getMobile().length()>11&&!data.getMobile().matches("\\d+")){
            data.setMobile(decryptPhone(data.getMobile()));
        }
        if(!data.getUserId().equals(Long.parseLong(getUserId()))){
            return R.error("非法操作");
        }
        return R.ok().put("data",data);
    }
    @Login
    @RepeatSubmit
    @ApiOperation("添加病人")
    @PostMapping("/addPatient")
    public R addPatient(@Valid @RequestBody FsPatientAddEditParam param, HttpServletRequest request){
        String json = configService.selectConfigByKey("his.store");
        StoreConfig storeConfig = JSONUtil.toBean(json, StoreConfig.class);
        Integer isIdVerification = storeConfig.getIsIdVerification();

        String idCardNumber = param.getIdCard(); // 替换为要验证的身份证号码
        String mobile = param.getMobile();
        if (idCardNumber == null || idCardNumber.trim().isEmpty()) {
            return R.error("身份证号码不合法");
        }
        if (idCardNumber.length() != 18) {
//            //大陆身份证是18位
//            if (isIdVerification != 1) {
//                return R.error("身份证号码不合法");
//            } else {
//                //非大陆身份校验需要手机号 手机号只支持大陆的办理的手机号
//                if (StringUtils.isBlank(mobile)){
//                    R.error("手机号不能为空");
//                }
//            }
            //暂时仅支持大陆身份证
            return  R.error("身份证号码不合法");
        } else {
            String regex = "\\d{17}[0-9Xx]";
            if (!Pattern.matches(regex, idCardNumber)) {
                return   R.error("身份证号码不合法");
            }
        }

        if (param.getPatientName().length()<2||param.getPatientName().length()>30||!param.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
            return   R.error("就诊人名称不合法");
        }

        try {
            if (idCardNumber != null) {
                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) {
                    return R.error("年龄必须大于18岁");
                }
                if (age > 200) {
                    return   R.error("年龄超过200岁");

                }
                Date birthday = param.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) {
                    return   R.error("年龄必须大于18岁");
                }
                if (age2 > 200) {
                    return   R.error("年龄超过200岁");
                }
            }
        }catch (Exception e){
            return   R.error("身份证校验错误");
        }

        //三方校验
        if (isIdVerification!=null&&isIdVerification == 1){
            boolean match = true;
            if (idCardNumber.length() != 18) {
                match = IdCardUtil.isMatchByMobile(storeConfig,param.getPatientName(), mobile);
            } else {
                match = IdCardUtil.isMatchById(storeConfig,param.getPatientName(), param.getIdCard());
            }
            if (!match){
                return R.error("身份证校验错误");
            }
        }

        FsPatient patient=new FsPatient();
        BeanUtil.copyProperties(param, patient);
        patient.setUserId(Long.parseLong(getUserId()));
        patient.setIsDel(0);
        patient.setStatus(1);
        patientService.insertFsPatient(patient);

        // 填写就诊人信息
        FsUserAddIntegralTemplateParam integralTemplateParam = new FsUserAddIntegralTemplateParam();
        integralTemplateParam.setUserId(Long.parseLong(getUserId()));
        integralTemplateParam.setLogType(FsUserIntegralLogTypeEnum.TYPE_11.getValue());
        integralTemplateParam.setBusinessId(patient.getPatientId().toString());
        userIntegralLogsService.addIntegralTemplate(integralTemplateParam);

        return R.ok("操作成功");
    }

    @Login
    @ApiOperation("编辑病人")
    @PostMapping("/editPatient")
    public R editPatient(@Valid @RequestBody FsPatientAddEditParam param, HttpServletRequest request){
        String json = configService.selectConfigByKey("his.store");
        StoreConfig storeConfig = JSONUtil.toBean(json, StoreConfig.class);
        Integer isIdVerification = storeConfig.getIsIdVerification();
        String mobile = param.getMobile();

        String idCardNumber = param.getIdCard(); // 替换为要验证的身份证号码
        if (idCardNumber == null || idCardNumber.trim().isEmpty()) {
            return R.error("身份证号码不合法");
        }
        if (idCardNumber.length() != 18) {
//            //大陆身份证是18位
//            if (isIdVerification != 1) {
//                return R.error("身份证号码不合法");
//            } else {
//                //非大陆身份校验需要手机号 手机号只支持大陆的办理的手机号
//                if (StringUtils.isBlank(mobile)){
//                    R.error("手机号不能为空");
//                }
//            }
            //暂时仅支持大陆身份证
            return  R.error("身份证号码不合法");
        } else {
            String regex = "\\d{17}[0-9Xx]";
            if (!Pattern.matches(regex, idCardNumber)) {
                return   R.error("身份证号码不合法");
            }
        }

        if (param.getPatientName().length()<2||param.getPatientName().length()>30||!param.getPatientName().matches("^[\u4e00-\u9fa5]+$")) {
            return   R.error("就诊人名称不合法");
        }
//        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 = param.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岁");
//        }

        //三方校验
        if (isIdVerification!=null&&isIdVerification == 1){
            boolean match = true;
            if (idCardNumber.length() != 18) {
                match = IdCardUtil.isMatchByMobile(storeConfig,param.getPatientName(), mobile);
            } else {
                match = IdCardUtil.isMatchById(storeConfig,param.getPatientName(), param.getIdCard());
            }
            if (!match){
                return R.error("身份证校验错误");
            }
        }

        FsPatient patient=new FsPatient();
        BeanUtil.copyProperties(param, patient);
        patientService.updateFsPatient(patient);
        return R.ok("操作成功");
    }

    @Login
    @ApiOperation("删除病人")
    @PostMapping("/delPatient")
    public R delPatient(@RequestBody FsPatientAddEditParam param, HttpServletRequest request){
        patientService.deleteFsPatientByPatientId(param.getPatientId());
        return R.ok("操作成功");
    }


}
