package cn.hnthyy.thmz.controller.zy;

import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.entity.his.zy.APatientMi;
import cn.hnthyy.thmz.entity.his.zy.ZyActpatient;
import cn.hnthyy.thmz.entity.his.zy.ZyLedgerFile;
import cn.hnthyy.thmz.entity.his.zy.ZyReceipt;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.enums.GenderEnum;
import cn.hnthyy.thmz.enums.ResponceTypeEnum;
import cn.hnthyy.thmz.enums.YesNoEnum;
import cn.hnthyy.thmz.service.his.zd.ZdUnitCodeService;
import cn.hnthyy.thmz.service.his.zy.ZyActpatientService;
import cn.hnthyy.thmz.service.his.zy.ZyLedgerFileService;
import cn.hnthyy.thmz.service.his.zy.ZyReceiptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class ZyActpatientController {
    @Autowired
    private ZyActpatientService zyActpatientService;
    @Autowired
    private ZdUnitCodeService zdUnitCodeService;
    @Autowired
    private ZyLedgerFileService zyLedgerFileService;
    @Autowired
    private ZyReceiptService zyReceiptService;
    /**
     * 保存入院信息
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/saveZyActpatient", method = {RequestMethod.POST})
    public Map<String, Object> saveZyActpatient(@RequestBody ZyActpatient zyActpatient , HttpServletRequest httpServletRequest) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (checkZyActpatient(zyActpatient, resultMap)){
                return resultMap;
            }
            User tokenUser = TokenUtil.getUser(httpServletRequest);
            zyActpatient.setOpIdCode(tokenUser.getUserIdCode());
            int num=zyActpatientService.saveZyActpatientFull(zyActpatient);
            if(num==1){
                resultMap.put("code", 0);
                resultMap.put("message", "保存入院信息成功");
                return resultMap;
            }
            resultMap.put("code", -1);
            resultMap.put("message", "保存入院信息失败");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", StringUtils.isBlank(e.getMessage())?"系统出错，请联系管理员":e.getMessage());
            log.error("系统异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }



    /**
     * 校验入院信息
     * @param zyActpatient
     * @param resultMap
     * @return
     */
    private boolean checkZyActpatient(@RequestBody ZyActpatient zyActpatient, Map<String, Object> resultMap) {
        if (zyActpatient == null) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院信息不能为空");
            return true;
        }
        if (zyActpatient.getAdmissDate()==null) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院日期不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getAdmissPhysician())) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院医生不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getClinicDiagStr())) {
            resultMap.put("code", -1);
            resultMap.put("message", "门诊诊断不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getAdmissDiagStr())) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院诊断不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getAdmissDept())) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院科室不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getAdmissWard())) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院病房不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getSmallDept())) {
            resultMap.put("code", -1);
            resultMap.put("message", "小病室不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getBedNo())) {
            resultMap.put("code", -1);
            resultMap.put("message", "床号不能为空");
            return true;
        }
        if (StringUtils.isBlank(zyActpatient.getAdmissStatus())) {
            resultMap.put("code", -1);
            resultMap.put("message", "入院状态不能为空");
            return true;
        }
        return false;
    }




    /**
     * 根据住院号查询在院记录数
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getCountByInpatientNo", method = {RequestMethod.GET})
    public Map<String, Object> getCountByInpatientNo(@RequestParam("inpatientNo") String inpatientNo) {
        log.info("根据住院号查询在院记录数");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(inpatientNo)) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院号不能为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "根据住院号查询在院记录数成功");
            resultMap.put("data", zyActpatientService.queryCountByInpatientNo(inpatientNo));
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "根据住院号查询在院记录数出错，请联系管理员");
            log.error("根据住院号查询在院记录数异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }





    /**
     * 修改住院号
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/modifyInpatientNo", method = {RequestMethod.POST})
    public Map<String, Object> modifyInpatientNo(@RequestBody APatientMi aPatientMi) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (aPatientMi==null) {
                resultMap.put("code", -1);
                resultMap.put("message", "参数不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(aPatientMi.getInpatientNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "新住院号不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(aPatientMi.getOldInpatientNo())) {
                resultMap.put("code", -1);
                resultMap.put("message", "旧住院号不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(aPatientMi.getName())) {
                resultMap.put("code", -1);
                resultMap.put("message", "姓名不能为空");
                return resultMap;
            }
            int num=zyActpatientService.modifyInpatientNo(aPatientMi);
            if(num==1){
                resultMap.put("code", 0);
                resultMap.put("message", "修改住院号成功");
                return resultMap;
            }
            resultMap.put("code", -1);
            resultMap.put("message", "修改住院号失败");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", StringUtils.isBlank(e.getMessage())?"系统出错，请联系管理员":e.getMessage());
            log.error("系统异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }




    /**
     * 根据病人门诊id或者住院号查询病人信息
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getZyActpatientByInpatientNoOrMzNO", method = {RequestMethod.POST})
    public Map<String, Object> getZyActpatientByInpatientNoOrMzNO(@RequestBody ZyActpatient zyActpatient) {
        log.info("根据病人门诊id或者住院号查询病人信息");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if(zyActpatient==null){
                resultMap.put("code", -1);
                resultMap.put("message", "查询参数不能为空");
                return resultMap;
            }
            if(StringUtils.isBlank(zyActpatient.getTableName())){
                resultMap.put("code", -1);
                resultMap.put("message", "病人在院类型不能为空");
                return resultMap;
            }
            if(zyActpatient.getPageIndex()==null){
                zyActpatient.setPageIndex(0);
            }
            if (StringUtils.isBlank(zyActpatient.getInpatientNo())) {
                zyActpatient.setInpatientNo(null);
            }else {
                zyActpatient.setInpatientNo("%"+zyActpatient.getInpatientNo()+"%");
            }
            if (StringUtils.isBlank(zyActpatient.getMzNo())) {
                zyActpatient.setMzNo(null);
            }else {
                zyActpatient.setMzNo("%"+zyActpatient.getMzNo()+"%");
            }
            if (StringUtils.isBlank(zyActpatient.getName())) {
                zyActpatient.setName(null);
            }else {
                zyActpatient.setName("%"+zyActpatient.getName()+"%");
            }
            if(StringUtils.isBlank(zyActpatient.getWard())){
                zyActpatient.setWard(null);
            }
            if(StringUtils.isBlank(zyActpatient.getZkDept())){
                zyActpatient.setZkDept(null);
            }
            if(StringUtils.isBlank(zyActpatient.getBeginTime())){
                zyActpatient.setBeginTime(null);
            }
            if(StringUtils.isBlank(zyActpatient.getEndTime())){
                zyActpatient.setEndTime(null);
            }
            resultMap.put("code", 0);
            resultMap.put("message", "根据病人门诊id或者住院号查询病人信息成功");
            List<ZyActpatient> list=zyActpatientService.queryZyActpatientByInpatientNoOrMzNO(zyActpatient);
            list.stream().forEach(z->{
                if(StringUtils.isNotBlank(z.getWard())){
                    z.setWardName(zdUnitCodeService.queryDeptNameByIdInCache(z.getWard()));
                }
                if(StringUtils.isNotBlank(z.getZkDept())){
                    z.setZkDeptName(zdUnitCodeService.queryDeptNameByIdInCache(z.getZkDept()));
                }
                ZyLedgerFile zyLedgerFile=zyLedgerFileService.queryLastLedgerSn(z.getInpatientNo(),z.getAdmissTimes());
                if(zyLedgerFile!=null){
                    if(StringUtils.isBlank(zyLedgerFile.getSettleType())){
                        //TODO 在院病人是否有出院医嘱
                        //未结算
                        z.setSettleType("0");
                    }else {
                        z.setSettleType(zyLedgerFile.getSettleType());
                    }
                }
                ResponceTypeEnum responceTypeEnum=ResponceTypeEnum.getReportTypeByCode(z.getResponceType());
                z.setResponceType(responceTypeEnum==null?"":responceTypeEnum.name);
                if(ZyActpatient.ZY_INACTPATIENT.equals(zyActpatient.getTableName())){
                    List<ZyReceipt> zyReceipts=zyReceiptService.queryAllValidReceipt(z.getInpatientNo(),z.getAdmissTimes());
                    Integer printFlag=null;
                    if(zyReceipts!=null && zyReceipts.size()>0){
                        for (ZyReceipt zyReceipt:zyReceipts){
                            if(zyReceipt==null){
                                continue;
                            }
                            //没有打印发票
                            if(StringUtils.isBlank(zyReceipt.getReceiptNo()) || ZyReceipt.DEFAULT_RECEIPT_NO.equals(zyReceipt.getReceiptNo().trim())){
                                printFlag=YesNoEnum.NO.code;
                            }else if (printFlag==null){
                                //当只要还有一个未打印的发票，都不能将打印标记改为已打印
                                printFlag=YesNoEnum.YES.code;
                            }
                        }
                    }
                    z.setPrintFlag(printFlag);
                }
            });
            resultMap.put("data", list);
            resultMap.put("total", zyActpatientService.queryCountByInpatientNoOrMzNO(zyActpatient));
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "根据病人门诊id或者住院号查询病人信息出错，请联系管理员");
            log.error("根据病人门诊id或者住院号查询病人信息异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }




    /**
     * 根据住院号查询在/出院记录
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/getByInpatientNo", method = {RequestMethod.GET})
    public Map<String, Object> getByInpatientNo(@RequestParam("inpatientNo") String inpatientNo,@RequestParam("admissTimes") Integer admissTimes,@RequestParam("tableName") String tableName) {
        log.info("根据住院号查询在院记录");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(inpatientNo)) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院号不能为空");
                return resultMap;
            }
            if (admissTimes==null) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院次数不能为空");
                return resultMap;
            }
            if (StringUtils.isBlank(tableName)) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人在院状态不能为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "根据住院号查询在院记录成功");
            ZyActpatient zyActpatient=zyActpatientService.queryByInpatientNo(tableName,inpatientNo,admissTimes);
            GenderEnum genderEnum= GenderEnum.getGenderByCode(Integer.valueOf(zyActpatient.getSex()));
            zyActpatient.setGender(genderEnum==null?GenderEnum.UNKNOWN.name:genderEnum.name);
            zyActpatient.setDeptName(zdUnitCodeService.queryDeptNameByIdInCache(zyActpatient.getDept()));
            zyActpatient.setResponceTypeName(ResponceTypeEnum.getReportTypeByCode(zyActpatient.getResponceType()).name);
            resultMap.put("data", zyActpatient);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "根据住院号查询在院记录出错，请联系管理员");
            log.error("根据住院号查询在院记录异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }








    /**
     * 立即出院
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/leaveHospital", method = {RequestMethod.GET})
    public Map<String, Object> leaveHospital(@RequestParam("inpatientNo") String inpatientNo,@RequestParam("admissTimes") Integer admissTimes, HttpServletRequest httpServletRequest) {
        log.info("根据住院号查询在院记录");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(inpatientNo)) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院号不能为空");
                return resultMap;
            }
            if (admissTimes==null) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院次数不能为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "病人出院操作成功");
            User tokenUser = TokenUtil.getUser(httpServletRequest);
            zyActpatientService.leaveHospital(inpatientNo,admissTimes,tokenUser);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "病人出院操作出错，请联系管理员");
            log.error("病人出院操作异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }




    /**
     * 召回病人
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/recall", method = {RequestMethod.GET})
    public Map<String, Object> recall(@RequestParam("inpatientNo") String inpatientNo,@RequestParam("admissTimes") Integer admissTimes, HttpServletRequest httpServletRequest) {
        log.info("根据住院号查询在院记录");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (StringUtils.isBlank(inpatientNo)) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院号不能为空");
                return resultMap;
            }
            if (admissTimes==null) {
                resultMap.put("code", -1);
                resultMap.put("message", "病人住院次数不能为空");
                return resultMap;
            }
            resultMap.put("code", 0);
            resultMap.put("message", "病人召回操作成功");
            User tokenUser = TokenUtil.getUser(httpServletRequest);
            zyActpatientService.recall(inpatientNo,admissTimes,tokenUser);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("message", "病人召回操作出错，请联系管理员");
            log.error("病人召回操作异常，错误信息{}", e.getMessage());
            return resultMap;
        }
    }

}
