package thyyxxk.webserver.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
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.casefrontsheet.YshHzRecord;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.datamodify.ZyDetailCharge;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.publicapi.ZkList;
import thyyxxk.webserver.entity.settings.notification.SendMessageParam;
import thyyxxk.webserver.entity.socketmessage.SocketMessage;
import thyyxxk.webserver.entity.inpatient.ZyActpatient;
import thyyxxk.webserver.entity.zhuyuanyisheng.PatientAllergenInfo;
import thyyxxk.webserver.entity.zhuyuanyisheng.caoyaoyizhu.YzActOrderCy;
import thyyxxk.webserver.entity.zhuyuanyisheng.jianyanjiancha.YshYjReq;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.OpRecord;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.YaoPinXiangMu;
import thyyxxk.webserver.service.redislike.RedisLikeService;
import thyyxxk.webserver.utils.*;
import thyyxxk.webserver.websocket.WebSocketServer;

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

/**
 * <p>
 * 描述： 公共接口
 * </p>
 *
 * @author xc
 * @date 2021-09-17 10:54
 */
@Service
@Slf4j
public class PublicServer {
    private final PublicDao dao;
    private final TransferInOfExpensesDao transferInOfExpensesDao;
    private final RedisLikeService redisLikeService;

    private final SettingsDao settingsDao;


