package com.bonus.material.devConfig.service.impl;

import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.material.devConfig.domain.*;
import com.bonus.material.devConfig.mapper.EquipmentTypeMapper;
import com.bonus.material.devConfig.service.EquipmentTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 装备分类服务实现
 */
@Service
public class EquipmentTypeServiceImpl implements EquipmentTypeService {

    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;

    @Override
    public List<EquipmentTypeDTO> getEquipmentTypeTree() {
        List<EquipmentType> allTypes = equipmentTypeMapper.selectAllEquipmentTypes();
        List<EquipmentType> tree = buildTree(allTypes);
        return convertToDTOList(tree);
    }

    @Override
    public List<EquipmentTypeDTO> getEquipmentCascader() {
        return getEquipmentTypeTree();
    }

    @Override
    public List<EquipmentTypeEntity> getEquipmentTypeList(EquipmentTypeEntity query) {
        return equipmentTypeMapper.selectEquipmentTypeList(query);
    }

    @Override
    public EquipmentType getEquipmentTypeDetail(Long id) {
        return equipmentTypeMapper.selectEquipmentTypeById(id);
    }

    @Override
    @Transactional
    public AjaxResult addEquipmentType(EquipmentType equipmentType) {
        // 设置默认值
        // 设置层级，如果没有设置则默认为1
        if (equipmentType.getLevel() == null) {
            equipmentType.setLevel(1);
        }
        equipmentType.setCreateTime(new Date());
        equipmentType.setUpdateTime(new Date());
        // 4. 校验同层级下名称是否重复（避免重复新增）
        int sameNameCount = equipmentTypeMapper.getToolByTypeIdAndTypeName(equipmentType);
        if (sameNameCount > 0) {
            return AjaxResult.error("当前分类下已存在同名类型，新增失败");
        }
        equipmentTypeMapper.insertEquipmentType(equipmentType);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult updateEquipmentType(EquipmentType equipmentType) {
        // 1. 校验父ID是否与自身ID相同
        if (equipmentType.getParentId() != null && equipmentType.getParentId().equals(equipmentType.getTypeId())) {
            // 抛出异常，阻止更新并回滚事务
            throw new IllegalArgumentException("父分类ID不能与自身ID相同，更新失败。");
        }
        int sameNameCount = equipmentTypeMapper.countSameNameInSameLevel(equipmentType);
        if (sameNameCount > 0) {
            return AjaxResult.error("当前分类下已存在同名类型，修改失败");
        }
        // 4. 执行正常的更新逻辑
        equipmentType.setUpdateTime(new Date());
        equipmentTypeMapper.updateEquipmentType(equipmentType);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public void deleteEquipmentType(Long id) {
        // 检查是否存在子分类
        Long count = equipmentTypeMapper.countChildrenByParentId(id);
        if (count > 0) {
            throw new RuntimeException("存在子分类，无法删除");
        }

        // 先删除属性
        equipmentTypeMapper.deleteTypePropertiesByTypeId(id);
        equipmentTypeMapper.deleteEquipmentTypeById(id);
    }

    /**
     * 构建树形结构
     */
    private List<EquipmentType> buildTree(List<EquipmentType> list) {
        List<EquipmentType> roots = list.stream()
                .filter(node -> node.getParentId() == null || node.getParentId() == 0)
                .collect(Collectors.toList());

        for (EquipmentType root : roots) {
            buildChildTree(root, list, 1);
        }

        return roots;
    }

    /**
     * 递归构建子树
     */
    private void buildChildTree(EquipmentType parent, List<EquipmentType> list, int level) {
        List<EquipmentType> children = list.stream()
                .filter(node -> parent.getTypeId().equals(node.getParentId()))
                .collect(Collectors.toList());

        parent.setChildren(children);
        parent.setLevel(level);
        parent.setLeaf(children.isEmpty());

        for (EquipmentType child : children) {
            buildChildTree(child, list, level + 1);
        }
    }

    /**
     * 转换为DTO列表
     */
    private List<EquipmentTypeDTO> convertToDTOList(List<EquipmentType> entities) {
        return entities.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为DTO
     */
    private EquipmentTypeDTO convertToDTO(EquipmentType entity) {
        EquipmentTypeDTO dto = new EquipmentTypeDTO();
        dto.setId(entity.getTypeId());
        dto.setName(entity.getTypeName());
        dto.setParentId(entity.getParentId());
        dto.setLevel(entity.getLevel());
        dto.setLeaf(entity.getLeaf());

        if (entity.getChildren() != null && !entity.getChildren().isEmpty()) {
            List<EquipmentTypeDTO> childDTOs = convertToDTOList(entity.getChildren());
            dto.setChildren(childDTOs);
        }

        return dto;
    }
}