package com.ylx.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.order.domain.AutoFlowConfig;
import com.ylx.order.domain.dto.RegulationConfigDTO;
import com.ylx.order.mapper.AutoFlowConfigMapper;
import com.ylx.order.service.AutoFlowConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AutoFlowConfigServiceImpl extends ServiceImpl<AutoFlowConfigMapper, AutoFlowConfig> implements AutoFlowConfigService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleAutoFlowConfig(RegulationConfigDTO dto) {
        // 查询是否存在记录
        LambdaQueryWrapper<AutoFlowConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AutoFlowConfig::getIsDelete, 0);
        AutoFlowConfig config = this.baseMapper.selectOne(wrapper);

        if (ObjectUtil.isNull(config)) {
            config = new AutoFlowConfig();
            config.setIsEnabled(dto.getAutoFlowEnabled() ? 1 : 0);
            config.setTimeoutHours(dto.getTimeoutHours());
            config.setDefaultAction(ObjectUtil.isNotNull(dto.getDefaultAction()) ? dto.getDefaultAction() : 0);
            this.baseMapper.insert(config);
        } else {
            config.setIsEnabled(dto.getAutoFlowEnabled() ? 1 : 0);
            config.setTimeoutHours(dto.getTimeoutHours());
            if (ObjectUtil.isNotNull(dto.getDefaultAction())) {
                config.setDefaultAction(dto.getDefaultAction());
            }
            this.baseMapper.updateById(config);
        }
    }

    @Override
    public void loadAutoFlowConfig(RegulationConfigDTO dto) {
        LambdaQueryWrapper<AutoFlowConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AutoFlowConfig::getIsDelete, 0);
        AutoFlowConfig config = this.baseMapper.selectOne(wrapper);

        if (ObjectUtil.isNull(config)) {
            dto.setAutoFlowEnabled(false);
            dto.setDefaultAction(0);
            return;
        }

        dto.setAutoFlowEnabled(ObjectUtil.equals(1, config.getIsEnabled()));
        dto.setTimeoutHours(config.getTimeoutHours());
        dto.setDefaultAction(ObjectUtil.isNotNull(config.getDefaultAction()) ? config.getDefaultAction() : 0);
    }
}
