package thyyxxk.webserver.service.inpatient.casefrontsheet;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.config.Assertion;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.inpatient.casefrontsheet.JieShouHuiZhenDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.casefrontsheet.JieShouHuiZhenPojo;
import thyyxxk.webserver.entity.executeItem.YzZyPatientFee;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.*;

import java.util.List;
import java.util.Set;

/**
 * <p style="color: red">
 * 描述： 接受会诊申请
 * </p>
 *
 * @author xc
 * @date 2021-07-27 10:29
 */
@Service
@Slf4j
public class JieShouHuiZhenService implements Assertion {

    private final JieShouHuiZhenDao dao;
    private final PublicServer publicServer;
    private final UserCache userCache;

    public static final String 主任编码 = "01425";
    public static final String 副主任编码 = "01426";
    public static final String 主治编码 = "01427";

    @Autowired
    public JieShouHuiZhenService(JieShouHuiZhenDao dao, PublicServer publicServer, UserCache userCache) {
        this.dao = dao;
        this.publicServer = publicServer;
        this.userCache = userCache;
    }

    /**
     * @param startTime 开始时间
     * @param endTime   接受时间
     * @return 返回没有会诊的信息
     */
    public ResultVo<List<JieShouHuiZhenPojo>> getHuiZhenData(String startTime, String endTime, boolean history) {
        Set<String> deptList = publicServer.getChildDeptByUserCode();
        QueryWrapper<?> qw = new QueryWrapper<>();

        String dateName = "a.req_date";
        if (history) {
            qw.eq("a.status_flag", "2");
            dateName = "a.hz_date";
        } else {
            qw.eq("a.status_flag", "1");
        }

        if (StringUtil.notBlank(startTime)) {
            qw.gt(dateName, startTime)
                    .le(dateName, endTime);
        }

        if (publicServer.noNeedRule()) {
            qw.in("a.req_dept1", deptList);
        }

        return ResultVoUtil.success(dao.getHuiZhenData(qw));
    }

    /**
     * @param deptCode 根据科室的编码来获取 科室的名字
     * @return 返回科室名字
     */
    public ResultVo<String> getDeptName(String deptCode) {
        return ResultVoUtil.success(dao.getDeptName(deptCode));
    }

    /**
     * @param admissTimes 住院次数
     * @param reqTimes    申请次数
     * @param inpatientNo 住院号
     * @return 返回具体信息
     */
    public ResultVo<JieShouHuiZhenPojo> getHuanZheXinXi(Integer admissTimes, Integer reqTimes, String inpatientNo) {
        JieShouHuiZhenPojo pojo = dao.getHuanZheXinXi(admissTimes, reqTimes, inpatientNo);
        if (pojo.getBirthDate() != null) {
            pojo.setAge(DateUtil.calculateAge(pojo.getBirthDate(), null));
        }
        return ResultVoUtil.success(pojo);
    }

    /**
     * @param param 更新的 主键 以及 更新的数据
     * @return 返回更新 提示
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo<String> wanChenHuiZhen(JieShouHuiZhenPojo param) {
        if (param.getAdmissTimes() != null && param.getReqTimes() != null && StringUtil.notBlank(param.getInpatientNo())) {
            if (StringUtil.isBlank(param.getHzComment())) {
                return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER, "会诊意见不能为空。");
            }
            param.setHzDoctor2(TokenUtil.getInstance().getTokenUserId());
            UserInfo userInfo = userCache.getUserInfoByToken();
            if (StringUtil.isBlank(userInfo.getEmpTitCode())) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您还没有职称，请医务部或者人资维护。");
            }
            String orderCode = dao.getOrderCodeByEmpTit(userInfo.getEmpTitCode());
            if (StringUtil.isBlank(orderCode)) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您的职称不支持，您接受会诊。");
            }
            param.setHzType(getHzTypeByOrderCode(orderCode));
            JieShouHuiZhenPojo reqData = dao.getHuanZheXinXi(param.getAdmissTimes(), param.getReqTimes(), param.getInpatientNo());
            dao.wanChenHuiZhen(param);
            dao.updateOrderConsultationCode(orderCode, reqData.getActOrderNo());
            if (param.getStatusFlag().equals(2)
                    && dao.feeCount(reqData.getInpatientNo(), reqData.getAdmissTimes(), reqData.getActOrderNo()) == 0
                    && dao.orderFeeCount(reqData.getInpatientNo(), reqData.getAdmissTimes(), reqData.getActOrderNo()) == 0) {
                // 插入費用中间表
                insertYzZyPatientFee(orderCode, reqData, userInfo);
            }
            return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, param.getStatusFlag() == 1 ? "保存成功" : "完成会诊");
        }
        return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER);
    }

    private void insertYzZyPatientFee(String orderCode, @NotNull JieShouHuiZhenPojo reqData, @NotNull UserInfo userInfo) {
        String occCode = nullIf(dao.getOccCode(orderCode), orderCode);

        YzZyPatientFee fee = YzZyPatientFee.builder()
                .inpatientNo(reqData.getInpatientNo())
                .admissTimes(reqData.getAdmissTimes())
                .chargeDate(reqData.getReqDate())
                .opIdCode(userInfo.getCode())
                .chargeCode(occCode)
                .infantFlag(reqData.getInpatientNo().contains("$") ? "1" : "0")
                .actOrderNo(reqData.getActOrderNo())
                .deptCode(reqData.getDeptCode())
                .execUnit(reqData.getReqDept1())
                .build();

        dao.insertYzZyPatientFee(fee);
    }

    /**
     * @param code 医嘱编码
     * @return 返回会诊级别
     */
    private String getHzTypeByOrderCode(String code) {
        switch (code) {
            case 主任编码:
                return "3";
            case 副主任编码:
                return "2";
            case 主治编码:
                return "1";
            default:
                return "0";
        }
    }

}


