package thyyxxk.webserver.service.zhuyuanyisheng;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.GetDateFormat;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.CaoYaoYiZhuDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.YiZhuLuRuDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.zhuyuanyisheng.caoyaoyizhu.CaoYaoChaXunTiaoJian;
import thyyxxk.webserver.entity.zhuyuanyisheng.caoyaoyizhu.YzActOrderCy;
import thyyxxk.webserver.entity.zhuyuanyisheng.caoyaoyizhu.YzActOrderCyDetail;
import thyyxxk.webserver.entity.zhuyuanyisheng.caoyaoyizhu.YzOrderPatternCy;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.YiZhuMingChen;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 描述：
 * </p>
 *
 * @author xc
 * @date 2022-02-26 08:39
 */
@Service
@Slf4j
public class CaoYaoYiZhuServer {

    private final CaoYaoYiZhuDao dao;
    private final PublicServer publicServer;
    private final YiZhuLuRuDao yiZhuLuRuDao;

    public CaoYaoYiZhuServer(CaoYaoYiZhuDao dao, PublicServer publicServer, YiZhuLuRuDao yiZhuLuRuDao) {
        this.dao = dao;
        this.publicServer = publicServer;
        this.yiZhuLuRuDao = yiZhuLuRuDao;
    }

    public ResultVo<IPage<YzActOrderCy>> huoQuCaoYaoShuJu(CaoYaoChaXunTiaoJian param) {
        IPage<YzActOrderCy> page = new Page<>(param.getCurrentPage(), param.getPageSize(), param.getTotal() == 0);
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.eq("inpatient_no", param.getPatNo());
        qw.eq("admiss_times", param.getTimes());
        if (param.getShiFouFaYao()) {
            qw.eq("status_flag", "4");
        } else {
            qw.le("status_flag", "3");
        }
        if (StringUtil.notBlank(param.getStartTime())) {
            qw.ge("input_date", param.getStartTime());
            qw.le("input_date", param.getEndTime());
        }
        dao.huoQuCaoYaoShuJu(page, qw);
        for (YzActOrderCy item : page.getRecords()) {
            item.setDaiJianFei(item.getQuantityDj().multiply(item.getOrderJeDj()));
            item.setJiaGe(item.getQuantity().multiply(item.getOrderJe()));
            item.setZongJia(item.getDaiJianFei().add(item.getJiaGe()));
        }
        return ResultVoUtil.success(page);
    }

    public ResultVo<List<YzActOrderCyDetail>> huoQuChaoYaoMingXi(BigDecimal orderNo) {
        return ResultVoUtil.success(dao.huoQuChaoYaoMingXi(orderNo));
    }

    public ResultVo<List<GetDropdownBox>> fuYongFangFa() {
        return ResultVoUtil.success(dao.fuYongFangFa());
    }

    public ResultVo<IPage<YiZhuMingChen>> huoQuCaoYao(String queryName, Integer groupNo, long currentPage, long pageSize, long total) {
        IPage<YiZhuMingChen> page = new Page<>(currentPage, pageSize, total == 0);
        String name = StringUtil.englishToCapital(queryName);
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.and(QueryWrapper -> QueryWrapper
                        .like("py_code", name)
                        .or()
                        .like("name", name)
                        .or()
                        .like("d_code", name)
                        .or()
                        .like("code", name)
                )
                .eq("group_no", groupNo);
        dao.huoQuCaoYao(page, qw);
        return ResultVoUtil.success(page);
    }


    public ResultVo<IPage<YzOrderPatternCy>> huoQuMuBan(String queryName, String deptCode, long currentPage, long pageSize, long total) {
        IPage<YzOrderPatternCy> page = new Page<>(currentPage, pageSize, total == 0);
        String name = StringUtil.englishToCapital(queryName);
        QueryWrapper<?> qw = new QueryWrapper<>();
        qw.and(QueryWrapper -> QueryWrapper
                .like("py_code", name)
                .or()
                .like("d_code", name)
                .or()
                .like("pattern_name", name)
        );
        if (publicServer.noNeedRule(1, 38)) {
            qw.eq("dept_code", deptCode);
        }
        qw.groupBy("pattern_name");
        dao.huoQuMuBan(page, qw);
        return ResultVoUtil.success(page);
    }

    public ResultVo<List<YzOrderPatternCy>> muBanXiangQing(String name, String deptCode) {
        return ResultVoUtil.success(dao.muBanXiangQing(name, deptCode));
    }

    public ResultVo<Boolean> chongFuMuBanMing(String name) {
        return ResultVoUtil.success(dao.chongFuMuBanMing(name) > 1);
    }

