package org.xyzh.news.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.dto.resource.TbResourceCategory;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.news.mapper.ResourceCategoryMapper;
import org.xyzh.api.news.category.ResourceCategoryService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @description 资源分类服务实现类
 * @filename NCResourceCategoryServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class NCResourceCategoryServiceImpl implements ResourceCategoryService {

    private static final Logger logger = LoggerFactory.getLogger(NCResourceCategoryServiceImpl.class);

    @Autowired
    private ResourceCategoryMapper resourceCategoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceCategory> createCategory(TbResourceCategory category) {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (category == null || !StringUtils.hasText(category.getName())) {
                resultDomain.fail("分类名称不能为空");
                return resultDomain;
            }

            // 检查分类名称是否已存在
            int count = resourceCategoryMapper.countByName(category.getName(), null);
            if (count > 0) {
                resultDomain.fail("分类名称已存在");
                return resultDomain;
            }

            // 设置默认值
            if (category.getID() == null) {
                category.setID(IDUtils.generateID());
            }
            if (category.getCategoryID() == null) {
                category.setCategoryID(IDUtils.generateID());
            }
            if (category.getOrderNum() == null) {
                category.setOrderNum(0);
            }
            
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            category.setDeleted(false);

            // 插入数据库
            int result = resourceCategoryMapper.insertResourceCategory(category);
            if (result > 0) {
                logger.info("创建分类成功: {}", category.getName());
                resultDomain.success("创建分类成功", category);
                return resultDomain;
            } else {
                resultDomain.fail("创建分类失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("创建分类异常: {}", e.getMessage(), e);
            resultDomain.fail("创建分类失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceCategory> updateCategory(TbResourceCategory category) {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (category == null || !StringUtils.hasText(category.getID())) {
                resultDomain.fail("分类ID不能为空");
                return resultDomain;
            }

            // 检查分类是否存在
            TbResourceCategory existingCategory = resourceCategoryMapper.selectById(category.getID());
            if (existingCategory == null || existingCategory.getDeleted()) {
                resultDomain.fail("分类不存在");
                return resultDomain;
            }

            // 检查分类名称是否重复（排除自身）
            if (StringUtils.hasText(category.getName())) {
                int count = resourceCategoryMapper.countByName(category.getName(), category.getID());
                if (count > 0) {
                    resultDomain.fail("分类名称已存在");
                    return resultDomain;
                }
            }

            // 更新时间
            category.setUpdateTime(new Date());

            // 更新数据库
            int result = resourceCategoryMapper.updateResourceCategory(category);
            if (result > 0) {
                logger.info("更新分类成功: {}", category.getID());
                // 重新查询返回完整数据
                TbResourceCategory updated = resourceCategoryMapper.selectById(category.getID());
                resultDomain.success("更新分类成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新分类失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新分类异常: {}", e.getMessage(), e);
            resultDomain.fail("更新分类失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteCategory(String categoryID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(categoryID)) {
                resultDomain.fail("分类ID不能为空");
                return resultDomain;
            }

            // 检查分类是否存在
            TbResourceCategory category = resourceCategoryMapper.selectByCategoryId(categoryID);
            if (category == null || category.getDeleted()) {
                resultDomain.fail("分类不存在");
                return resultDomain;
            }

            // 检查是否有子分类
            ResultDomain<Boolean> hasChildResult = hasChildCategories(categoryID);
            if (hasChildResult.isSuccess() && Boolean.TRUE.equals(hasChildResult.getData())) {
                resultDomain.fail("该分类下存在子分类，无法删除");
                return resultDomain;
            }

            // 检查是否有关联资源
            ResultDomain<Boolean> hasResourceResult = hasResources(categoryID);
            if (hasResourceResult.isSuccess() && Boolean.TRUE.equals(hasResourceResult.getData())) {
                resultDomain.fail("该分类下存在资源，无法删除");
                return resultDomain;
            }

            // 物理删除
            int result = resourceCategoryMapper.deleteResourceCategory(category);
            if (result > 0) {
                logger.info("删除分类成功: {}", categoryID);
                resultDomain.success("删除分类成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("删除分类失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("删除分类异常: {}", e.getMessage(), e);
            resultDomain.fail("删除分类失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResourceCategory> getCategoryById(String categoryID) {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            if (!StringUtils.hasText(categoryID)) {
                resultDomain.fail("分类ID不能为空");
                return resultDomain;
            }

            TbResourceCategory category = resourceCategoryMapper.selectByCategoryId(categoryID);
            if (category == null || category.getDeleted()) {
                resultDomain.fail("分类不存在");
                return resultDomain;
            }

            resultDomain.success("查询成功", category);
            return resultDomain;
        } catch (Exception e) {
            logger.error("查询分类异常: {}", e.getMessage(), e);
            resultDomain.fail("查询分类失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResourceCategory> getAllCategories() {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            List<TbResourceCategory> categories = resourceCategoryMapper.selectResourceCategories(new TbResourceCategory());
            resultDomain.success("查询成功", categories);
            return resultDomain;
        } catch (Exception e) {
            logger.error("查询分类列表异常: {}", e.getMessage(), e);
            resultDomain.fail("查询分类列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResourceCategory> getCategoriesByParent(String parentID) {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            if (!StringUtils.hasText(parentID)) {
                resultDomain.fail("父分类ID不能为空");
                return resultDomain;
            }

            List<TbResourceCategory> categories = resourceCategoryMapper.selectByParentId(parentID);
            resultDomain.success("查询成功", categories);
            return resultDomain;
        } catch (Exception e) {
            logger.error("查询子分类列表异常: {}", e.getMessage(), e);
            resultDomain.fail("查询子分类列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResourceCategory> getCategoryTree() {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            // 查询所有分类
            List<TbResourceCategory> allCategories = resourceCategoryMapper.selectCategoryTree();
            
            // 构建树形结构
            List<TbResourceCategory> tree = buildCategoryTree(allCategories, null);
            
            resultDomain.success("查询成功", tree);
            return resultDomain;
        } catch (Exception e) {
            logger.error("查询分类树异常: {}", e.getMessage(), e);
            resultDomain.fail("查询分类树失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> hasChildCategories(String categoryID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            if (!StringUtils.hasText(categoryID)) {
                resultDomain.fail("分类ID不能为空");
                return resultDomain;
            }

            List<TbResourceCategory> children = resourceCategoryMapper.selectByParentId(categoryID);
            resultDomain.success("查询成功", !children.isEmpty());
            return resultDomain;
        } catch (Exception e) {
            logger.error("检查子分类异常: {}", e.getMessage(), e);
            resultDomain.fail("检查子分类失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> hasResources(String categoryID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            if (!StringUtils.hasText(categoryID)) {
                resultDomain.fail("分类ID不能为空");
                return resultDomain;
            }

            // TODO: 需要查询资源表判断是否有关联资源
            // 这里暂时返回false，需要在ResourceMapper中添加相应方法
            resultDomain.success("查询成功", false);
            return resultDomain;
        } catch (Exception e) {
            logger.error("检查分类资源异常: {}", e.getMessage(), e);
            resultDomain.fail("检查分类资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResourceCategory> updateCategoryOrder(String categoryID, Integer orderNum) {
        ResultDomain<TbResourceCategory> resultDomain = new ResultDomain<>();
        try {
            if (!StringUtils.hasText(categoryID) || orderNum == null) {
                resultDomain.fail("参数不能为空");
                return resultDomain;
            }

            TbResourceCategory category = resourceCategoryMapper.selectByCategoryId(categoryID);
            if (category == null || category.getDeleted()) {
                resultDomain.fail("分类不存在");
                return resultDomain;
            }

            TbResourceCategory updateCategory = new TbResourceCategory();
            updateCategory.setID(category.getID());
            updateCategory.setOrderNum(orderNum);
            updateCategory.setUpdateTime(new Date());

            int result = resourceCategoryMapper.updateResourceCategory(updateCategory);
            if (result > 0) {
                logger.info("更新分类排序成功: {}", categoryID);
                TbResourceCategory updated = resourceCategoryMapper.selectById(category.getID());
                resultDomain.success("更新排序成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新排序失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新分类排序异常: {}", e.getMessage(), e);
            resultDomain.fail("更新排序失败: " + e.getMessage());
            return resultDomain;
        }
    }

    /**
     * 构建分类树形结构
     * @param allCategories 所有分类列表
     * @param parentID 父分类ID
     * @return 树形结构列表
     */
    private List<TbResourceCategory> buildCategoryTree(List<TbResourceCategory> allCategories, String parentID) {
        List<TbResourceCategory> result = new ArrayList<>();
        
        for (TbResourceCategory category : allCategories) {
            // 找出当前父级下的子分类
            if ((parentID == null && category.getParentID() == null) || 
                (parentID != null && parentID.equals(category.getParentID()))) {
                
                // 递归查找子分类（如果TbResourceCategory有children字段，可以在这里设置）
                // List<TbResourceCategory> children = buildCategoryTree(allCategories, category.getCategoryID());
                // category.setChildren(children);
                
                result.add(category);
            }
        }
        
        return result;
    }
}
