package shop.alien.second.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.SecondGoodsCategory;
import shop.alien.entity.store.LifeFans;
import shop.alien.mapper.second.SecondGoodsCategoryMapper;
import shop.alien.second.service.SecondGoodsCategoryService;
import shop.alien.util.common.JwtUtil;

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

/**
 * 二手商品服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondGoodsCategoryServiceImpl extends ServiceImpl<SecondGoodsCategoryMapper, SecondGoodsCategory> implements SecondGoodsCategoryService {

    @Autowired
    private SecondGoodsCategoryMapper mapper;
    /**
     * 保存商品为草稿状态
     * @param parentId 商品实体
     * @return 是否成功保存
     */
    @Override
    public List<SecondGoodsCategory> querySecondGoodsByParentId(Integer parentId, Integer categoryState) throws Exception {
        try {
            return mapper.querySecondGoodsByParentId(parentId, categoryState);
        } catch (Exception e) {
            log.error("SecondGoodsCategoryServiceImpl.querySecondGoodsByParentId Error Mgs={}", e.getMessage());
            throw new Exception("查询二级商品分类失败", e);
        }
    }

    @Override
    public Integer insertSecondGoodsCategory(SecondGoodsCategory category) throws Exception {
        try {
            QueryWrapper<SecondGoodsCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", category.getParentId());
            queryWrapper.orderByDesc("category_sort").last("LIMIT 1");
            SecondGoodsCategory lastCategory = this.getOne(queryWrapper);

            if(lastCategory == null || lastCategory.getCategorySort() == null) {
                category.setCategorySort(1);
            } else {
                category.setCategorySort(lastCategory.getCategorySort() + 1);
            }
            return mapper.insert(category);
        } catch (Exception e) {
            log.error("SecondGoodsCategoryServiceImpl.insertSecondGoodsCategory Error Mgs={}", e.getMessage());
            throw new Exception("查询二级商品分类失败", e);
        }
    }

    public Integer updateSecondGoodsCategory(SecondGoodsCategory category) throws Exception {
        try {
            JSONObject data = JwtUtil.getCurrentUserInfo();
            String userId = null;
            if (data != null) {
                userId = data.getString("userId");
            }
            if (StringUtil.isBlank(userId)) {
                return null;
            }
            LambdaUpdateWrapper<SecondGoodsCategory> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SecondGoodsCategory::getId, category.getId());
            if (StringUtils.isNotBlank(category.getCategoryName())) {
                wrapper.set(SecondGoodsCategory::getCategoryName, category.getCategoryName());
            }
            if (StringUtils.isNotBlank(category.getCategoryUrl())) {
                wrapper.set(SecondGoodsCategory::getCategoryUrl, category.getCategoryUrl());
            }
            if (category.getParentId() != null) {
                wrapper.set(SecondGoodsCategory::getParentId, category.getParentId());
            }
            if (category.getCategorySort() != null) {
                wrapper.set(SecondGoodsCategory::getCategorySort, category.getCategorySort());
            }
            if (category.getCategoryState() != null) {
                wrapper.set(SecondGoodsCategory::getCategoryState, category.getCategoryState());
            }
            wrapper.set(SecondGoodsCategory::getUpdatedUserId, userId);
            if (category.getDeleteFlag() != null) {
                wrapper.set(SecondGoodsCategory::getDeleteFlag, category.getDeleteFlag());
            } else {
                wrapper.set(SecondGoodsCategory::getDeleteFlag, 0);
            }
            return mapper.update(null, wrapper);
        } catch (Exception e) {
            log.error("SecondGoodsCategoryServiceImpl.insertSecondGoodsCategory Error Mgs={}", e.getMessage());
            throw new Exception("更新二级商品分类失败", e);
        }
    }


    @Override
    public List<SecondGoodsCategory> querySecondGoodsTree() throws Exception {
        try {
            return buildTree(mapper.querySecondGoodsInfo());
        } catch (Exception e) {
            log.error("SecondGoodsCategoryServiceImpl.querySecondGoodsByParentId Error Mgs={}", e.getMessage());
            throw new Exception("查询二级商品分类失败", e);
        }
    }

    // 2. 构建树的核心逻辑
    public List<SecondGoodsCategory> buildTree(List<SecondGoodsCategory> nodes) {
        Map<Integer, SecondGoodsCategory> nodeMap = nodes.stream()
                .collect(Collectors.toMap(SecondGoodsCategory::getId, n -> n));

        List<SecondGoodsCategory> roots = nodes.stream()
                .filter(n -> -1 == n.getParentId()) // 假设根节点的parentId为-1
                .sorted((n1, n2) -> {
                    if (n1.getCategorySort() == null) return 1;
                    if (n2.getCategorySort() == null) return -1;
                    return n1.getCategorySort().compareTo(n2.getCategorySort());
                })
                .collect(Collectors.toList());

        for (SecondGoodsCategory root : roots) {
            addChildrenRecursive(root, nodeMap);
        }
        return roots;
    }

    private void addChildrenRecursive(SecondGoodsCategory parent, Map<Integer, SecondGoodsCategory> nodeMap) {
        List<SecondGoodsCategory> children = nodeMap.values().stream()
                .filter(child -> child.getParentId().equals(parent.getId()))
                .sorted((n1, n2) -> {
                    if (n1.getCategorySort() == null) return 1;
                    if (n2.getCategorySort() == null) return -1;
                    return n1.getCategorySort().compareTo(n2.getCategorySort());
                })
                .collect(Collectors.toList());
        if (!children.isEmpty()) {
            parent.setChildren(children);
        }
        children.forEach(child -> addChildrenRecursive(child, nodeMap));
    }
}