    public ResultVo<String> cunMuBan(YzOrderPatternCy param) {
        log.info("插入模板草药模板：{}", JSON.toJSONString(param));

        dao.chaRuMuBan(param.getList(), param.getPatternName(), TokenUtil.getTokenUserId(),
                PingYinUtils.pyShouZiMuDaXie(param.getPatternName()), PingYinUtils.getWBCode(param.getPatternName()),
                param.getDeptCode());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    public ResultVo<String> baoCunCaoYao(YzActOrderCy param) {
        log.info("上传的数据：{}", JSON.toJSONString(param));
        if (ListUtil.isBlank(param.getList())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请先选择需要上传的数据。");
        }
        publicServer.huanZheJieSuan(param.getInpatientNo(), param.getAdmissTimes());
        BigDecimal sum = new BigDecimal(0);
        for (YzActOrderCyDetail item : param.getList()) {
            sum = sum.add(item.getQuantity().multiply(item.getRetprice()));
        }
        param.setOrderJe(sum);
        param.setInputId(TokenUtil.getTokenUserId());
        param.setOrderJeDj(dao.huoQuDaiJianFei());
        param.setPageNo(publicServer.getTheDrugListNo());
        XinZhenYiZhu huanZheXinXi = yiZhuLuRuDao.huoQuHuanZheXinXi(param.getInpatientNo(), param.getAdmissTimes());
        param.setOrderNo(BigDecimal.valueOf(publicServer.getActOrderNo()));
        dao.chaRuCaoYaoYiZhu(param, huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(), huanZheXinXi.getSmallDept());
        dao.chaRuCaoYaoXiangQing(param.getList(), param.getOrderNo());
        dao.chaRuYiZhu(param, "草药医嘱:" + param.getOrderName() + param.getQuantity() + "剂", huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(), huanZheXinXi.getSmallDept(), publicServer.getInfantFlag(huanZheXinXi.getInpatientNo()));
        List<String> content = new ArrayList<>();
        content.add(String.format("草药医嘱名：<span style='color:#409eff'>【%s】</span><br>" +
                "剂数：<span style='color:#409eff'>【%s】</span><br>" +
                "患者名：<span style='color:#409eff'>【%s】<br></span>" +
                "床位：<span style='color:#409eff'>【%s】</span>", param.getOrderName(), param.getQuantity().toString(), huanZheXinXi.getName(), huanZheXinXi.getBedNo()));
        publicServer.faSongXiaoXi(huanZheXinXi, content, "新增草药医嘱", TokenUtil.getTokenUserId());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    /**
     * 删除草药模板
     * 管理员和有医嘱模板编辑，权限的可以直接删除
     * 科室主任有权限删除本科室的模板
     *
     * @param name     模板名称
     * @param deptCode 科室编码
     * @return 返回提示
     */
    public ResultVo<String> shanChuMuBan(String name, String deptCode) {
        YzOrderPatternCy mb = dao.caoYaoMuBanXiangQing(name);
        List<Integer> rolse = publicServer.getRoleCode().getData();
        // 如果有这个权限直接删除
        if (publicServer.noNeedRule(rolse, YiZhuPublic.MU_BAN_BIAN_JI_QUAN_XIAN)) {
            // 本人创建的也可以直接删除
            if (mb.getCreateId().equals(TokenUtil.getTokenUserId())) {
                return shanChuCaoYaoMuBan(name);
            }
            // 科主任 可以删除自己科室的模板
            if (publicServer.needRule(rolse, YiZhuPublic.KE_ZHU_REN_BIAN_MA)) {
                if (mb.getDeptCode().trim().equals(deptCode)) {
                    return shanChuCaoYaoMuBan(name);
                }
            }
        } else {
            return shanChuCaoYaoMuBan(name);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有权限删除。");
    }

    private ResultVo<String> shanChuCaoYaoMuBan(String name) {
        dao.shanChuMuBan(name);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

    public ResultVo<String> shanChuCaoYao(String patNo, Integer times, BigDecimal orderNo) {
        YzActOrderCy cy = dao.caoYaoXinXi(patNo, times, orderNo);
        if (cy == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有查询到原来的信息。");
        }
        if (!cy.getStatusFlag().trim().equals("1")) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "该草药无法删除。");
        }
        log.info("删除草药==》操作人：{}，数据：{}", TokenUtil.getTokenUserId(), JSON.toJSONStringWithDateFormat(cy, GetDateFormat.DATE_TIME));
        dao.genXingCaoYaoShanChuBiaoZhi(patNo, times, orderNo);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }

}