    public PublicServer(PublicDao dao, TransferInOfExpensesDao transferInOfExpensesDao, RedisLikeService redisLikeService, SettingsDao settingsDao) {
        this.dao = dao;
        this.transferInOfExpensesDao = transferInOfExpensesDao;
        this.redisLikeService = redisLikeService;
        this.settingsDao = settingsDao;
    }

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

    }

    /**
     * 获取用户的角色信息
     *
     * @return 返回角色
     */
    public ResultVo<List<Integer>> getRoleCode() {
        return ResultVoUtil.success(redisLikeService.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
     */
    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 (ListUtil.isBlank(roleCode)) {
            return true;
        }
        if (roleCode.contains(1)) {
            return false;
        }
        for (Integer i : jueSeBianMa) {
            if (roleCode.contains(i)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取新的医嘱号
     *
     * @return 返回医嘱号
     */
    public float getActOrderNo() {
        dao.lockTable();
        float actOrderNo = dao.getActOrderNo() + 1;
        dao.updateActOrderNo(actOrderNo);
        return actOrderNo;
    }

    /**
     * 获取模板的编码
     *
     * @return 返回编码信息
     */
    public String getPatternCode() {
        dao.lockTable();
        Integer patternCode = dao.getPatternCode() + 1;
        dao.updatePatternCode(patternCode);
        return patternCode.toString();
    }

    /**
     * 获取医嘱模板下面的 子级 排序号
     *
     * @return 返回序号
     */
    public float getPatternOrderCode() {
        dao.lockTable();
        float patternOrderCode = dao.getPatternOrderCode() + 1;
        dao.updatePatternOrderCode(patternOrderCode);
        return patternOrderCode;
    }

    /**
     * @return 返回说明模板的编码
     */
    public Integer getYjTemplateNo() {
        dao.lockYshConfig();
        Integer tempNo = dao.tempNo() + 1;
        dao.updateTempNo(tempNo);
        return tempNo;
    }

    /**
     * @return 返回申请号
     */
    public Integer getReqPageNo() {
        dao.lockYshConfig();
        Integer reqNo = dao.getReqNo() + 1;
        dao.updateReqNo(reqNo);
        return reqNo;
    }

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

    /**
     * 返回
     *
     * @param inpatientNo 住院号
     * @return 返回新住院号
     */
    public 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(1)) {
            Map<String, GetDropdownBox> map = dao.getKeShiLieBiao(deptCode).stream().collect(Collectors.toMap(GetDropdownBox::getCode, a -> a, (k1, k2) -> k1));
            if (StringUtil.isBlank(map.get(deptCode).getParentCode())) {
                return new ArrayList<>(map.keySet());
            }
            return Stream.of(deptCode).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 获取科室的子科室和本科
     *
     * @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) {
        return ResultVoUtil.success(dao.getRenYuan(StringUtil.isContainChinese(code)));
    }

    /**
     * 搜索项目信息
     *
     * @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());
    }

    /**
     * 获取这个人的账页号
     *
     * @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);
        }
    }

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

    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);
        log.info("查询患者的信息在院：住院号{}", inpatientNo);
        if (zyActpatient == null) {
            throw new BizException(ExceptionEnum.NULL_POINTER, "没有查询到患者的基本信息。");
        }
        zyActpatient.setInfantFlag(getInfantFlag(zyActpatient.getInpatientNo()));
        zyActpatient.setInpatientNo(getInpatientNo(zyActpatient.getInpatientNo()));
        return zyActpatient;
    }

    /**
     * 这里是重置流水
     *
     * @param patNo 住院号
     * @param times 住院次数
     */
    @Transactional(rollbackFor = Exception.class)
    public void chongZhiLiuShui(String patNo, Integer times) {
        List<ZyDetailCharge> paiXu = dao.huoQuZhongYeFeiYong(patNo, times);
        log.info("获取数据：{}", JSON.toJSONString(paiXu));
        int maxDetailSn = dao.maxDetailSn(patNo, times);

        List<List<ZyDetailCharge>> fenDuan = ListUtils.partition(paiXu, 100);
        for (List<ZyDetailCharge> zyDetailCharges : fenDuan) {
            dao.chongZhiLiuShui(patNo, times, zyDetailCharges, maxDetailSn);
        }

        for (List<ZyDetailCharge> zyDetailCharges : fenDuan) {
            dao.chongZhiLiuShui(patNo, times, zyDetailCharges, 0);
        }

    }

    /**
     * 获取麻醉方式
     *
     * @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;
    }

    /**
     * 获取药品单号
     *
     * @return 药品单号
     */
    public Integer getTheDrugListNo() {
        dao.lockTable();
        Integer index = dao.caoYaoDanHao() + 1;
        dao.genXingCaoYaoDanHao(index);
        return Integer.valueOf(DateUtil.formatDatetime(new Date(), "yyMMdd") + index);
    }

    public String getGroupNo() {
        String groupNo = "71";
        if (DateUtil.timeIsInRound(DateUtil.formatDatetime(new Date(), "HH:mm:ss"), "08:00:00", "19:59:59")) {
            groupNo = "73";
        }
        return groupNo;
    }

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

    public void huoQuGaiYiZhuXiaXiangMu(BigDecimal orderNo) {
        YshHzRecord hz = dao.huiZhen(orderNo);
        if (hz != null) {
            if (hz.getStatusFlag().trim().equals("2")) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, "该医嘱下的会诊，已经完成无法删除了。");
            }
            return;
        }
        YshYjReq yj = dao.yiJi(orderNo);
        if (yj != null) {
            if (yj.getReceiveFlag().trim().equals("2")) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, String.format("该医嘱下【%s】，已经完成无法删除了。", yj.getReqType().trim().equals("2") ? "检验" : "检查"));
            }
            return;
        }
        OpRecord shouShu = dao.shouShu(orderNo);
        if (shouShu != null) {
            if (!shouShu.getStatus().trim().equals("1")) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, "该医嘱下的手术，无法被删除。");
            }
            return;
        }
        YzActOrderCy caoYao = dao.caoYao(orderNo);
        if (caoYao != null) {
            if (caoYao.getStatusFlag().trim().equals("4")) {
                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>";
    }

    /**
     * @param huanZheXinXi 患者信息
     * @param content      内容
     * @param title        标题
     * @param userCode     发送人id
     */
    @Async
    public void faSongXiaoXi(XinZhenYiZhu huanZheXinXi, List<String> content, String title, String userCode) {
        List<String> huShiBianMa = dao.huoQuHuanZheBingFangDeHuShi(huanZheXinXi.getDeptCode());
        JSONObject obj = new JSONObject();
        obj.put("message", "您有新的通知请及时查看。");
        // 消息数量
        obj.put("count", content.size());

        // 发送通知类
        List<SocketMessage> socketMessage1 = new ArrayList<>();
        List<SocketMessage> socketMessage2 = new ArrayList<>();
        for (String s : content) {
            SocketMessage faSongNeiRong = new SocketMessage();
            faSongNeiRong.setSender(userCode);
            faSongNeiRong.setContent(s);
            // 雪花算法
            faSongNeiRong.setId(SnowFlakeId.instance().nextId());
            faSongNeiRong.setPatId(huanZheXinXi.getInpatientNo() + "_" + huanZheXinXi.getAdmissTimes());
            faSongNeiRong.setTitle(title);
            socketMessage1.add(faSongNeiRong);
            for (String huShi : huShiBianMa) {
                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);
        for (List<SocketMessage> item : fenGeFaSongFang) {
            dao.chaRuTongZhiXinXi(item);
        }
        for (List<SocketMessage> item : fenGeJieShouFang) {
            dao.chaRuJieShouShuJu(item);
        }
        huShiBianMa.forEach(code -> WebSocketServer.sendMessageByUserCode(code, SocketMsg.socketVo(Message.SYSTEM_NOTIFICATION, obj)));

    }

    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() + " 条。");
    }

    @DS("his")
    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_NOTIFICATION);
    }

    /**
     * @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);
    }

    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());
        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);
        }
        WebSocketServer.sendMessageToAll(SocketMsg.socketVo(Message.SYSTEM_NOTIFICATION, obj));
        log.info("发送全体消息 => 操作员：{}，消息体：{}", TokenUtil.getTokenUserId(), obj);
        return ResultVoUtil.success();
    }


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


}

