package thyyxxk.webserver.service.medicalinsurance;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.SystemConfig;
import thyyxxk.webserver.constants.sidicts.MedType;
import thyyxxk.webserver.dao.his.medicalinsurance.SiWorkLogDao;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.medicalinsurance.inpatient.SiAdmissApply;
import thyyxxk.webserver.entity.medicalinsurance.inpatient.settleapply.response.SiSettleApply;
import thyyxxk.webserver.entity.medicalinsurance.setlinfo.SiSetlinfo;
import thyyxxk.webserver.entity.medicalinsurance.worklog.MatchWorkLog;
import thyyxxk.webserver.entity.medicalinsurance.worklog.WorkLog;
import thyyxxk.webserver.entity.medicalinsurance.worklog.WorkLogInquiry;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.DateUtil;

import java.util.ArrayList;
import java.util.List;

@Service
public class SiWorkLogService {
    private final SiWorkLogDao dao;
    private final String medinsurDept;
    private final UserCache userCache;

    @Autowired
    public SiWorkLogService(SiWorkLogDao dao, SystemConfig config, UserCache userCache) {
        this.dao = dao;
        this.medinsurDept = config.getMedinsurDept();
        this.userCache = userCache;
    }

    public List<UserInfo> getYbkStaff() {
        return dao.getYbkStaff(medinsurDept);
    }

    public List<WorkLog> getWorkLog(WorkLogInquiry inquiry) {
        makeStaffStatement(inquiry);
        switch (inquiry.getType()) {
            case MZ_SETTLE:
                return getMzSetlWorkLog(inquiry);
            case SI_MATCH:
                return getSiMatchWorkLog(inquiry);
            case ADM_VERIFY:
                return getAdmVerifyWorkLog(inquiry);
            case DIS_VERIFY:
                return getDisVerifyWorkLog(inquiry);
            case ALL:
            default:
                return getAllWorkLog(inquiry);
        }
    }

    private void makeStaffStatement(WorkLogInquiry inquiry) {
        if (StrUtil.isBlank(inquiry.getStaff())) {
            List<UserInfo> userList = getYbkStaff();
            StringBuilder builder = new StringBuilder();
            for (UserInfo user : userList) {
                builder.append(",").append(user.getCode());
            }
            if (builder.length() > 1) {
                inquiry.setStaff(builder.substring(1));
            }
        }
        if (StrUtil.isNotBlank(inquiry.getStaff())) {
            String staffRaw =  inquiry.getStaff();
            String[] staff = staffRaw.split(",");
            StringBuilder statement = new StringBuilder("(");
            for (String staffId : staff) {
                statement.append("'").append(staffId).append("',");
            }
            statement.deleteCharAt(statement.length() - 1);
            statement.append(")");
            inquiry.setStaff(statement.toString());
        }
    }

    private void makeGsTimeStatement(WorkLogInquiry inquiry) {
        String start = inquiry.getStart();
        String gsStart = start
                .replaceAll("-", "")
                .replaceAll(":", "")
                .replaceAll(" ", "");
        String end = inquiry.getEnd();
        String gsEnd = end
                .replaceAll("-", "")
                .replaceAll(":", "")
                .replaceAll(" ", "");
        inquiry.setGsStart(gsStart);
        inquiry.setGsEnd(gsEnd);
    }

