package thyyxxk.webserver.service.zhuyuanyisheng.emr;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.emr.EmrAuditDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.zhuyuanyisheng.emr.EmrAuditDetail;
import thyyxxk.webserver.entity.zhuyuanyisheng.emr.EmrSetAudit;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.*;

@Service
@Slf4j
public class EmrAuditServer {
    private final EmrAuditDao dao;
    private final PublicServer publicServer;

    public EmrAuditServer(EmrAuditDao dao, PublicServer publicServer) {
        this.dao = dao;
        this.publicServer = publicServer;
    }

    public ResultVo<String> setAudit(EmrSetAudit data) {
        if (ListUtil.isBlank(data.getList())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请选择质控数据");
        }
        String userCode = TokenUtil.getInstance().getTokenUserId();
        // 防止有重复的审核项目
        Set<String> auditSet = new HashSet<>();
        Date now = new Date();
        data.getList().forEach(item -> {
            auditSet.add(item.getName());
            item.setApprover(userCode)
                    .setFinalControl(data.getFinalControl())
                    .setReviewTime(now);
        });

        if (auditSet.size() != data.getList().size()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请勿添加重复审核项目。");
        }
        ListUtil.batchList(data.getList(), EmrAuditDao.class, (mapper, item) -> {
            mapper.insertAudit(data.getPatNo(), data.getTimes(), data.getId(), data.getDoctor(), data.getLevel(), item);
        });

        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<String> rectifyMedicalRecords(Integer id, Integer state) {
        dao.rectifyMedicalRecords(id, state, TokenUtil.getInstance().getTokenUserId(), new Date());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<Map<Date, List<EmrAuditDetail>>> getHistoricalAudit(Integer emrId, Integer finalControl) {
        List<EmrAuditDetail> historicalData = dao.getHistoricalAudit(emrId);
        if (finalControl == 1) {
            historicalData.addAll(dao.getLinkQualityControl(emrId));
        }
        Map<Date, List<EmrAuditDetail>> map = new TreeMap<>(Comparator.reverseOrder());
        for (EmrAuditDetail item : historicalData) {
            Date key = item.getReviewTime();
            if (map.containsKey(key)) {
                List<EmrAuditDetail> list = map.get(key);
                list.add(item);
                map.replace(key, list);
            } else {
                List<EmrAuditDetail> list = new ArrayList<>();
                list.add(item);
                map.put(key, list);
            }
        }
        return ResultVoUtil.success(map);
    }

    public ResultVo<String> updateFinalControl(String patNo, Integer times) {
        dao.updateFinalControl(patNo, times);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<String> updateControlLevel(String patNo, Integer times, Integer bazl) {
        // 病案签收就不能改了
        if (dao.whetherToSignForTheMedicalRecord(patNo, times) > 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "病案已签收，无法修改病案质量。");
        }
        dao.updateControlLevel(patNo, times, bazl, TokenUtil.getInstance().getTokenUserId());
        log.info("病案质量：{}，质控医生：{}", bazl, TokenUtil.getInstance().getTokenUserId());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<List<EmrAuditDetail>> getEmrAuditByEmrId(EmrAuditDetail params) {
        QueryWrapper<EmrAuditDetail> qw = new QueryWrapper<>();
        qw.select(
                "approver",
                "review_time",
                "id",
                "number_of_defects",
                "name",
                "scoring_criteria",
                "remark",
                "remediation_status",
                "approverName = (select rtrim(name) from a_employee_mi where code = approver)",
                "history",
                "modify_person",
                "modifyPersonName = (select rtrim(name) from a_employee_mi where code = modify_person)",
                "modification_time",
                "level",
                "minus_points"
        );
        qw.eq("emr_id", params.getEmrId());
        qw.eq("pat_no", params.getPatNo());
        qw.eq("times", params.getTimes());
        qw.eq("history", 0);
        qw.eq("final_control", params.getFinalControl());
        return ResultVoUtil.success(dao.selectList(qw));
    }


    public ResultVo<String> deleteEmrAuditByEmrId(String id) {
        EmrAuditDetail emrAuditDetail = dao.selectById(id);
        if (publicServer.needRule(78) || emrAuditDetail.getApprover().equals(TokenUtil.getInstance().getTokenUserId())) {
            dao.deleteById(id);
            return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
        }
        return ResultVoUtil.fail(ExceptionEnum.ERROR_MESSAGE, "您没有权限删除");

    }


}
