package com.ylx.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ylx.order.domain.RefundRuleDetail;
import com.ylx.order.domain.dto.RegulationConfigDTO;
import com.ylx.order.domain.vo.RegulationConfigVO;
import com.ylx.order.service.AutoFlowConfigService;
import com.ylx.order.service.RefundRuleDetailService;
import com.ylx.order.service.RefundRuleMasterService;
import com.ylx.order.service.RegulationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RegulationServiceImpl implements RegulationService {

    @Resource
    private AutoFlowConfigService autoFlowConfigService;
    @Resource
    private RefundRuleMasterService refundRuleMasterService;
    @Resource
    private RefundRuleDetailService refundRuleDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFullConfig(RegulationConfigDTO dto) {
        // 1. 保存/更新自动流转配置 (auto_flow_config)
        handleAutoFlowConfig(dto);

        // 2. 保存/更新退款规则 (refund_rule_master + detail)
        handleRefundRules(dto);
    }

    private void handleAutoFlowConfig(RegulationConfigDTO dto) {
        this.autoFlowConfigService.handleAutoFlowConfig(dto);
    }

    private void handleRefundRules(RegulationConfigDTO dto) {
        this.refundRuleMasterService.handleRefundRules(dto);
    }

    @Override
    public RegulationConfigDTO getFullConfig() {
        RegulationConfigDTO dto = new RegulationConfigDTO();
        this.autoFlowConfigService.loadAutoFlowConfig(dto);
        this.refundRuleMasterService.loadRefundRules(dto);
        return dto;
    }

    @Override
    public List<RegulationConfigVO> getDescListByExecStatus(Integer execStatus) {
        LambdaQueryWrapper<RefundRuleDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RefundRuleDetail::getStageType, execStatus)
                .orderByAsc(RefundRuleDetail::getSortOrder);
        List<RefundRuleDetail> list = this.refundRuleDetailService.list(wrapper);
        if (CollUtil.isNotEmpty(list)){
            return list.stream()
                    .map(RegulationConfigVO::new)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
