package com.cf.imes.module.system.service.customplateno.factory.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.module.executor.api.customplateno.OrderCustomPlateNoApi;
import com.cf.imes.module.executor.api.customplateno.dto.CustomPlateNoRuleDTO;
import com.cf.imes.module.system.dal.dataobject.customplateno.CustomPlateNoSeqDO;
import com.cf.imes.module.system.dal.mysql.customplateno.CustomPlateNoSeqMapper;
import com.cf.imes.module.system.enums.customplateno.ResetModeEnum;
import com.cf.imes.module.system.service.customplateno.factory.service.AbstractCustomPlateNoResetServiceHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import static com.cf.imes.module.system.enums.ErrorCodeConstants.SYSTEM_CONFIG_CUSTOM_PLATE_NO_ORDER_RESET_UPDATE_ERROR;

/**
 * 自定义板编号板件序号规则复位处理器
 *
 * @author Gqr
 * @since 2024/11/28 19:01
 */
@Service("plateNoRuleResetServiceHandler")
@Slf4j
public class PlateNoRuleResetServiceHandler extends AbstractCustomPlateNoResetServiceHandler {

    @Resource
    private CustomPlateNoSeqMapper customPlateNoSeqMapper;

    @Resource
    private OrderCustomPlateNoApi orderCustomPlateNoApi;

    @Override
    public void reset(CustomPlateNoRuleDTO ruleDTO) {
        ResetModeEnum resetModeEnum = ResetModeEnum.getByMode(ruleDTO.getResetMode());
        if (ObjectUtil.equal(resetModeEnum, ResetModeEnum.ORDER) || ObjectUtil.equal(resetModeEnum, ResetModeEnum.YEAR)
                || ObjectUtil.equal(resetModeEnum, ResetModeEnum.MONTH) || ObjectUtil.equal(resetModeEnum, ResetModeEnum.DAY)) {
            // 更新机构下全局序号中的板件序号前序值
            LambdaUpdateWrapper<CustomPlateNoSeqDO> seqLambdaUpdateWrapper = new LambdaUpdateWrapper<CustomPlateNoSeqDO>()
                    .eq(CustomPlateNoSeqDO::getOrganId, OrganContextHolder.getOrganId())
                    .set(CustomPlateNoSeqDO::getPlateNoSeq, null);
            customPlateNoSeqMapper.update(seqLambdaUpdateWrapper);
        }

        // 更新使用该配置的生产单中的orderNoSeq
        CommonResult<Boolean> orderResetResult = orderCustomPlateNoApi.resetOrderSeq(ruleDTO);
        if(orderResetResult.isError()) {
            ServiceException serviceException = new ServiceException(SYSTEM_CONFIG_CUSTOM_PLATE_NO_ORDER_RESET_UPDATE_ERROR);
            log.error(orderResetResult.getMsg(), serviceException);
            throw serviceException;
        }
    }
}
