package com.zt.plat.module.base.service.businessindicator;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.zt.plat.module.base.controller.admin.businessindicator.vo.*;
import com.zt.plat.module.base.dal.dataobject.businessindicator.BusinessIndicatorDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.base.dal.dao.businessindicator.BusinessIndicatorMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.base.enums.ErrorCodeConstants.*;

import com.zt.plat.module.base.dal.dataobject.businessalgorithm.BusinessAlgorithmDO;
import com.zt.plat.module.base.dal.dataobject.businessrule.BusinessRuleDO;
import com.zt.plat.module.base.dal.dao.businessalgorithm.BusinessAlgorithmMapper;
import com.zt.plat.module.base.dal.dao.businessrule.BusinessRuleMapper;
import com.zt.plat.module.system.api.user.AdminUserApi;
import com.zt.plat.module.system.api.user.dto.AdminUserRespDTO;

/**
 * 经营指标 Service 实现类
 *
 * @author chengpeng
 */
@Service
@Validated
public class BusinessIndicatorServiceImpl implements BusinessIndicatorService {

    @Resource
    private BusinessIndicatorMapper businessIndicatorMapper;
    
    @Resource
    private BusinessAlgorithmMapper businessAlgorithmMapper;
    
    @Resource
    private BusinessRuleMapper businessRuleMapper;
    
    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public BusinessIndicatorRespVO createBusinessIndicator(BusinessIndicatorSaveReqVO createReqVO) {
        // 插入
        BusinessIndicatorDO businessIndicator = BeanUtils.toBean(createReqVO, BusinessIndicatorDO.class);
        businessIndicatorMapper.insert(businessIndicator);
        // 返回
        return BeanUtils.toBean(businessIndicator, BusinessIndicatorRespVO.class);
    }

    @Override
    public void updateBusinessIndicator(BusinessIndicatorSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessIndicatorExists(updateReqVO.getId());
        // 更新
        BusinessIndicatorDO updateObj = BeanUtils.toBean(updateReqVO, BusinessIndicatorDO.class);
        businessIndicatorMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessIndicator(Long id) {
        // 校验存在
        validateBusinessIndicatorExists(id);
        // 删除
        businessIndicatorMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessIndicatorListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessIndicatorExists(ids);
        // 删除
        businessIndicatorMapper.deleteByIds(ids);
        }

    private void validateBusinessIndicatorExists(List<Long> ids) {
        List<BusinessIndicatorDO> list = businessIndicatorMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_INDICATOR_NOT_EXISTS);
        }
    }

    private void validateBusinessIndicatorExists(Long id) {
        if (businessIndicatorMapper.selectById(id) == null) {
            throw exception(BUSINESS_INDICATOR_NOT_EXISTS);
        }
    }

    @Override
    public BusinessIndicatorDO getBusinessIndicator(Long id) {
        return businessIndicatorMapper.selectById(id);
    }

    @Override
    public PageResult<BusinessIndicatorDO> getBusinessIndicatorPage(BusinessIndicatorPageReqVO pageReqVO) {
        return businessIndicatorMapper.selectPage(pageReqVO);
    }
    
    @Override
    public PageResult<BusinessIndicatorRespVO> getBusinessIndicatorPageWithRelations(BusinessIndicatorPageReqVO pageReqVO) {
        // 查询经营指标分页数据
        PageResult<BusinessIndicatorDO> pageResult = businessIndicatorMapper.selectPage(pageReqVO);
        
        // 转换为 VO 对象
        List<BusinessIndicatorRespVO> voList = BeanUtils.toBean(pageResult.getList(), BusinessIndicatorRespVO.class);
        
        // 收集需要关联查询的 ID 列表
        Set<Long> algorithmIds = new HashSet<>();
        Set<Long> ruleIds = new HashSet<>();
        Set<Long> userIds = new HashSet<>();
        
        for (BusinessIndicatorDO indicator : pageResult.getList()) {
            if (indicator.getAlgorithmId() != null) {
                algorithmIds.add(indicator.getAlgorithmId());
            }
            if (indicator.getRuleId() != null) {
                ruleIds.add(indicator.getRuleId());
            }
            if (indicator.getUserId() != null) {
                userIds.add(indicator.getUserId());
            }
        }
        
        // 批量查询关联数据
        List<BusinessAlgorithmDO> algorithms = algorithmIds.isEmpty() ? Collections.emptyList() : 
            businessAlgorithmMapper.selectBatchIds(algorithmIds);
        List<BusinessRuleDO> rules = ruleIds.isEmpty() ? Collections.emptyList() : 
            businessRuleMapper.selectBatchIds(ruleIds);
        Map<Long, AdminUserRespDTO> userMap = userIds.isEmpty() ? Collections.emptyMap() : 
            adminUserApi.getUserMap(userIds);
            
        // 建立 ID 到对象的映射
        Map<Long, BusinessAlgorithmDO> algorithmMap = new HashMap<>();
        Map<Long, BusinessRuleDO> ruleMap = new HashMap<>();
        
        for (BusinessAlgorithmDO algorithm : algorithms) {
            algorithmMap.put(algorithm.getId(), algorithm);
        }
        
        for (BusinessRuleDO rule : rules) {
            ruleMap.put(rule.getId(), rule);
        }
        
        // 填充关联信息
        for (int i = 0; i < pageResult.getList().size(); i++) {
            BusinessIndicatorDO indicator = pageResult.getList().get(i);
            BusinessIndicatorRespVO vo = voList.get(i);
            
            // 填充算法相关信息
            if (indicator.getAlgorithmId() != null && algorithmMap.containsKey(indicator.getAlgorithmId())) {
                BusinessAlgorithmDO algorithm = algorithmMap.get(indicator.getAlgorithmId());
                vo.setAlgorithmName(algorithm.getName());
                vo.setAlgorithmTypeValue(algorithm.getTypeValue());
            }
            
            // 填充规则相关信息
            if (indicator.getRuleId() != null && ruleMap.containsKey(indicator.getRuleId())) {
                BusinessRuleDO rule = ruleMap.get(indicator.getRuleId());
                vo.setRuleName(rule.getName());
                vo.setRuleTypeValue(rule.getTypeValue());
            }
            
            // 填充用户相关信息
            if (indicator.getUserId() != null && userMap.containsKey(indicator.getUserId())) {
                AdminUserRespDTO user = userMap.get(indicator.getUserId());
                vo.setUserName(user.getNickname());
            }
        }
        
        return new PageResult<>(voList, pageResult.getTotal());
    }
    
    @Override
    public List<BusinessIndicatorDO> getBusinessIndicatorListByParentId(Long parentId) {
        return businessIndicatorMapper.selectListByParentId(parentId);
    }

}