package thyyxxk.webserver.api.forpowersi;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.dao.his.api.forpowersi.drgdip.DrgDipDao;
import thyyxxk.webserver.entity.api.forpowersi.drgdip.*;
import thyyxxk.webserver.entity.api.forpowersi.drgdip.statement.*;
import thyyxxk.webserver.service.hutoolcache.DeptCache;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.EntityStringTrim;
import thyyxxk.webserver.utils.IdCardUtil;
import thyyxxk.webserver.utils.StringUtil;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/forpowersi/drgdpi")
public class DrgDipController {
    private final UserCache userCache;
    private final DeptCache deptCache;
    private final DrgDipDao dao;

    private static final Integer NO_RECORD_EXIST = 0;

    private static final String IN_HOSPITAL_DOCTORS_ADVICE = "yz_act_order";

    private static final String OUT_HOSPITAL_DOCTORS_ADVICE = "yz_inact_order";

    @Autowired
    public DrgDipController(DrgDipDao dao, UserCache userCache, DeptCache deptCache) {
        this.dao = dao;
        this.userCache = userCache;
        this.deptCache = deptCache;
    }

    @PassToken
    @PostMapping("/executeQuery")
    public JSONObject executeQuery(@RequestBody RequestParams params) {
        DrgDipRequestType type = DrgDipRequestType.get(params.getType());
        if (null == type) {
            return DrgDipResponseFactory.wrongParameters("指标命名集不能为空。");
        }
        if (StringUtil.notBlank(params.getVisitId())) {
            String[] strArray = params.getVisitId().split("_");
            if (strArray.length < 3) {
                return DrgDipResponseFactory.wrongParameters("visitId格式错误，请检查。");
            }
            params.setSetlId(dao.getSetId(strArray[0], strArray[1], strArray[2]));
            params.setPatNo(strArray[0]);
            params.setTimes(Integer.parseInt(strArray[1]));
            params.setLedgerSn(Integer.parseInt(strArray[2]));
        }
        try {
            switch (type) {
                case HIS_BASE_DEPT_INFO:
                    return queryHisBaseDeptInfo(params);
                case HIS_BASE_EMP_INFO:
                    return queryHisBaseEmpInfo(params);
                case MI_INSUR_HOSP_DRUGS_REL:
                    return queryMiInsurHospDrugsRel(params);
                case MI_INSUR_HOSP_ITEMS_REL:
                    return queryMiInsurHospItemsRel(params);
                case HIS_BASE_MDCL_ITEMS_REL:
                    return queryHisBaseMdclItemsRel(params);
                case HIS_OUTP_SETTL_DATA:
                    return queryHisOutpSettlData(params);
                case HIS_OUTP_ADVICE:
                    return queryHisOutpAdvice(params);
                case HIS_OUTP_ADVICE_DETAIL:
                    return queryHisOutpAdviceDetail(params);
                case HIS_OUTP_CHARGE:
                    return queryHisOutpCharge(params);
                case HIS_HSPTZD_PATIENT_BASE:
                    return queryHisHsptzdPatientBase(params);
                case HIS_HSPTZD_PATIENT_BASE_CY:
                    return queryHisHsptzdPatientBaseCy(params);
                case HIS_BABY_INFO:
                    return queryHisBabyInfo(params);
                case HIS_HSPTZD_CHARGE:
                    return queryHisHsptzdCharge(params);
                case HIS_HSPTZD_MDCL_ADVICE:
                    return queryHisHsptzdMdclAdvice(params);
                case YIBAO_SETLINFO_2304:
                    return queryYibaoSetlinfo2304(params);
                case YIBAO_SETLDETAIL_2304:
                    return queryYibaoSetldetail2304(params);
                case YIBAO_5204:
                    return queryYibao5204(params);
                case HIS_PATIENT_DAGNS:
                    return queryHisPatientDagns(params);
                case HIS_PATIENT_OPRT_INFO:
                    return queryHisPatientOprtInfo(params);
                case YIBAO_N041:
                    return queryYibaoN041(params);
                case YIBAO_SETLINFO_4101A:
                    return queryYibaoSetlinfo4101a(params);
                case YIBAO_OPSPDISEINFO_4101A:
                    return queryYibaoOpspdiseinfo4101a(params);
                case YIBAO_DISEINFO_4101A:
                    return queryYibaoDiseinfo4101a(params);
                case YIBAO_OPRNINFO_4101A:
                    return queryYibaoOprninfo4101a(params);
                case YIBAO_ICUINFO_4101A:
                    return queryYibaoIcuinfo4101a(params);
                case YIBAO_BLDINFO_4101A:
                    return queryYibaoBldinfo4101a(params);
                case INVALID_REQUEST_TYPE:
                default:
                    return DrgDipResponseFactory.wrongParameters("无法识别的指标命名集。");
            }
        } catch (Exception e) {
            log.error("DRG/DIP查询出错", e);
            return DrgDipResponseFactory.serviceExecutionException(e.getLocalizedMessage());
        }
    }

