package thyyxxk.webserver.service.zhuyuanyisheng;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
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.dao.his.zhuyuanyisheng.JianYanJianChaDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.YiZhuLuRuDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.datamodify.SelectValueObject;
import thyyxxk.webserver.entity.zhuyuanyisheng.jianyanjiancha.*;
import thyyxxk.webserver.entity.zhuyuanyisheng.query.ChaXunJianChaHeJianYan;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.PatientTemp;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.*;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 描述： 住院医生，检查申请
 * </p>
 *
 * @author xc
 * @date 2022-02-10 15:37
 */
@Service
@Slf4j
public class JianYanJianChaShenQingServer {
    private final JianYanJianChaDao dao;
    private final PublicServer publicServer;
    private final YiZhuLuRuDao yiZhuLuRuDao;

    public JianYanJianChaShenQingServer(JianYanJianChaDao dao, PublicServer publicServer, YiZhuLuRuDao yiZhuLuRuDao) {
        this.dao = dao;
        this.publicServer = publicServer;
        this.yiZhuLuRuDao = yiZhuLuRuDao;
    }

    /*-------------------------------------------------------------- 下面是检查的逻辑 -----------------------------------------------------------------------------------------------------*/

    /**
     * 获取检验检查的名字
     *
     * @param name    姓名
     * @param patNo   住院号
     * @param times   住院次数
     * @param bedNo   床位
     * @param reqType 2-检验 3-检查
     * @return 返回数据
     */
    public ResultVo<List<Map<String, String>>> huoQuJianYanJianChaMing(String name, String patNo, Integer times, String bedNo, String reqType) {
        return ResultVoUtil.success(dao.huoQuJianJianChaMing(patNo, times, bedNo, StringUtil.isContainChinese(name), reqType));
    }

    /**
     * 获取检查申请
     *
     * @param param 检查申请
     * @return 返回数据
     */
    public ResultVo<IPage<YshYjReq>> huoQuJianChaShenQing(ChaXunJianChaHeJianYan param) {
        IPage<YshYjReq> page = new Page<>(param.getCurrentPage(), param.getPageSize(), param.getTotal() == 0);
        page = dao.huoQuJianChaShenQing(page, param.getPatNo(), param.getTimes(), param.getOrderName(), param.getStartTime(), param.getEndTime());
        return ResultVoUtil.success(page);
    }

    public ResultVo<Map<String, Object>> huoQuShengQingXiangQing(Integer reqNo) {
        YshYjReq req = dao.huoQuShengQingXiangQing(reqNo);
        if (req == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_HTML_ERROR, "没有查询到有效信息，可能已经被删除了。");
        }
        Map<String, Object> map = new HashMap<>();
        StringBuilder zhuYiShiXiang = new StringBuilder();
        JcZdClass jc = dao.daYingXiangQing(req.getOrderType());
        // 获取患者的住址和性别
        PatientTemp patient = dao.huoQuHuanZheXinXi(req.getInpatientNo());
        req.setSex(patient.getSex());
        // 地址
        req.setHomeStreet(patient.getHomeStreet());
        //联系电话
        req.setHomeTel(patient.getHomeTel());
        // 医保身份
        req.setResponceTypeName(dao.huoQuHuanZheShenFen(req.getInpatientNo()));