    private List<WorkLog> getMzSetlWorkLog(WorkLogInquiry inquiry) {
        makeGsTimeStatement(inquiry);
        List<WorkLog> result = new ArrayList<>();
        List<SiSetlinfo> mzList = dao.getMzSetlinfo(inquiry);
        for (SiSetlinfo mz : mzList) {
            WorkLog workLog = new WorkLog();
            workLog.setStaffId(mz.getStaffId());
            workLog.setStaffName(userCache.getEmployeeName(mz.getStaffId()));
            workLog.setWorkType("门诊结算");
            workLog.setWorkContent("门诊医保结算。医疗类别：" + MedType.getName(mz.getMedType()) +
                    "；门诊ID：" + mz.getPatNo() + "；医保就诊ID：" + mz.getMdtrtId() +
                    "；医保结算ID：" + mz.getSetlId());
            workLog.setWorkTime(mz.getSetlTime());
            result.add(workLog);
        }
        List<SiSetlinfo> gsList = dao.getGsSetlinfo(inquiry);
        for (SiSetlinfo gs : gsList) {
            WorkLog workLog = new WorkLog();
            workLog.setStaffId(gs.getStaffId());
            workLog.setStaffName(userCache.getEmployeeName(gs.getStaffId()));
            workLog.setWorkType("门诊结算");
            workLog.setWorkContent("门诊工伤结算。医疗类别：" + MedType.getName(gs.getMedType()) +
                    "；门诊ID：" + gs.getPatNo() + "；医保就诊ID：" + gs.getMdtrtId() +
                    "；医保结算ID：" + gs.getSetlId());
            workLog.setWorkTime(DateUtil.parse(gs.getAae036(), "yyyyMMddHHmmss"));
            result.add(workLog);
        }
        return result;
    }

    private List<WorkLog> getSiMatchWorkLog(WorkLogInquiry inquiry) {
        List<WorkLog> result = new ArrayList<>();
        List<MatchWorkLog> list = dao.getMatchLog(inquiry);
        for (MatchWorkLog log : list) {
            WorkLog workLog = new WorkLog();
            workLog.setWorkTime(log.getOpTime());
            workLog.setWorkType("医保匹配");
            workLog.setStaffId(log.getOpStaff());
            workLog.setStaffName(userCache.getEmployeeName(log.getOpStaff()));
            String content = log.getYbTypeName() + log.getOpTypeName();
            content = content + "。HIS编码：" + log.getCode() + "；HIS名称：" + log.getName() +
                    "；医保编码：" + log.getNationalCode() + "；医保名称：" + log.getNationalName();
            workLog.setWorkContent(content);
            result.add(workLog);
        }
        return result;
    }

    private List<WorkLog> getAdmVerifyWorkLog(WorkLogInquiry inquiry) {
        List<WorkLog> result = new ArrayList<>();
        List<SiAdmissApply> list = dao.getAdmApply(inquiry);
        for (SiAdmissApply apply : list) {
            WorkLog workLog = new WorkLog();
            workLog.setWorkType("入院审核");
            workLog.setWorkTime(apply.getHandleDatetime());
            workLog.setStaffId(apply.getHandleStaff());
            workLog.setStaffName(userCache.getEmployeeName(apply.getHandleStaff()));
            workLog.setWorkContent("入院审核。住院号：" + apply.getPatNo() + "；住院次数：" + apply.getTimes() +
                    "；处理意见：" + apply.getHandleComment());
            result.add(workLog);
        }
        return result;
    }

    private List<WorkLog> getDisVerifyWorkLog(WorkLogInquiry inquiry) {
        List<WorkLog> result = new ArrayList<>();
        List<SiSettleApply> list = dao.getDisApply(inquiry);
        for (SiSettleApply apply : list) {
            WorkLog workLog = new WorkLog();
            workLog.setWorkType("出院审核");
            workLog.setWorkTime(apply.getHandleDatetime());
            workLog.setStaffId(apply.getHandleStaff());
            workLog.setStaffName(userCache.getEmployeeName(apply.getHandleStaff()));
            String typeName = apply.getType() == 1 ? "出院结算审核。" : "中间断账审核。";
            workLog.setWorkContent(typeName + "住院号：" + apply.getPatNo() + "；住院次数：" + apply.getTimes() +
                    "；处理意见：" + apply.getHandleComment());
            result.add(workLog);
        }
        return result;
    }

    private List<WorkLog> getAllWorkLog(WorkLogInquiry inquiry) {
        List<WorkLog> result = new ArrayList<>();
        result.addAll(getMzSetlWorkLog(inquiry));
        result.addAll(getSiMatchWorkLog(inquiry));
        result.addAll(getAdmVerifyWorkLog(inquiry));
        result.addAll(getDisVerifyWorkLog(inquiry));
        return result;
    }
}
