package thyyxxk.webserver.service.zhuyuanyisheng;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtflys.forest.annotation.LogHandler;
import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
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.ShouShuShenQingDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.YiZhuLuRuDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.zhuyuanyisheng.query.ChaXunJianChaHeJianYan;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.OpRecord;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.ShouShuFanHui;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.XinZengShouShu;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.*;

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

/**
 * <p>
 * 描述： 手术申请
 * </p>
 *
 * @author xc
 * @date 2022-02-22 15:45
 */
@Service
@Slf4j
public class ShouShuShenQingServer {
    private final ShouShuShenQingDao dao;
    private final PublicServer publicServer;
    private final YiZhuLuRuDao yiZhuLuRuDao;

    public ShouShuShenQingServer(ShouShuShenQingDao dao, PublicServer publicServer, YiZhuLuRuDao yiZhuLuRuDao) {
        this.dao = dao;
        this.publicServer = publicServer;
        this.yiZhuLuRuDao = yiZhuLuRuDao;
    }

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

    public ResultVo<List<Map<String, String>>> huoQuShouShuMingCheng(String patNo, Integer times, String name) {
        return ResultVoUtil.success(dao.huoQuShouShuMing(patNo, times, StringUtil.isContainChinese(name)));
    }

    public ResultVo<IPage<OpRecord>> huoQuShouShu(ChaXunJianChaHeJianYan param) {
        IPage<OpRecord> page = new Page<>(param.getCurrentPage(), param.getPageSize(), param.getTotal() == 0);
        QueryWrapper<OpRecord> qw = new QueryWrapper<>();
        qw.select("op_name, op_datetime, status,record_id");
        qw.eq("inpatient_no", param.getPatNo());
        qw.eq("admiss_times", param.getTimes());
        if (StringUtil.notBlank(param.getStartTime())) {
            qw.ge("req_date", param.getStartTime());
            qw.le("req_date", param.getEndTime());
        }
        if (StringUtil.notBlank(param.getOrderName())) {
            qw.eq("op_name", param.getOrderName());
        }
        qw.ne("status", "d");
        dao.selectPage(page, qw);
        return ResultVoUtil.success(page);
    }

    public ResultVo<OpRecord> huoQuShouShuShenQingDaYing(String patNo, Integer times, Integer recordId) {
        OpRecord op = dao.daYingShouShu(patNo, times, recordId);
        if (op == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "该手术可能已经被删除了。");
        }

        try {
            EntityCopy.Copy(dao.daYingHuanZheXinXi(patNo, times), op);
        } catch (Exception e) {
            e.printStackTrace();
        }
        op.setAge(DateUtil.calculateAge(DateUtil.parse(op.getBirthDate(), GetDateFormat.DATE), null).toString());
        return ResultVoUtil.success(op);
    }

    public ResultVo<IPage<ShouShuFanHui>> fenLeiXiangQing(String code, String name, long total, long currentPage, long pageSize) {
        IPage<ShouShuFanHui> page = new Page<>(currentPage, pageSize, total == 0);
        page = dao.fenLeiXiangQing(page, code, StringUtil.isContainChinese(name));
        return ResultVoUtil.success(page);
    }

    /**
     * 远程搜索手术部位
     *
     * @param name 名字
     * @return 返回
     */
    @DS("his")
    public ResultVo<List<GetDropdownBox>> huoQuShouShuBuWei(String name) {
        return ResultVoUtil.success(dao.huoQuShouShuBuWei(StringUtil.isContainChinese(name)));
    }

    public ResultVo<String> xinZengShouShuShenQing(XinZengShouShu param) {
        log.info("上传数据：{}", JSON.toJSONString(param));
        if (ListUtil.isBlank(param.getList())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请先选择需要上传的数据。");
        }
        publicServer.huanZheJieSuan(param.getInpatientNo(), param.getAdmissTimes());
        String userCode = TokenUtil.getTokenUserId();
        Integer shenQingCiShu = dao.shouShuShenQingCiShu(param.getInpatientNo(), param.getAdmissTimes());
        List<OpRecord> shenChengYiZhu = new ArrayList<>();
        List<String> content = new ArrayList<>();
        for (OpRecord item : param.getList()) {
            item.setRecordId(publicServer.huoQuShouShuHao());
            item.setActOrderNo(BigDecimal.valueOf(publicServer.getActOrderNo()));
            item.setOpTimes(shenQingCiShu += 1);
            // 是否生成医嘱
            if (item.getSsyzFlag().equals("1")) {
                shenChengYiZhu.add(item);
            }
            content.add(String.format("手术名称：<span style='color:#409eff'>【%s】</span><br>" +
                    "手术时间：<span style='color:#409eff'>【%tF %<tT】</span><br>", item.getOpName(), item.getOpDatetime()));
        }
        XinZhenYiZhu huanZheXinXi = yiZhuLuRuDao.huoQuHuanZheXinXi(param.getInpatientNo(), param.getAdmissTimes());
        dao.chaRuShouShuYiSheng(param.getList());
        dao.chaRuShouShu(param.getList(), param.getInpatientNo(), param.getName(), param.getAdmissTimes(),
                huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(), userCode, param.getBedNo(), param.getAdmissWard());

        if (ListUtil.notBlank(shenChengYiZhu)) {
            dao.chaRuYiZhu(shenChengYiZhu, publicServer.getInfantFlag(param.getInpatientNo()),
                    userCode, param.getInpatientNo(), param.getAdmissTimes(), huanZheXinXi.getDeptCode(), huanZheXinXi.getDeptCode(), param.getExecDept());
        }
        publicServer.faSongXiaoXi(huanZheXinXi, content, "新增手术", TokenUtil.getTokenUserId());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }


    public ResultVo<String> shanChuShouShu(Integer recordId) {
        OpRecord op = dao.shouShuXinXi(recordId);
        if (op == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到该手术的信息。");
        }
        if (!op.getStatus().trim().equals("1")) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "无法删除该手术。");
        }
        dao.genXingShanChuBiaoZhi(recordId);
        log.info("删除手术==》操作人：{}，申请单号：{}", TokenUtil.getTokenUserId(), recordId);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }


    public ResultVo<String> addASurgicalSite(String name) {
        if (dao.repeatPartName(name)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "手术部位名称重复");
        }
        String maxCode = String.valueOf(dao.getTheMaximumSurgicalCode() + 1);
        String newCode = maxCode.length() > 1 ? maxCode : '0' + maxCode;
        dao.insertNewSurgicalSite(newCode, name, PingYinUtils.pyShouZiMuDaXie(name), PingYinUtils.getWBCode(name));
        log.info("新增手术部位==>操作人:{}", TokenUtil.getTokenUserId());
        return ResultVoUtil.success(newCode);
    }

    public ResultVo<String> removeSurgicalSite(String code) {
        dao.removeSurgicalSite(code);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION);
    }
}
