package thyyxxk.webserver.service.inpatient;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.inpatient.ZhuYuanYiZhuDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.YzActOrder;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 描述： 医嘱退费
 * </p>
 *
 * @author xc
 * @date 2021-09-17 10:25
 */
@Service
@Slf4j
public class ZhuYuanYiZhuServer {

    private final ZhuYuanYiZhuDao dao;


    private final PublicServer publicServer;

    public ZhuYuanYiZhuServer(ZhuYuanYiZhuDao dao, PublicServer publicServer) {
        this.dao = dao;
        this.publicServer = publicServer;
    }

    /**
     * 分页获取可以退费的医嘱号 只有 临时医嘱才能退费
     *
     * @param param 查询条件 分页 住院号 ，次数 ，医嘱编码，医嘱号，开始时间，结束时间
     * @return 返回分页数据
     */
    public ResultVo<IPage<YzActOrder>> getOrderList(YzActOrder param) {
        int infantFlag = 0;
        if (param.getInpatientNo().contains("$")) {
            param.setInpatientNo(param.getInpatientNo().split("\\$")[0]);
            infantFlag = 1;
        }
        if (StringUtil.isBlank(param.getInpatientNo()) || param.getAdmissTimes() == null) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "住院号或住院次数为空。( >﹏<。)");
        }
        IPage<YzActOrder> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        dao.getYzXinXi(page, param.getInpatientNo(), param.getAdmissTimes(), param.getOrderCode(),
                param.getActOrderNo(), param.getQueryStartTime(), param.getQueryEndTime(), infantFlag);
        if (page.getRecords().isEmpty()) {
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST);
        }
        List<YzActOrder> tuiFeiYiZhuHaoList = dao.getTuiFei(page.getRecords());
        if (ListUtil.notBlank(tuiFeiYiZhuHaoList)) {
            Map<BigDecimal, YzActOrder> yiTuiFeiYiZhuMap = tuiFeiYiZhuHaoList.stream().collect(Collectors.toMap(YzActOrder::getActOrderNo, a -> a, (k1, k2) -> k1));
            page.getRecords().forEach(item -> {
                if (yiTuiFeiYiZhuMap.containsKey(item.getActOrderNo())) {
                    item.setTfFlag(1);
                } else if (item.getDrugQuan().signum() == -1) {
                    item.setTfFlag(2);
                } else {
                    item.setTfFlag(0);
                }

            });
        }
        return ResultVoUtil.success(page);
    }

    /**
     * 生成退费医嘱数据
     * 不能重复退费，不能退负数
     *
     * @param param 需要，住院号，次数，医嘱号
     * @return 返回提示
     */
    public ResultVo<String> yiZhuTuiFei(YzActOrder param) {
        if (ListUtil.isBlank(param.getTuiFeiList())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "请先选择退费数据，￢o(￣-￣ﾒ)");
        }
        if (param.getTuiFeiList().size() >= 100) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "一次性退费超过100条，￢o(￣-￣ﾒ)");
        }
        List<YzActOrder> yuanYiZhuShuJu = dao.yuanYiZhu(param.getInpatientNo(), param.getAdmissTimes(), param.getTuiFeiList());
        if (ListUtil.isBlank(yuanYiZhuShuJu)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "未查询到对应的住院号。┌(。Д。)┐");
        }
        List<YzActOrder> tuiFeiList = dao.getTuiFei(param.getTuiFeiList());
        if (!tuiFeiList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            tuiFeiList.forEach(item -> {
                sb.append("<span style='color:red'>【").append(item.getActOrderNo()).append("】</span><br>");
            });
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, String.format("%s 以上医嘱重复退费", sb));
        }

        for (YzActOrder yzActOrder : yuanYiZhuShuJu) {
            // 价格 不为负数 才能退费
            if (yzActOrder.getDrugQuan().signum() == -1) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, String.format("医嘱号为：【%s】费用为负数无法退费。( ´Д｀)y━・~~", yzActOrder.getActOrderNo()));
            }
            yzActOrder.setDrugQuan(yzActOrder.getDrugQuan().negate());
            yzActOrder.setNewActOrderNo(publicServer.getActOrderNo());
        }
        dao.yiZhuTuiFei(yuanYiZhuShuJu, TokenUtil.getTokenUserId());
        dao.insertYzActOrderTf(yuanYiZhuShuJu);
        log.info("医嘱退费:操作人：{},数据：{}", TokenUtil.getTokenUserId(), JSON.toJSONStringWithDateFormat(yuanYiZhuShuJu, DateUtil.DEFAULT_PATTERN));
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_NOTIFICATION, "操作成功。*.。(๑･∀･๑)*.。");
    }

}
