package thyyxxk.webserver.service.zhuyuanyisheng;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.YzConfig;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.OrderQuashDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.zhuyuanyisheng.orderquash.ReqOrderQuash;
import thyyxxk.webserver.entity.zhuyuanyisheng.orderquash.ReturnReqOrderQuash;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.DateUtil;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderQuashService {
    private final OrderQuashDao dao;
    private final PublicServer publicServer;
    private final YzConfig yzConfig;


    /**
     * 作废医嘱
     *
     * @param param
     * @return
     */
    public ResultVo<Integer> applicationForRevocation(ReqOrderQuash param) {
        Date orderDate = dao.selectOrderStartTime(param.getActOrderNo());
        if (orderDate == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "原医嘱已不存在。");
        }

        if (yzConfig.getYzAllowInvalidation()) {
            // 申请作废先一步要停止医嘱
            dao.stopOrder(param.getActOrderNo());
        }

        Date now = new Date();
        param.setReqId(TokenUtil.getInstance().getTokenUserId())
                .setReqDatetime(now);

        long subtract = DateUtil.theDifferenceIsHours(now, orderDate);

        // 超过 24 小时 要申请
        if (subtract > 24) {
            return insertTheRequest(param, "医嘱超过24小时");
        }

        // 有费用要申请
        if (dao.selectZyDetailCharge(param.getActOrderNo(), param.getPatNo(), param.getTimes()) > 0) {
            return insertTheRequest(param, "该医嘱已产生费用");
        }

        // 有药单申请
        if (dao.selectYpOrder(param.getActOrderNo()) > 0) {
            return insertTheRequest(param, "该医嘱已产生药单");
        }

        // 有费用中间表申请
        if (dao.selectZyPatientFee(param.getActOrderNo()) > 0) {
            return insertTheRequest(param, "项目，医嘱已确费");
        }

        param.setState(2).setApproverRemark("系统自动审核。");
        // 删除原来的数据
        dao.deleteById(param.getActOrderNo());
        // 插入申请表数据
        dao.insert(param);
        revocationOfMedicalOrders(param);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_ALERT, "撤销成功，如果医嘱还存在请刷新页面。", 1);
    }

    private ResultVo<Integer> insertTheRequest(ReqOrderQuash param, String message) {
        if (!yzConfig.getYzAllowInvalidation()) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, message);
        }
        ReqOrderQuash quash = dao.selectById(param.getActOrderNo());
        if (quash == null) {
            dao.insert(param);
        } else if (quash.getState() == 2) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "医嘱已经通过审核了。");
        } else if (quash.getState() == 3 || quash.getState() == 1) {
            dao.deleteById(param.getActOrderNo());
            dao.insert(param);
        }
        log.info("日志：{}", JSON.toJSONString(param));
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_ALERT, message + "无法撤销，已经向医务部提出申请，审核通过后撤销医嘱。", 0);
    }


    public ResultVo<List<ReturnReqOrderQuash>> getReqOrderQuash(String startTime, String endTime, int state, Boolean myReq) {
        QueryWrapper<ReturnReqOrderQuash> qw = new QueryWrapper<>();
        qw.ge("req_datetime", startTime)
                .le("req_datetime", endTime);
        qw.eq("state", state);

        if (myReq) {
            qw.eq("req_id", TokenUtil.getInstance().getTokenUserId());
        }

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


    public ResultVo<List<ReturnReqOrderQuash>> selectReqListByPat(String patNo, String times, int state) {
        return ResultVoUtil.success(dao.selectReqListByPat(patNo, times, state));
    }

    public ResultVo<String> saveData(List<ReqOrderQuash> list) {
        if (ListUtil.isBlank(list)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请先选择数据。");
        }
        if (publicServer.needRule(38)) {
            String code = TokenUtil.getInstance().getTokenUserId();
            Date now = new Date();
            for (ReqOrderQuash item : list) {
                item.setApproverId(code);
                item.setApproverDatatime(now);
                dao.updateReqOrderQuash(item);
                revocationOfMedicalOrders(item);
            }
            return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "您没有审核权限。");
    }

    /**
     * 删除费用等信息
     *
     * @param item 数据
     */
    public void revocationOfMedicalOrders(ReqOrderQuash item) {
        BigDecimal order = item.getActOrderNo();
        // 删除费用中间表
        dao.delPatientFee(order);
        // 删除药品表
        dao.delYpZyOrder(order);
        dao.eraseOrder(order);
        dao.upErase(order);
        dao.delYzOrder(order);
        log.info("撤销医嘱, 医嘱号：{}, 操作人：{}", order, TokenUtil.getInstance().getTokenUserId());
    }


}