    private JSONObject queryHisBaseDeptInfo(RequestParams params) {
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        List<HisBaseDeptInfo> list = dao.selectHisBaseDeptInfo(params.getPageNumber(), params.getPageSize());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisBaseEmpInfo(RequestParams params) {
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        List<HisBaseEmpInfo> list = dao.selectHisBaseEmpInfo(params.getPageNumber(), params.getPageSize());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryMiInsurHospDrugsRel(RequestParams params) {
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        List<MiInsurHospDrugsRel> list = dao.selectMiInsurHospDrugsRel(params.getPageNumber(), params.getPageSize());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryMiInsurHospItemsRel(RequestParams params) {
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        List<MiInsurHospItemsRel> list = dao.selectMiInsurHospItemsRel(params.getPageNumber(), params.getPageSize());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisBaseMdclItemsRel(RequestParams params) {
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        return DrgDipResponseFactory.noCorrespondingDataFound();
    }

    private JSONObject queryHisOutpSettlData(RequestParams params) {
        if ((null == params.getPageNumber() || null == params.getPageSize())
                && null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize、visitId 不能同时为空。");
        }
        List<HisOutpSettlData> list = null == params.getVisitId() ?
                dao.selectHisOutpSettlData(params.getPageNumber(), params.getPageSize())
                : dao.selectHisOutpSettlDataByVisitId(params.getSetlId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisOutpAdvice(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        return DrgDipResponseFactory.noCorrespondingDataFound();
    }

    private JSONObject queryHisOutpAdviceDetail(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<HisOutpAdviceDetail> list = dao.selectHisOutpAdviceDetail(params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisOutpCharge(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<HisOutpCharge> list = dao.selectHisOutpCharge(params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        list.forEach(item -> {
            item.setVisitDept(deptCache.get(item.getVisitDeptId()).getName());
        });
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisHsptzdPatientBase(RequestParams params) {
        if (null == params.getVisitId()) {
            List<VisitId> visitIdList = dao.selectAllHisHsptzdPatientBase();
            if (visitIdList.isEmpty()) {
                return DrgDipResponseFactory.noCorrespondingDataFound();
            }
            return DrgDipResponseFactory.success(visitIdList);
        }
        List<HisHsptzdPatientBase> list = dao.selectHisHsptzdPatientBaseInHosp(
                params.getPatNo(), params.getTimes(), params.getLedgerSn());
        if (list.isEmpty()) {
            list = dao.selectHisHsptzdPatientBaseOutHosp(params.getPatNo(), params.getTimes(), params.getLedgerSn());
            if (list.isEmpty()) {
                return DrgDipResponseFactory.noCorrespondingDataFound();
            }
        }
        list.forEach(item -> {
            if (IdCardUtil.isValidatedIdCard(item.getIdCard())) {
                item.setAge(String.valueOf(IdCardUtil.getAgeByIdCard(item.getIdCard())));
            }
            item.setVisitDept(deptCache.get(item.getVisitDeptId()).getName());
            item.setTbDoctor(userCache.getEmployeeName(item.getTbDoctorId()));
            item.setHospDischDept(deptCache.get(item.getHospDischDeptId()).getName());
        });
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisHsptzdPatientBaseCy(RequestParams params) {
        if (null == params.getStartDate() || null == params.getEndDate()) {
            return DrgDipResponseFactory.wrongParameters("startDate、endDate不能为空。");
        }
        List<VisitId> visitIdList = dao.selectHisHsptzdPatientBaseByDateRange(params.getStartDate(), params.getEndDate());
        if (visitIdList.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(visitIdList);
    }

    private JSONObject queryHisBabyInfo(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<HisBabyInfo> list = dao.selectHisBabyInfo(params.getPatNo(), params.getTimes(), params.getLedgerSn());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisHsptzdCharge(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        if (null == params.getPageNumber() || null == params.getPageSize()) {
            return DrgDipResponseFactory.wrongParameters("pageNumber、pageSize不能为空。");
        }
        if (params.getPageSize() > 1000) {
            return DrgDipResponseFactory.wrongParameters("pageSize允许的最大值为【1000】。");
        }
        List<HisHsptzdCharge> list = dao.selectHisHsptzdCharge(params.getPatNo(), params.getTimes(),
                params.getLedgerSn(), params.getPageNumber(), params.getPageSize());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        list.forEach(item -> {
            item.setVisitDept(deptCache.get(item.getVisitDeptId()).getName());
            if (StringUtil.isBlank(item.getExecDeptId())) {
                item.setExecDeptId(item.getPrescrDeptId());
                item.setExecDept(item.getPrescrDept());
            }
        });
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisHsptzdMdclAdvice(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        int inHospCount = dao.selectInHospCount(params.getPatNo(), params.getTimes());
        String table = inHospCount == NO_RECORD_EXIST ?
                OUT_HOSPITAL_DOCTORS_ADVICE : IN_HOSPITAL_DOCTORS_ADVICE;
        List<HisHsptzdMdclAdvice> list = dao.selectHisHsptzdMdclAdvice(
                params.getPatNo(), params.getTimes(), table, params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoSetlinfo2304(RequestParams params) {
        if (null == params.getVisitId()) {
            if (null == params.getStartDate() || null == params.getEndDate()) {
                return DrgDipResponseFactory.wrongParameters("startDate、endDate、visitId不能同时为空。");
            }
            List<YibaoSetlinfo2304Brief> briefList = dao.selectSetlBrief(params.getStartDate(), params.getEndDate());
            if (briefList.isEmpty()) {
                return DrgDipResponseFactory.noCorrespondingDataFound();
            }
            return DrgDipResponseFactory.success(briefList);
        }
        List<YibaoSetlinfo2304> list = dao.selectYibaoSetlinfo2304(params.getSetlId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoSetldetail2304(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoSetldetail2304> list = dao.selectYibaoSetldetail2304(params.getSetlId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibao5204(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<Yibao5204> list = dao.selectYibao5204(params.getSetlId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryHisPatientDagns(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<HisPatientDagns> admList = dao.selectHisPatientAdmDagns(params.getPatNo(), params.getTimes());
        List<HisPatientDagns> disList = dao.selectHisPatientDisDangs(params.getPatNo(), params.getTimes());
        if (admList.isEmpty() && disList.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        if (admList.isEmpty()) {
            return DrgDipResponseFactory.success(accomplishDagns(disList, params.getVisitId()));
        }
        if (disList.isEmpty()) {
            return DrgDipResponseFactory.success(accomplishDagns(admList, params.getVisitId()));
        }
        admList.get(0).setDagnsTypeId("2");
        admList.addAll(disList);
        return DrgDipResponseFactory.success(accomplishDagns(admList, params.getVisitId()));
    }

    private List<HisPatientDagns> accomplishDagns(List<HisPatientDagns> dangsList, String visitId) {
        for (int i = 0; i < dangsList.size(); i++) {
            HisPatientDagns dagns = dangsList.get(i);
            dagns.setVisitId(visitId);
            dagns.setOrder(i + 1);
        }
        return dangsList;
    }

    private JSONObject queryHisPatientOprtInfo(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<HisPatientOprtInfo> list = dao.selectHisPatientOprtInfo(params.getPatNo(), params.getTimes());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        list.forEach(item -> item.setVisitId(params.getVisitId()));
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoN041(RequestParams params) {
        if (null == params.getVisitId()) {
            if (null == params.getStartDate() || null == params.getEndDate()) {
                return DrgDipResponseFactory.wrongParameters("startDate、endDate、visitId不能同时为空。");
            }
            List<VisitId> visitIdList = dao.selectSignedVisitId(params.getStartDate(), params.getEndDate());
            if (visitIdList.isEmpty()) {
                return DrgDipResponseFactory.noCorrespondingDataFound();
            }
            return DrgDipResponseFactory.success(visitIdList);
        }
        List<YibaoN041> list = dao.selectYibaoN041(params.getPatNo(), params.getTimes());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        YibaoN041 yibaoN041 = list.get(0);
        yibaoN041.setVisitId(params.getVisitId());
        List<YibaoN041DiagItem> diagList = dao.selectYibaoN041Diags(params.getPatNo(), params.getTimes());
        for (int i = 0; i < diagList.size(); i++) {
            yibaoN041.setOthDiagItem(i, diagList.get(i));
        }
        List<YibaoN041SurgeryItem> surgeryList = dao.selectYibaoN041Surgeries(params.getPatNo(), params.getTimes());
        for (int i = 0; i < surgeryList.size(); i++) {
            yibaoN041.setOthSurgeryItem(i, surgeryList.get(i));
        }
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoSetlinfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            if (null == params.getStartDate() || null == params.getEndDate()) {
                return DrgDipResponseFactory.wrongParameters("startDate、endDate、visitId不能同时为空。");
            }
            List<VisitId> visitIdList = dao.getSettlementDocumentVisitID(params.getStartDate(), params.getEndDate());
            if (visitIdList.isEmpty()) {
                return DrgDipResponseFactory.noCorrespondingDataFound();
            }
            return DrgDipResponseFactory.success(visitIdList);
        }
        List<YibaoSetlinfo4101a> info = dao.basicPatientInfoOfStatement(params.getSetlId(), params.getVisitId());
        EntityStringTrim.beanAttributeValueTrimList(info);

        if (info == null) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        return DrgDipResponseFactory.success(info);
    }

    private JSONObject queryYibaoOpspdiseinfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoOpspdiseinfo4101a> list = dao.getOpspdiseinfoBySetlId(params.getSetlId(), params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        EntityStringTrim.beanAttributeValueTrimList(list);
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoDiseinfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoDiseinfo4101a> list = dao.getDiseinfoBySetlId(params.getSetlId(), params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        EntityStringTrim.beanAttributeValueTrimList(list);
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoOprninfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoOprninfo4101a> list = dao.getOprninfoBySetlId(params.getSetlId(), params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        EntityStringTrim.beanAttributeValueTrimList(list);
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoIcuinfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoIcuinfo4101a> list = dao.getIcoInfoBySetlId(params.getSetlId(), params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        EntityStringTrim.beanAttributeValueTrimList(list);
        return DrgDipResponseFactory.success(list);
    }

    private JSONObject queryYibaoBldinfo4101a(RequestParams params) {
        if (null == params.getVisitId()) {
            return DrgDipResponseFactory.wrongParameters("visitId不能为空。");
        }
        List<YibaoBldinfo4101a> list = dao.getBldinfoBySetlId(params.getSetlId(), params.getVisitId());
        if (list.isEmpty()) {
            return DrgDipResponseFactory.noCorrespondingDataFound();
        }
        EntityStringTrim.beanAttributeValueTrimList(list);
        return DrgDipResponseFactory.success(list);
    }
}
