package thyyxxk.webserver.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.constants.Message;
import thyyxxk.webserver.constants.RestrictedDrugLevels;
import thyyxxk.webserver.constants.Ysjb;
import thyyxxk.webserver.dao.his.PublicDao;
import thyyxxk.webserver.dao.his.inpatient.TransferInOfExpensesDao;
import thyyxxk.webserver.dao.his.settings.SettingsDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.datamodify.ZyDetailCharge;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.inpatient.ZyActpatient;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.login.UserInfoSelect;
import thyyxxk.webserver.entity.medicalinsurance.inpatient.ZyPatientInfo;
import thyyxxk.webserver.entity.publicapi.ItemDrug;
import thyyxxk.webserver.entity.publicapi.ZkList;
import thyyxxk.webserver.entity.settings.notification.SendMessageParam;
import thyyxxk.webserver.entity.socketmessage.SocketMessage;
import thyyxxk.webserver.entity.zhuyuanyisheng.PatientAllergenInfo;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.YaoPinXiangMu;
import thyyxxk.webserver.service.hutoolcache.ExtraCache;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.http.websocket.SocketV2;
import thyyxxk.webserver.http.websocket.dto.WebSocketByListUserCode;
import thyyxxk.webserver.http.websocket.dto.WebSocketToAll;
import thyyxxk.webserver.utils.*;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 描述： 公共接口
 * </p>
 *
 * @author xc
 * @date 2021-09-17 10:54
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PublicServer {
    private final PublicDao dao;
    private final TransferInOfExpensesDao transferInOfExpensesDao;
    private final SettingsDao settingsDao;
    private final SqlSessionFactory sqlSessionFactory;
    private final SocketV2 intergrationPlatformSocket;
    private final ExtraCache extraCache;
    private final UserCache userCache;

    /**
     * 手术日期格式
     *
     * @param opStartDate   手术开始时间
     * @param opEndDate     手术结束时间
     * @param anstStartDate 麻醉开始时间
     * @param anstEndDate   麻醉结束时间
     */
    public static void surgeryTimeLimit(String opName, Date opStartDate, Date opEndDate, Date anstStartDate, Date anstEndDate) {
        if (anstStartDate != null) {
            if (DateUtil.shiJianDaXiao(opStartDate, anstStartDate, "<")) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, opName + ":麻醉开始时间要大于手术开始时间.");
            }
            long opDate = opEndDate.getTime() - opStartDate.getTime();
            long anstDate = anstEndDate.getTime() - anstStartDate.getTime();
            if (opDate >= anstDate) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, opName + ":手术麻醉时间一定要比手术时间长.");
            }
        }
    }

    /**
     * 获取用户的角色信息
     *
     * @return 返回角色
     */
    public ResultVo<List<Integer>> getRoleCode() {
        return ResultVoUtil.success(userCache.getUserInfoByToken().getRoles());
    }

    /**
     * @param jueSeBianMa 不需要限制的角色id
     * @return Boolean
     */
    public Boolean noNeedRule(int... jueSeBianMa) {
        return getaBoolean(jueSeBianMa, getRoleCode().getData());
    }

    /**
     * @param jueSeBianMa 不需要限制的角色id
     * @return Boolean
     */
    public Boolean noNeedRule(List<Integer> role, int... jueSeBianMa) {
        return getaBoolean(jueSeBianMa, role);
    }

    /**
     * @param jueSeBianMa 不需要限制的角色id
     * @return Boolean 如果有就返回true
     */
    public Boolean needRule(int... jueSeBianMa) {
        return !getaBoolean(jueSeBianMa, getRoleCode().getData());
    }

    /**
     * @param jueSeBianMa 不需要限制的角色id
     * @return Boolean
     */
    public Boolean needRule(List<Integer> role, int... jueSeBianMa) {
        return !getaBoolean(jueSeBianMa, role);
    }

    public Boolean getaBoolean(int[] jueSeBianMa, List<Integer> roleCode) {
        if (roleCode.contains(1)) {
            return false;
        }
        if (ListUtil.isBlank(roleCode)) {
            return true;
        }
        for (Integer i : jueSeBianMa) {
            if (roleCode.contains(i)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取新的医嘱号
     *
     * @return 返回医嘱号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public BigDecimal getActOrderNo() {
        BigDecimal oldId = dao.getActOrderNo();
        BigDecimal newId = oldId.add(BigDecimal.ONE);
        int num = dao.updateActOrderNo(newId, oldId);
        // 插入生成医嘱的日志
        orderRecord(newId, TokenUtil.getInstance().getTokenUserId());
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成医嘱号错误，请重试！");
        }
        return newId;
    }

    /**
     * 获取新的医嘱编码号
     *
     * @return 返回医嘱号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public String getOrderNo() {
        BigDecimal oldId = dao.getOrderCode();
        BigDecimal newId = oldId.add(BigDecimal.ONE);
        int num = dao.updateOrderNo(newId, oldId);
        // 插入生成医嘱的日志
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成医嘱项目编码错误，请重试！");
        }
        return fmtNoWithLead0(newId, 5);
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public BigDecimal[] getBatchOrderNo(int size) {
        BigDecimal oldId = dao.getOrderCode();
        BigDecimal newId = oldId.add(new BigDecimal(size));
        int num = dao.updateOrderNo(newId, oldId);
        // 插入生成医嘱的日志
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成医嘱项目编码错误，请重试！");
        }
        return new BigDecimal[] {oldId, newId};
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public String getSupplyNo() {
        int supply = dao.getSupply();
        int newSupply = supply + 1;
        int num = dao.updateSupply(supply, newSupply);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成给药方式错误，请重试！");
        }
        return fmtNoWithLead0(newSupply, 3);
    }

    public String getMzSupplyNo() {
        int supply = dao.getMzSupply();
        int newSupply = supply + 1;
        return fmtNoWithLead0(newSupply, 3);
    }

    /**
     * 将数字格式化为指定长度的字符串，不足位数在前面补0.
     *
     * @param number 需要格式化的数字
     * @param length 格式化后的字符串长度
     * @return 格式化后的字符串
     * @throws IllegalArgumentException 如果 length 小于等于 0
     */
    public String fmtNoWithLead0(Object number, int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0.");
        }

        String numberString;

        if (number instanceof BigDecimal) {
            numberString = ((BigDecimal) number).toPlainString(); // 使用 toPlainString() 防止科学计数法
        } else if (number instanceof Integer) {
            numberString = String.valueOf(number);
        } else {
            throw new IllegalArgumentException("Unsupported number type.  Must be BigDecimal or Integer.");
        }


        if (numberString.length() >= length) {
            // 如果数字本身长度大于等于指定长度，则直接返回数字字符串，不进行补0
            return numberString;
        }

        StringBuilder sb = new StringBuilder();
        int zerosToAdd = length - numberString.length();
        for (int i = 0; i < zerosToAdd; i++) {
            sb.append("0");
        }
        sb.append(numberString);

        return sb.toString();
    }

    /**
     * 获取模板的编码
     *
     * @return 返回编码信息
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public String getPatternCode() {
        Integer oldId = dao.getPatternCode();
        Integer newId = oldId + 1;
        int num = dao.updatePatternCode(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成模板编码错误，请重试！");
        }
        return newId.toString();
    }

    /**
     * 获取医嘱模板下面的 子级 排序号
     *
     * @return 返回序号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public BigDecimal getPatternOrderCode() {
        BigDecimal oldId = dao.getPatternOrderCode();
        BigDecimal newId = oldId.add(BigDecimal.ONE);
        int num = dao.updatePatternOrderCode(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成子医嘱模板编码错误，请重试！");
        }
        return newId;
    }

    /**
     * @return 返回说明模板的编码
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Integer getYjTemplateNo() {
        Integer oldId = dao.tempNo();
        Integer newId = oldId + 1;
        int num = dao.updateTempNo(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成说明模板的编码错误，请重试！");
        }
        return newId;
    }

    /**
     * @return 返回申请号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Integer getReqPageNo() {
        Integer oldId = dao.getReqNo();
        Integer newId = oldId + 1;
        int num = dao.updateReqNo(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成申请号错误，请重试！");
        }
        return newId;
    }

    /**
     * 获取药品单号
     *
     * @return 药品单号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Integer getTheDrugListNo() {
        Integer oldId = dao.caoYaoDanHao();
        Integer newId = oldId + 1;
        int num = dao.genXingCaoYaoDanHao(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成申请号错误，请重试！");
        }
        return Integer.valueOf(DateUtil.formatDatetime(new Date(), "yyMMdd") + newId);
    }

    /**
     * 获取传染病序号
     *
     * @return 序号
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Integer getCrbNo() {
        Integer oldId = dao.oldCrbNo();
        Integer newId = oldId + 1;
        int num = dao.updateCrbNo(newId, oldId);
        if (num == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成申请号错误，请重试！");
        }
        return newId;
    }

    /**
     * @param inpatientNo 住院号
     * @return 返回婴儿标志
     */
    public static int getInfantFlag(String inpatientNo) {
        if (StringUtil.isBlank(inpatientNo)) {
            return 0;
        }
        if (inpatientNo.contains("$")) {
            return 1;
        }
        return 0;
    }

    /**
     * 返回
     *
     * @param inpatientNo 住院号
     * @return 返回新住院号
     */
    public static String getInpatientNo(String inpatientNo) {
        if (StringUtil.isBlank(inpatientNo)) {
            return "";
        }
        if (inpatientNo.contains("$")) {
            inpatientNo = inpatientNo.split("\\$")[0];
        }
        return inpatientNo;
    }

    /**
     * 获取最大流水号
     *
     * @param inpatientNo 住院号
     * @param admissTimes 住院次数
     * @return 返回 流水
     */
    public Integer getMaxDetailSn(String inpatientNo, Integer admissTimes) {
        return transferInOfExpensesDao.getMaxDetailSn(inpatientNo, admissTimes);
    }

    /**
     * 获取科室的子科室和本科
     *
     * @param deptCode 科室代码
     * @return 返回科室
     */
    public List<String> getKeShiLieBiaoList(String deptCode) {
        if (noNeedRule()) {
            List<String> list = dao.getKeShiLieBiao(deptCode);
            list.add(deptCode);
            return list;
        }
        return new ArrayList<>();
    }

    public Set<String> getChildDeptByUserCode() {
        return getChildDeptByUserCode(true);
    }

    public Set<String> getChildDeptByUserCode(String userCode) {
        return getChildDeptByUserCode(true, userCode);
    }

    public Set<String> getChildDeptByUserCode(boolean needPartTimeDept, String userCode) {
        UserInfo userInfo = userCache.get(userCode);
        return getDept(needPartTimeDept, userInfo);
    }

    /**
     * 获取医生的子科室 和 兼职科室 以及兼职下面的子科室
     *
     * @return 返回科室
     */
    public Set<String> getChildDeptByUserCode(boolean needPartTimeDept) {
        UserInfo userInfo = userCache.getUserInfoByToken();
        return getDept(needPartTimeDept, userInfo);
    }

    @NotNull
    public Set<String> getDept(boolean needPartTimeDept, UserInfo userInfo) {
        Set<String> list = new HashSet<>();
        if (needPartTimeDept && ListUtil.notBlank(userInfo.getPartTimeDept())) {
            list.addAll(userInfo.getPartTimeDept());
        }
        list.add(userInfo.getDeptCode());
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.in("parent_code", list);
        List<String> temp = dao.selectChildDeptByCodeList(qw);
        if (ListUtil.notBlank(temp)) {
            list.addAll(temp);
        }
        return list;
    }


    /**
     * 获取科室 列表 下面的子科室
     *
     * @param deptCodeList 科室列表
     * @return 返回科室
     */
    public List<String> getKeShiLieBiaoList(List<String> deptCodeList) {
        if (ListUtil.isBlank(deptCodeList)) {
            return new ArrayList<>();
        }
        return dao.getKeShiLieBiaoList(deptCodeList);
    }

    /**
     * 获取人员信息
     *
     * @param code 人员代码
     * @return 返回人员
     */
    public ResultVo<List<GetDropdownBox>> getRenYuan(String code, String deptCode) {
        return ResultVoUtil.success(dao.getRenYuan(StringUtil.isContainChinese(code), deptCode));
    }

    /**
     * 获取员工信息
     *
     * @param code 编码
     * @return 返回
     */
    public UserInfo huoQuYuanGongXinXi(String code) {
        if (StringUtil.isBlank(code)) {
            return new UserInfo();
        }
        return dao.huoQuYuanGongBianMa(code);
    }

    public ResultVo<List<UserInfoSelect>> getPersonnelAll() {
        return ResultVoUtil.success(dao.getPersonnelAll());
    }

    /**
     * 搜索项目信息
     *
     * @param pyCode 拼音码
     * @return 返回项目信息
     */
    public ResultVo<List<GetDropdownBox>> getChargeCode(String pyCode) {
        log.info("获取编码：{}", pyCode);
        return ResultVoUtil.success(dao.getChargeCode(StringUtil.isContainChinese(pyCode)));
    }

    /**
     * 获取科室信息
     *
     * @return 返回科室
     */
    public ResultVo<List<GetDropdownBox>> getDept() {
        return ResultVoUtil.success(dao.getDept());
    }

    public ResultVo<List<GetDropdownBox>> queryDept(String code) {
        return ResultVoUtil.success(dao.queryDept(StringUtil.isContainChinese(code)));
    }

    /**
     * 获取这个人的账页号
     *
     * @param inpatientNo 住院号
     * @param admissTimes 住院次数
     * @return 返回有用的账页号
     */
    public Integer getLedgerSn(String inpatientNo, Integer admissTimes) {
        if (StringUtil.isBlank(inpatientNo) || admissTimes == null) {
            return 0;
        }
        inpatientNo = getInpatientNo(inpatientNo);
        return dao.getLedgerSn(inpatientNo, admissTimes);
    }

    /**
     * 更新患者的退费对应的正流水号
     *
     * @param inpatientNo 住院号
     * @param admissTimes 住院次数
     * @param ledger      账页号
     */
    public void genXingYuanLiuShuiBiaoZhi(String inpatientNo, Integer admissTimes, Integer ledger) {
        dao.chongZhiZhenLiuShui(inpatientNo, admissTimes, ledger);
        // 这里是重置 正流水号
        List<Integer> huoQuTuiFeiYuanLiuShui = dao.huoQuTuiFeiYuanLiuShui(inpatientNo, admissTimes, ledger);
        if (ListUtil.notBlank(huoQuTuiFeiYuanLiuShui)) {
            List<List<Integer>> fenGeFuLiuShui = ListUtils.partition(huoQuTuiFeiYuanLiuShui, 50);
            for (List<Integer> integers : fenGeFuLiuShui) {
                dao.genXingFuShuDuiYingZhenLiuShui(inpatientNo, admissTimes, ledger, integers);
            }
        }
        // 这里是判断正数的是否没有了,如果正数的没有了 那么负数的就要更新为空
        List<Integer> xuYaoQingKongDeFuLiuShui = new ArrayList<>();
        List<Integer> zhenShuLiuShuiMap = dao.zhenShuLiuShui(inpatientNo, admissTimes, ledger);
        List<Integer> fuShuLiuShui = dao.fuShuLiuShui(inpatientNo, admissTimes, ledger);
        for (Integer integer : fuShuLiuShui) {
            if (!zhenShuLiuShuiMap.contains(integer) && !xuYaoQingKongDeFuLiuShui.contains(integer)) {
                xuYaoQingKongDeFuLiuShui.add(integer);
            }
        }
        if (ListUtil.notBlank(xuYaoQingKongDeFuLiuShui)) {
            List<List<Integer>> list = ListUtils.partition(xuYaoQingKongDeFuLiuShui, 50);
            for (List<Integer> integers : list) {
                dao.chongZhiFuShuYuanLiuShui(inpatientNo, admissTimes, ledger, integers);
            }
        }
        // 这里判断是否重复退费，退多了
        Map<Integer, ZyDetailCharge> chongFuYuanLiuShuiMap = dao.chongFuTuiFeiLiuShui(inpatientNo, admissTimes, ledger).stream().collect(Collectors.toMap(ZyDetailCharge::getOriDetailSn, a -> a, (k1, k2) -> k1));
        if (!chongFuYuanLiuShuiMap.isEmpty()) {
            List<ZyDetailCharge> chongFuTuiFeiZhenShu = dao.getZhenShuLiuShui(inpatientNo, admissTimes, ledger, chongFuYuanLiuShuiMap.keySet());
            List<Integer> xuYaoChongZhiLiuShui = new ArrayList<>();
            if (ListUtil.notBlank(chongFuTuiFeiZhenShu)) {
                for (ZyDetailCharge zyDetailCharge : chongFuTuiFeiZhenShu) {
                    ZyDetailCharge zy = chongFuYuanLiuShuiMap.get(zyDetailCharge.getDetailSn());
                    if (BigUtils.bigXiaoYu(zyDetailCharge.getChargeFee(), zy.getChargeFee().negate())) {
                        xuYaoChongZhiLiuShui.add(zyDetailCharge.getDetailSn());
                    }
                }
            }
            // 这里更新
            if (ListUtil.notBlank(xuYaoChongZhiLiuShui)) {
                dao.chongFuTuiFeiChongZhi(inpatientNo, admissTimes, ledger, xuYaoChongZhiLiuShui);
            }
        }
        // 这个是判断 trans_flag_yb = 2 费用相加 不为 0 的 就重置一下
        if (!BigUtils.dengYu(dao.zhenFuXingDiFeiYong(inpatientNo, admissTimes, ledger), 0)) {
            dao.chongXingZhengFuXiangDi(inpatientNo, admissTimes, ledger);
        }
    }


    public List<String> huoQuBingFangDeKeShi(String deptCode) {
        if (getRoleCode().getData().contains(1) || getRoleCode().getData().contains(8) || StringUtil.isBlank(deptCode)) {
            return new ArrayList<>();
        }
        List<String> keShiDaiMa = dao.bingFangSuoSuKeShi(deptCode);
        if (ListUtil.isBlank(keShiDaiMa)) {
            keShiDaiMa.add(deptCode);
        }
        return keShiDaiMa;
    }

    /**
     * 这里的住院号是没有 处理过得
     *
     * @param inpatientNo 住院号
     * @return 返回病人基本信息
     */
    public ZyActpatient huoQuHuanZheXinXi(String inpatientNo) {
        if (StringUtil.isBlank(inpatientNo)) {
            throw new BizException(ExceptionEnum.NULL_POINTER, "住院号为空。");
        }
        ZyActpatient zyActpatient = dao.getHuanZheJiBenXinXi(inpatientNo);
        if (zyActpatient == null) {
            throw new BizException(ExceptionEnum.NULL_POINTER, "没有查询到患者的基本信息。");
        }
        zyActpatient.setInfantFlag(getInfantFlag(zyActpatient.getInpatientNo()));
        zyActpatient.setInpatientNo(getInpatientNo(zyActpatient.getInpatientNo()));
        return zyActpatient;
    }

    /**
     * 获取麻醉方式
     *
     * @return 返回数据
     */
    public ResultVo<List<GetDropdownBox>> maZuiFangShi() {
        return ResultVoUtil.success(dao.maZuiFangShi());
    }

    public Integer huoQuJianYanJianChaXuHao() {
        dao.jianYanJianChaSuo();
        Integer xuHao = dao.jianYanJianChaXuHao() + 1;
        dao.genXingJianYanJianChaXuHao(xuHao);
        return xuHao;
    }

    public Integer huoQuShouShuHao() {
        dao.suoZhuShouShu();
        Integer index = dao.shouShuXuHao() + 1;
        dao.genXingShouShuXuHao(index);
        return index;
    }

    public void huanZheJieSuan(String patNo, Integer times) {
        if (StringUtil.isBlank(patNo) || times == null) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "住院号不能为空。");
        }
        patNo = getInpatientNo(patNo);
        Integer settleType = dao.jieSuanXinXi(patNo, times);
        if (settleType == null) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "没有查询到患者结算信息。");
        }
        if (settleType == 1) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "患者已经结算无法进行操作了。");
        }
    }

    /**
     * 药品限制
     *
     * @param listCode 药品的编码以及规格 做成code
     * @return 返回提示
     */
    public String yaoPinXianZhi(List<String> listCode, boolean delFlag) {
        StringBuilder sb = new StringBuilder();
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.in("rtrim(code) + rtrim(serial)", listCode);
        Map<String, YaoPinXiangMu> map = dao.huoQuYaoPinPiPeiXinXi(qw).stream().collect(Collectors.toMap(YaoPinXiangMu::getZdCode, a -> a, (k1, k2) -> k1));
        return yaoPingXiangMuXianZhi(map, sb, "药品", delFlag);
    }

    public String xiangMuXianZhi(List<String> listCode, boolean delFlag) {
        Map<String, YaoPinXiangMu> map = dao.huoQuXiangMuXinXi(listCode).stream().collect(Collectors.toMap(YaoPinXiangMu::getZdCode, a -> a, (k1, k2) -> k1));
        StringBuilder sb = new StringBuilder();
        return yaoPingXiangMuXianZhi(map, sb, "项目", delFlag);
    }

    @NotNull
    public String yaoPingXiangMuXianZhi(Map<String, YaoPinXiangMu> map, StringBuilder sb, String name, boolean delFlag) {
        for (YaoPinXiangMu item : map.values()) {
            if (delFlag && item.getDelFlag() == 1) {
                sb.append(cuoWuXinXi(item.getZdCode(), "00".equals(item.getSerial().trim()) ? "医嘱名：" + item.getName() + " 项目名：" + item.getZdName() : "" + item.getName(), name + "已被停用"));
            }
            if (StringUtil.isBlank(item.getNationalCode()) && !delFlag) {
                sb.append(cuoWuXinXi(item.getZdCode(), "00".equals(item.getSerial().trim()) ? "医嘱名：" + item.getName() + " 项目名：" + item.getZdName() : "" + item.getName(), name + "没有匹配医保编码"));
            }
        }
        return sb.toString();
    }

    public String cuoWuXinXi(String code, String name, String xinXi) {
        return "编码：<span style='color:teal'>【" + code + "】</span><br>" + "名称：<span style='color:#a5673f'>【" + name + "】 </span><br>" + "<span style='color:red'>" + xinXi + "</span><br>";
    }

    public void sendDoctorNotification(XinZhenYiZhu huanZheXinXi, String content, String title, String sender, List<String> userCodeList) {
        sendDoctorNotification(huanZheXinXi, Collections.singletonList(content), title, sender, userCodeList);
    }


    public void faSongXiaoXi(XinZhenYiZhu huanZheXinXi, String content, String title, String userCode) {
        List<String> huShiBianMa = dao.huoQuHuanZheBingFangDeHuShi(huanZheXinXi.getDeptCode());
        sendDoctorNotification(huanZheXinXi, Collections.singletonList(content), title, userCode, huShiBianMa);
    }

    /**
     * @param huanZheXinXi 患者信息
     * @param content      内容
     * @param title        标题
     * @param userCode     发送人id
     */
    public void faSongXiaoXi(XinZhenYiZhu huanZheXinXi, List<String> content, String title, String userCode) {
        List<String> huShiBianMa = dao.huoQuHuanZheBingFangDeHuShi(huanZheXinXi.getDeptCode());
        sendDoctorNotification(huanZheXinXi, content, title, userCode, huShiBianMa);
    }

    /**
     * @param huanZheXinXi 患者信息
     * @param content      内容
     * @param title        标题
     * @param sender       发送人  TokenUtil.getInstance().getTokenUserId() 不能使用这个因为用的 异步的方法 会导致 tokenUtil.getTokenUserId() 为 99999
     * @param userCodeList 接收方
     */
    @Async
    public void sendDoctorNotification(XinZhenYiZhu huanZheXinXi, List<String> content, String title, String sender, List<String> userCodeList) {
        int count = content.size();
        // 发送通知类
        List<SocketMessage> socketMessage1 = new ArrayList<>();
        List<SocketMessage> socketMessage2 = new ArrayList<>();
        for (String s : content) {
            SocketMessage faSongNeiRong = new SocketMessage();
            faSongNeiRong.setSender(sender);
            faSongNeiRong.setContent(s);
            // 雪花算法
            faSongNeiRong.setId(SnowFlakeId.instance().nextId());
            faSongNeiRong.setPatId(huanZheXinXi.getInpatientNo() + "_" + huanZheXinXi.getAdmissTimes());
            faSongNeiRong.setTitle(title);
            socketMessage1.add(faSongNeiRong);
            for (String huShi : userCodeList) {
                SocketMessage jieShouFang = new SocketMessage();
                jieShouFang.setMsgId(faSongNeiRong.getId());
                jieShouFang.setSender(faSongNeiRong.getSender());
                jieShouFang.setReceiver(huShi);
                socketMessage2.add(jieShouFang);
            }
        }
        List<List<SocketMessage>> fenGeFaSongFang = ListUtils.partition(socketMessage1, 20);
        List<List<SocketMessage>> fenGeJieShouFang = ListUtils.partition(socketMessage2, 20);

        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        PublicDao mapper = sqlSession.getMapper(PublicDao.class);

        for (List<SocketMessage> item : fenGeFaSongFang) {
            mapper.chaRuTongZhiXinXi(item);
        }
        for (List<SocketMessage> item : fenGeJieShouFang) {
            mapper.chaRuJieShouShuJu(item);
        }

        try {
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }

        JSONObject json = new JSONObject();
        UserInfo userInfo = userCache.get(sender);
        json.put("avatar", userInfo.getAvatar());
        json.put("deptName", userInfo.getDeptName());
        json.put("name", userInfo.getName());
        json.put("msg", "患者：【" + huanZheXinXi.getName() + "】" + "新增数据：" + count + "条");
        json.put("title", title);
        json.put("count", count);

        String msgContent = SocketMsg.socketVo(Message.AVATAR_NOTIFICATION, json);

        intergrationPlatformSocket.sendUserCodeListMessage(
                WebSocketByListUserCode.create(userCodeList, msgContent)
        );

    }


    public ResultVo<String> makePyCode(String tableName, String idColumn, String nameColumn, String pyColumn) {
        List<CodeName> list = dao.originalList(tableName, idColumn, nameColumn, pyColumn);
        if (null == list || list.isEmpty()) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有需要更改的数据。");
        }
        for (CodeName item : list) {
            String pycode = PingYinUtils.pyShouZiMuDaXie(item.getName());
            dao.updatePycode(tableName, idColumn, item.getCode(), pyColumn, pycode);
            log.info("修复：{}，{}，{}", item.getCode(), item.getName(), pycode);
        }
        return ResultVoUtil.success("修复拼音码成功，共修复 " + list.size() + " 条。");
    }


    public ResultVo<String> makeDCode(String tableName, String idColumn, String nameColumn, String dColumn) {
        List<CodeName> list = dao.originalDCodeList(tableName, idColumn, nameColumn, dColumn);
        if (null == list || list.isEmpty()) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有需要更改的数据。");
        }
        for (CodeName item : list) {
            String dcode = PingYinUtils.getWBCode(item.getName());
            dao.updateDcode(tableName, idColumn, item.getCode(), dColumn, dcode);
            log.info("修复：{}，{}，{}", item.getCode(), item.getName(), dcode);
        }
        return ResultVoUtil.success("修复五笔码成功，共修复 " + list.size() + " 条。");
    }

    public ResultVo<List<GetDropdownBox>> getAllergens(String name) {
        return ResultVoUtil.success(dao.getAllergens(StringUtil.isContainChinese(name)));
    }

    public ResultVo<List<PatientAllergenInfo>> getPatientAllergens(String patNo) {
        return ResultVoUtil.success(dao.getPatientAllergens(patNo));
    }

    public ResultVo<Boolean> whetherThePatientHasAllergens(String PatNo) {
        return ResultVoUtil.success(dao.whetherThePatientHasAllergens(PatNo) > 0);
    }

    public ResultVo<Integer> newPatientAllergens(String patNo, String allergenCode, int allergenType) {
        if (StringUtil.isBlank(patNo)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有患者住院号");
        }
        PatientAllergenInfo info = new PatientAllergenInfo();
        info.setAllergenCode(allergenCode);
        info.setPatNo(patNo);
        info.setType(allergenType);
        dao.newPatientAllergens(info);
        return ResultVoUtil.success(info.getId());
    }

    public ResultVo<String> removePatientAllergens(Integer id) {
        dao.removePatientAllergens(id);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    /**
     * @param name 名称
     * @return 获取药品信息
     */
    public ResultVo<List<GetDropdownBox>> getDrugInfo(String name) {
        return ResultVoUtil.success(dao.getDrugInfo(StringUtil.isContainChinese(name)));
    }


    public ResultVo<List<GetDropdownBox>> getBldCat(String name) {
        return ResultVoUtil.success(dao.getBldCat(StringUtil.isContainChinese(name)));
    }

    /**
     * 获取转科列表
     *
     * @return
     */
    public ResultVo<List<ZkList>> getTheTransferList() {
        List<ZkList> list = dao.getTheTransferList();
        for (ZkList zkList : list) {
            zkList.setValue(JSON.toJSONString(zkList));
        }
        return ResultVoUtil.success(list);
    }

    @Data
    @AllArgsConstructor
    public static class IntCodeName {
        private Integer code;
        private String name;
    }

    public ResultVo<Map<String, Object>> getPeopleToFillInInformation() throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> map = new HashMap<>(Capacity.EIGHT);
        map.put("restrictedDrugLevels", EnumToJson.toJson(RestrictedDrugLevels.values()));
        map.put("ysjbData", EnumToJson.toJson(Ysjb.values()));
        map.put("deptData", getDept().getData());
        map.put("empPosition", dao.getEmpPosition());
        map.put("empInmark", dao.getEmpInmark());
        map.put("zdIfcadre", dao.getZdIfcadre());
        map.put("zdEmpTitle", dao.getZdEmpTitle());
        map.put("mzyZdChargeType", dao.getMzyZdChargeType());

        List<IntCodeName> list = new ArrayList<IntCodeName>() {{
            add(new IntCodeName(1, "非限制"));
            add(new IntCodeName(2, "限制"));
        }};

        map.put("doctorYpZl", list);
        return ResultVoUtil.success(map);
    }

    public ResultVo<Boolean> idVerification(String idCard) {
        return ResultVoUtil.success(IdCardUtil.isValidatedIdCard(idCard));
    }

    public Integer getPersonnelCode() {
        dao.lockThePersonnelCodeTable();
        Integer code = dao.getPersonnelCode();
        dao.updateStaffCodeTable(code);
        return code;
    }

    public ResultVo<String> sendMessage(SendMessageParam param) {
        settingsDao.insertNewMessage(SnowFlakeId.instance().nextId(), param.getMessage());
        JSONObject obj = new JSONObject();
        obj.put("message", param.getMessage());
        if (null != param.getRefreshDelay()) {
            int delay = param.getRefreshDelay() * 1000;
            obj.put("refreshDelay", delay);
        }
        String msgContent = SocketMsg.socketVo(Message.SYSTEM_NOTIFICATION, obj);

        intergrationPlatformSocket.sendMessageToAll(
                WebSocketToAll.create(msgContent)
        );

        log.info("发送全体消息 => 操作员：{}，消息体：{}", TokenUtil.getInstance().getTokenUserId(), obj);
        return ResultVoUtil.success();
    }


    public void sendSystemAnnouncement() {
        Map<String, String> map = extraCache.getMessage();
        JSONObject obj = new JSONObject();
        obj.put("data", map);
        String msgContent = SocketMsg.socketVo(Message.SYSTEM_ANNOUNCEMENT, obj);

        intergrationPlatformSocket.sendMessageToAll(
                WebSocketToAll.create(msgContent)
        );
    }

    /**
     * @description: 查询有住院的科室
     * @author: lihong
     * @date: 2022/12/26 16:58
     * @return: thyyxxk.webserver.entity.ResultVo<java.util.List < thyyxxk.webserver.entity.datamodify.GetDropdownBox>>
     **/
    public ResultVo<List<GetDropdownBox>> getZhuYuanDept() {
        return ResultVoUtil.success(dao.getZhuYuanDept());
    }


    @Async
    public void orderRecord(BigDecimal orderCode, String userCode) {
        if (orderCode == null) {
            return;
        }
        if (dao.selectRecordByOrderNo(orderCode) > 0) {
            return;
        }
        dao.insertOrderNoRecord(orderCode, userCode);
    }

    public ResultVo<UserInfo> getUserInfoByCode(String code) {
        return ResultVoUtil.success(userCache.get(code));
    }


    public ZyPatientInfo getPatInfo(String patNo, Integer times) {
        ZyPatientInfo p = dao.queryPatientInfo(patNo, times, "zy_actpatient");
        if (p == null) {
            p = dao.queryPatientInfo(patNo, times, "zy_inactpatient");
        }
        return p;
    }

    public ResultVo<JSONObject> getUserConfigByCode(String code) {
        String config = dao.getUserConfigByCode(code);
        return ResultVoUtil.success(StringUtil.isBlank(config) ? new JSONObject() : JSONObject.parseObject(config));
    }


    public ResultVo<String> setUserConfigByCode(JSONObject config) {
        dao.setUserConfigByCode(TokenUtil.getInstance().getTokenUserId(), JSON.toJSONString(config));
        return ResultVoUtil.success();
    }

    public ResultVo<String> refreshUserInfo(String code) {
        userCache.refreshCache(code);
        return ResultVoUtil.success();
    }

    public ResultVo<List<ItemDrug>> getItemDrug(String code) {
        return ResultVoUtil.success(dao.getItemDrug(StringUtil.isContainChinese(code)));
    }

    public Set<String> getUserDeptList(String code) {
        Set<String> deptList;
        UserInfo userInfo = userCache.get(code);
        if (userInfo.getDeptCode().startsWith("8")) {
            deptList = dao.chaXunZhiZXinKeShi(userInfo.getDeptCode());
            deptList.add(userInfo.getDeptCode());
        } else {
            deptList = getDept(true, userInfo);
        }
        return deptList;
    }

    public Set<String> getUserDeptList() {
        return getUserDeptList(TokenUtil.getInstance().getTokenUserId());
    }

    public static <T> String listToSqlIn(Collection<T> collection) {
        if (collection == null || collection.isEmpty()) {
            return "('')";
        }

        Set<T> uniqueSet = new HashSet<>(collection);
        StringBuilder sb = new StringBuilder("(");
        for (T item : uniqueSet) {
            if (item instanceof String) {
                sb.append("'").append(item).append("',");
            } else {
                sb.append(item).append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(")");

        return sb.toString();
    }

}

