package thyyxxk.webserver.service.orderZdMaintain;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.orderZdMaintain.OrderZdMaintainDao;
import thyyxxk.webserver.dao.his.orderZdMaintain.YzOrderFrequencyDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.orderZdMaintain.dto.AddOrderOccurenceDTO;
import thyyxxk.webserver.entity.orderZdMaintain.dto.YzOrderItemDTO;
import thyyxxk.webserver.entity.orderZdMaintain.dto.frequency.YzOrderFrequencyDTO;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.PingYinUtils;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class OrderZdMaintainService {
    private final OrderZdMaintainDao dao;
    private final PublicServer publicServer;
    private final YzOrderFrequencyDao yzOrderFrequencyDao;


    public ResultVo<YzOrderItemDTO> saveItem(YzOrderItemDTO params) {
        log.info("保存医嘱项目数据：操作人:{} == {}", TokenUtil.getInstance().getTokenUserId(), params);
        String message = "更新成功";
        params.setPyCode(PingYinUtils.pyShouZiMuDaXie(params.getOrderName(), 10));
        params.setDCode(PingYinUtils.getWBCode(params.getOrderName(), 10));

        if (StrUtil.isNotBlank(params.getOrderCode())) {
            dao.updateChangeItem(params);
        } else {
            String orderNo = publicServer.getOrderNo();
            params.setOrderCode(orderNo);
            dao.insertOrderItem(params);
            message = "插入成功";
        }

        List<YzOrderItemDTO> changeItem = dao.getOrderItem(StrUtil.format("order_code = '{}' ", params.getOrderCode()));
        if (changeItem != null && !changeItem.isEmpty()) {
            return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION, message, changeItem.get(0));
        }
        return ResultVoUtil.fail(ExceptionEnum.LOGICAL_HTML_ERROR, "操作失败");
    }


    public ResultVo<String> saveOrderOccurence(AddOrderOccurenceDTO params) {
        dao.delOcc(params.getOrderCode());

        ListUtil.batchList(params.getOrderItem(), OrderZdMaintainDao.class, (m, item) -> {
            item.setOrderCode(params.getOrderCode());
            m.insertOcc(item);
        });

        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION, "更新成功");
    }


    public ResultVo<String> saveOrderFrequency(YzOrderFrequencyDTO params) {
        int old = dao.hasOrderFrequency(params.getCode());
        if (old > 0) {
            yzOrderFrequencyDao.updateById(params);
        } else {
            yzOrderFrequencyDao.insert(params);
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION);
    }





}