        map.put("biaoTi", jc.getComm());
        Field[] fields = jc.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            // 输出属性名和属性值
            try {
                String key = field.getName();
                Object value = EntityStringTrim.getFieldValue(jc, key);
                if (key.startsWith("comment") && StringUtil.notBlank((String) value)) {
                    zhuYiShiXiang.append(((String) value).trim()).append("\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        map.put("zhuYiShiXiang", zhuYiShiXiang.toString());
        map.put("shuJu", req);
        return ResultVoUtil.success(map);
    }


    /**
     * 查询检查检验分类
     *
     * @param total       总条数
     * @param currentPage 当前页
     * @param leiXing     类型 1-新申请 2-个人 3-科室
     * @param jianCha     true 检查 false 检验
     * @return 返回分页数据
     */
    public ResultVo<IPage<JcZdClass>> jianChaJianYanFenLei(long total, long currentPage, Integer leiXing, Boolean jianCha) {
        IPage<JcZdClass> page = new Page<>();
        if (leiXing == 1) {
            if (jianCha) {
                if (total == 0) {
                    page.setTotal(dao.jianChaMingTiaoShu());
                }
                page.setRecords(dao.jianChaMing(currentPage));
            } else {
                page = new Page<>(currentPage, 20, total == 0);
                page = dao.jianYanFenLei(page);
                return ResultVoUtil.success(page);
            }
        } else {
            page = new Page<>(currentPage, 20, total == 0);
            page = dao.jianChaJianYanMuBan(page, leiXing, TokenUtil.getTokenUserId(), jianCha ? "3" : "2");
        }
        return ResultVoUtil.success(page);
    }

    /**
     * 检验检查的分类详细信息
     *
     * @param code    编码
     * @param bwCode  不是个人编码的话就需要这个
     * @param jianCha true 检查 false 检验
     * @return 返回详细的内容
     */
    public ResultVo<List<Map<String, String>>> chaKanFenLeiXiangQing(String code, String bwCode, Boolean jianCha) {
        if (jianCha) {
            if (StringUtil.notBlank(bwCode) && bwCode.equals("mb")) {
                return ResultVoUtil.success(dao.chaKanMuBanNeiRong(code, "3"));
            }
            return ResultVoUtil.success(dao.chaKanFenLeiXiangQing(code, bwCode));
        }
        if (StringUtil.notBlank(bwCode) && bwCode.equals("mb")) {
            return ResultVoUtil.success(dao.chaKanMuBanNeiRong(code, "2"));
        }
        return ResultVoUtil.success(dao.chaKanJianYanXiangQing(code));
    }

    /**
     * 删除检查或检验模板
     *
     * @param code     要删除的模板 code
     * @param deptCode 当前患者的科室编码
     * @return 返回提示
     */
    public ResultVo<String> shanShuJianChaMuBan(String code, String deptCode) {
        ZyTcYj yj = dao.jianChaLuRuRen(code);
        if (yj == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找对应的记录可能已经被删除了。");
        }
        if (jianChaMuBanPanDuan(yj.getOpId(), yj.getTcExec(), deptCode)) {
            dao.shanChuJianChaMuBan(code);
            return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有权限执行这个操作。");
    }

    /**
     * 检查模板的判断
     *
     * @param opId     录入人
     * @param tcExec   模板的科室
     * @param deptCode 当前用户的科室
     * @return boolean
     */
    public boolean jianChaMuBanPanDuan(String opId, String tcExec, String deptCode) {
        List<Integer> userRole = publicServer.getRoleCode().getData();
        // 医务部
        if (userRole.contains(38)) {
            return true;
        }
        // 科主任 可以删除自己科室任意模板
        if (userRole.contains(11) && tcExec.trim().equals(deptCode)) {
            return true;
        }
        // 普通的只能删除自己的
        return opId.trim().equals(TokenUtil.getTokenUserId());
    }

    /**
     * 获取说明，模板的一下信息
     *
     * @param name        根据说明模板来 搜索
     * @param fenLei      分类
     * @param total       总数
     * @param currentPage 当前页
     * @return 返回提示
     */
    public ResultVo<IPage<YshZdYjTemplate>> huoMuShuoMingMuBan(String name, Integer fenLei, long total, long currentPage) {
        Page<YshZdYjTemplate> page = new Page<>(currentPage, 20, total == 0);
        page = dao.huoQuShuoMingMuBan(page, StringUtil.isContainChinese(name), fenLei, TokenUtil.getTokenUserId());
        return ResultVoUtil.success(page);
    }

    /**
     * 对于说明模板的操作
     *
     * @param param 说明模板的内容
     * @return 返回提示
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo<String> shouMingMuBanChaoZuo(YshZdYjTemplate param) {
        switch (param.getLeiXing()) {
            case "修改":
                return xiuGaiMuBan(param, dao.muBanShuJu(param.getCode()));
            case "删除":
                return shanChuMuBan(dao.muBanShuJu(param.getCode()));
            case "新增":
                return xinZengShouMingMuBan(param);
        }
        return ResultVoUtil.success();
    }

    /**
     * 修改说明模板
     *
     * @param param 修改的数据
     * @param mb    原来的数据
     * @return 返回提示
     */
    private ResultVo<String> xiuGaiMuBan(YshZdYjTemplate param, YshZdYjTemplate mb) {
        if (publicServer.noNeedRule(38)) {
            if (!TokenUtil.getTokenUserId().equals(mb.getOpId().trim())) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "该模板创建人不是你，无法操作。");
            }
        }
        dao.genXingShouMingMuBan(param.getJcText(), param.getName(),
                PingYinUtils.pyShouZiMuDaXie(param.getName()),
                PingYinUtils.getWBCode(param.getName()), param.getCode());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    /**
     * 删除说明模板
     *
     * @param mb 通过数据库查找 原来的模板
     * @return 返回提示
     */
    private ResultVo<String> shanChuMuBan(YshZdYjTemplate mb) {
        List<Integer> userRole = publicServer.getRoleCode().getData();
        if (publicServer.noNeedRule(userRole, 38)) {
            if (TokenUtil.getTokenUserId().equals(mb.getOpId().trim()) || (userRole.contains(11) && mb.getDeptCode().trim().equals(mb.getUserDeptCode().trim()))) {
                dao.shanChuShouMingMuBan(mb.getCode());
                return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
            } else {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有权限修改。");
            }
        }
        dao.shanChuShouMingMuBan(mb.getCode());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    /**
     * 新增说明模板
     *
     * @param param 新增的数据
     * @return 返回提示
     */
    private ResultVo<String> xinZengShouMingMuBan(YshZdYjTemplate param) {
        if (param.getWhFlag().trim().equals("3") && publicServer.noNeedRule(38)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有权限创建全院模板。");
        }
        param.setCode(publicServer.getYjTemplateNo().toString());
        param.setPyCode(PingYinUtils.pyShouZiMuDaXie(param.getName(), 8));
        param.setDCode(PingYinUtils.getWBCode(param.getName(), 8));
        param.setOpId(TokenUtil.getTokenUserId());
        dao.xinZengShouMingMuBan(param);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }


    /**
     * 搜索临床诊断
     *
     * @param name    搜索的名字
     * @param laiYuan true 医保 false 本院
     * @return 返回搜索的数据
     */
    @DS("his")
    public ResultVo<List<GetDropdownBox>> huoQuLinChuangZhenDuan(String name, Boolean laiYuan) {
        return laiYuan ? ResultVoUtil.success(dao.yiBaoZhenDuan(StringUtil.isContainChinese(name))) :
                ResultVoUtil.success(dao.benYuanLinChuangZhenDuan(StringUtil.isContainChinese(name)));
    }

    /**
     * 判断检查模板是否有重复的
     *
     * @param name 名称
     * @return 返回有没有
     */
    public ResultVo<Boolean> jianChaJianYanMuBanMing(String name, String reqType) {
        return ResultVoUtil.success(dao.huoQuJianChaJianYanChongFuMuBanMing(name, TokenUtil.getTokenUserId(), reqType).size() > 0);
    }

    /**
     * 保存检查或检验模板
     *
     * @param param 数据
     * @return 返回提示
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo<String> baoCunJianChaJianYanMuBan(ZyTcYj param) {
        if (publicServer.noNeedRule(11)) {
            if (param.getOrderType().equals("2")) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有权限创建科室模板。");
            }
        }
        // TODO 新增模板的时候要先删除
        param.setOpId(TokenUtil.getTokenUserId());
        param.setTcNo(publicServer.huoQuJianYanJianChaXuHao().toString());
        param.setPyCode(PingYinUtils.pyShouZiMuDaXie(param.getTcName(), 8));
        param.setDCode(PingYinUtils.getWBCode(param.getTcName(), 8));
        List<String> yuanShuJu = dao.huoQuJianChaJianYanChongFuMuBanMing(param.getTcName(), param.getOpId(), param.getReqType());
        if (ListUtil.notBlank(yuanShuJu)) {
            for (String s : yuanShuJu) {
                dao.shanChuJianChaMuBan(s);
            }
        }
        dao.chaRuJCJYMuBan(param);
        dao.chaRuJCJYMuBanNeiRong(param.getList(), param.getTcNo(), param.getReqType().trim());
        log.info("模板数据：{}", JSON.toJSONString(param.getList()));
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    public ResultVo<String> baoCunJianYanJianCha(TianJiaJianChaJianYan param) {
        if (ListUtil.isBlank(param.getList())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请选择需要保存的数据。");
        }
        XinZhenYiZhu huanZheXinXi = yiZhuLuRuDao.huoQuHuanZheXinXi(param.getInpatientNo(), param.getAdmissTimes());
        publicServer.huanZheJieSuan(param.getInpatientNo(), param.getAdmissTimes());
        List<String> xm = new ArrayList<>();
        int index = 1;
        List<String> content = new ArrayList<>();
        StringBuilder cuoWuXinXi = new StringBuilder();
        for (YshYjReq item : param.getList()) {
            if (StringUtil.notBlank(item.getJzFlag()) && item.getJzFlag().equals("0")) {
                item.setJzFlag(null);
            }
            if (StringUtil.notBlank(item.getYbSelfFlag()) && item.getYbSelfFlag().equals("0")) {
                item.setYbSelfFlag(null);
            }
            if (StringUtil.isBlank(item.getOrderCode())) {
                cuoWuXinXi.append(baoCunCuoWuXinXi(index, "项目编码不能为空"));
            }
            if (StringUtil.isBlank(item.getOrderName())) {
                cuoWuXinXi.append(baoCunCuoWuXinXi(index, "项目名称不能为空"));
            }
            if (item.getStartTime() == null) {
                cuoWuXinXi.append(baoCunCuoWuXinXi(index, "检查时间不能为空"));
            } else if (DateUtil.shiJianDaXiao(huanZheXinXi.getAdmissDate(), item.getStartTime(), ">")) {
                cuoWuXinXi.append(baoCunCuoWuXinXi(index, "检查时间不能在入院时间之前。"));
            }
            if (StringUtil.isBlank(item.getExecDept())) {
                cuoWuXinXi.append(baoCunCuoWuXinXi(index, "执行科室不能为空。"));
            }
            if (param.getReqType().equals("3")) {
                if (StringUtil.isBlank(item.getReqComment())) {
                    cuoWuXinXi.append(baoCunCuoWuXinXi(index, "病室摘要不能为空。"));
                }
                if (StringUtil.isBlank(item.getReqTzComment())) {
                    cuoWuXinXi.append(baoCunCuoWuXinXi(index, "体征信息不能为空。"));
                }
                if (StringUtil.isBlank(item.getReqOtherResult())) {
                    cuoWuXinXi.append(baoCunCuoWuXinXi(index, "相关辅检结果不能为空。"));
                }
                if (StringUtil.isBlank(item.getDiagCode())) {
                    cuoWuXinXi.append(baoCunCuoWuXinXi(index, "临床诊断不能为空。"));
                }
            } else {
                if (StringUtil.isBlank(item.getInspectStuff())) {
                    cuoWuXinXi.append(baoCunCuoWuXinXi(index, "标本不能为空。"));
                }
            }

            if (cuoWuXinXi.length() > 0) {
                cuoWuXinXi.append("<br>");
            } else {
                item.setActOrderNo(BigDecimal.valueOf(publicServer.getActOrderNo()));
                item.setReqNo(publicServer.getReqPageNo());
            }
            xm.add(item.getOrderCode().trim());
            content.add(String.format("%s：<span style='color:#409eff'>【%s】</span><br>" +
                            "患者姓名：<span style='color:#409eff'>【%s】</span><br>" +
                            "床位：<span style='color:#409eff'>【%s】</span>", param.getReqType().equals("2") ? "检查名" : "检验名",
                    item.getOrderName(), huanZheXinXi.getName(), huanZheXinXi.getBedNo()));
            index++;
        }
        String tingYong = publicServer.xiangMuXianZhi(xm, true);
        if (StringUtil.notBlank(tingYong)) {
            throw new BizException(ExceptionEnum.LOGICAL_HTML_ERROR, tingYong);
        }

        if (StringUtil.notBlank(cuoWuXinXi.toString())) {
            throw new BizException(ExceptionEnum.LOGICAL_HTML_ERROR, String.valueOf(cuoWuXinXi));
        }
        String userCode = TokenUtil.getTokenUserId();
        dao.chaRuShenQing(param.getList(), param.getInpatientNo(), param.getName(), param.getAge() + "岁", param.getAdmissTimes(),
                param.getBedNo(), userCode, huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(), param.getReqType());
        dao.chaRuShenQingYiZhu(param.getList(), param.getInpatientNo(), param.getAdmissTimes(), userCode, huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(),
                publicServer.getInfantFlag(param.getInpatientNo()));

        publicServer.faSongXiaoXi(huanZheXinXi, content, param.getReqType().equals("2") ? "新增检查" : "新增检验", TokenUtil.getTokenUserId());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    public String baoCunCuoWuXinXi(int index, String xinXi) {
        return String.format("第【%d】行%s<br>", index, xinXi);
    }


    /*-------------------------------------------------------------- 下面是检验的逻辑 -----------------------------------------------------------------------------------------------------*/
    public ResultVo<IPage<YshYjReq>> huoQuJianYan(ChaXunJianChaHeJianYan param) {
        Page<YshYjReq> page = new Page<>(param.getCurrentPage(), param.getPageSize(), param.getTotal() == 0);
        page.addOrder(OrderItem.desc("act_order_no"));
        page = dao.huoQuJianYan(page, param.getPatNo(), param.getTimes(), param.getStartTime(), param.getEndTime(), param.getOrderName());
        return ResultVoUtil.success(page);
    }

    public ResultVo<IPage<JcZdClass>> huoQuJianYanMing(long total, long currentPage, Integer leiXing) {
        IPage<JcZdClass> page = new Page<>(currentPage, 20, total == 0);
        if (leiXing == 1) {
            page = dao.jianYanFenLei(page);
            return ResultVoUtil.success(page);
        }
        return ResultVoUtil.success();
    }


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

    @DS("his")
    public ResultVo<List<JianYanFeiYongXiangQing>> viewInspectionItemDetails(String orderCode) {
        return ResultVoUtil.success(dao.viewInspectionItemDetails(orderCode));
    }


    public ResultVo<String> shanChuJianChaJianYan(Integer reqNo, String patNo, Integer times) {
        if (StringUtil.isBlank(patNo)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "住院号不能为空。");
        }
        YshYjReq yj = dao.huoQuJianYanJianCha(reqNo, patNo, times);
        if (yj == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有查询到该数据的具体信息，已经被删除了。");
        }
        if (yj.getReceiveFlag().trim().equals("2")) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "结果已返回，无法删除。");
        }
        dao.shanChuJianYanJianCha(reqNo, patNo, times);
        dao.shanChuYiZhu(yj.getActOrderNo());
        log.info("删除医技申请==》操作人：{}，医技数据：{}", TokenUtil.getTokenUserId(), JSON.toJSONString(yj));
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }


}

