package cn.iocoder.yudao.module.erp.service.autocode;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.autocode.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.autocode.AutocodeRuleDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.autocode.AutocodePartDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.autocode.AutocodeRuleMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.autocode.AutocodePartMapper;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 编码规则 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class AutocodeRuleServiceImpl implements AutocodeRuleService {

    @Resource
    private AutocodeRuleMapper autocodeRuleMapper;
    @Resource
    private AutocodePartMapper autocodePartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAutocodeRule(AutocodeRuleSaveReqVO createReqVO) {
        // 插入
        AutocodeRuleDO autocodeRule = BeanUtils.toBean(createReqVO, AutocodeRuleDO.class);
        autocodeRuleMapper.insert(autocodeRule);

        // 插入子表
        createAutocodePartList(autocodeRule.getId(), createReqVO.getAutocodeParts());
        // 返回
        return autocodeRule.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAutocodeRule(AutocodeRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateAutocodeRuleExists(updateReqVO.getId());
        // 更新
        AutocodeRuleDO updateObj = BeanUtils.toBean(updateReqVO, AutocodeRuleDO.class);
        autocodeRuleMapper.updateById(updateObj);

        // 更新子表
        updateAutocodePartList(updateReqVO.getId(), updateReqVO.getAutocodeParts());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAutocodeRule(Long id) {
        // 校验存在
        validateAutocodeRuleExists(id);
        // 删除
        autocodeRuleMapper.deleteById(id);

        // 删除子表
        deleteAutocodePartByRuleId(id);
    }

    private void validateAutocodeRuleExists(Long id) {
        if (autocodeRuleMapper.selectById(id) == null) {
            throw exception(AUTOCODE_RULE_NOT_EXISTS);
        }
    }

    @Override
    public AutocodeRuleDO getAutocodeRule(Long id) {
        return autocodeRuleMapper.selectById(id);
    }
    @Override
    public AutocodeRuleDO getAutocodeRuleByRuleCode(String ruleCode) {
        return autocodeRuleMapper.selectOne(AutocodeRuleDO::getRuleCode, ruleCode);
    }
    @Override
    public PageResult<AutocodeRuleDO> getAutocodeRulePage(AutocodeRulePageReqVO pageReqVO) {
        return autocodeRuleMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（编码规则组成） ====================

    @Override
    public List<AutocodePartDO> getAutocodePartListByRuleId(Long ruleId) {
        return autocodePartMapper.selectListByRuleId(ruleId);
    }

    private void createAutocodePartList(Long ruleId, List<AutocodePartDO> list) {
        list.forEach(o -> o.setRuleId(ruleId));
        autocodePartMapper.insertBatch(list);
    }

    private void updateAutocodePartList(Long ruleId, List<AutocodePartDO> list) {
        deleteAutocodePartByRuleId(ruleId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createAutocodePartList(ruleId, list);
    }

    private void deleteAutocodePartByRuleId(Long ruleId) {
        autocodePartMapper.deleteByRuleId(ruleId);
    }

}