package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.config.redis.BaseRedisService;
import shop.alien.entity.store.TagCategory;
import shop.alien.entity.store.vo.LabelButtonOptionVo;
import shop.alien.entity.store.vo.TagCategoryVo;
import shop.alien.mapper.TagCategoryMapper;
import shop.alien.storeplatform.service.StorePlatformTagCategoryService;

import java.util.Collections;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class StorePlatformTagCategoryServiceImpl extends ServiceImpl<TagCategoryMapper, TagCategory> implements StorePlatformTagCategoryService {

    public final TagCategoryMapper tagCategoryMapper;
    private final BaseRedisService baseRedisService;
    private static final String TAG_TREE_CACHE_KEY = "tag:tree";

    @Override
    public TagCategory createTag(TagCategory tagCategory) {

        // 校验同一层级是否存在相同的标签
//        List<TagCategory> tagCategoryList = tagCategoryMapper.selectList(new LambdaQueryWrapper<TagCategory>().eq(TagCategory::getLabelType, tagCategory.getLabelType()).eq(TagCategory::getTagName, tagCategory.getTagName()));
//        if(CollectionUtils.isNotEmpty(tagCategoryList)){
//            throw new IllegalArgumentException("标签已经存在");
//        }

        // 将数据存储到数据库中
        log.info("标签创建, 请求参数: {}", tagCategory);
        int result = tagCategoryMapper.insert(tagCategory);
        log.info("标签创建, 结果: {}", result);
        // 清除相关缓存
//        baseRedisService.delete(TAG_TREE_CACHE_KEY);
        return tagCategory;
    }

    @Override
    public IPage<TagCategory> getTagList(int page, int size,String label,String labelType, String labelButtonType) {
        IPage<TagCategory> iPage = new Page<>(page, size);
        LambdaQueryWrapper<TagCategory> tagCategoryLambdaQueryWrapper = new LambdaQueryWrapper<TagCategory>();
        tagCategoryLambdaQueryWrapper.eq(TagCategory::getDeleteFlag, 0);
        if(StringUtils.isNotBlank(label)){
            tagCategoryLambdaQueryWrapper.like(TagCategory::getTagName,label);
        }
        if(StringUtils.isNotBlank(labelType)){
            tagCategoryLambdaQueryWrapper.eq(TagCategory::getLabelType, labelType);
        }
        if(StringUtils.isNotBlank(labelButtonType)){
            tagCategoryLambdaQueryWrapper.eq(TagCategory::getLabelButtonType, labelButtonType);
        }
        tagCategoryLambdaQueryWrapper.orderByDesc(TagCategory::getCreatedTime);
        return tagCategoryMapper.selectPage(iPage,tagCategoryLambdaQueryWrapper);
    }

//    @Override
//    public List<TagCategory> getTagTree() {
//        // 缓存获取
//
//        List<TagCategory> tagCategoryTree = new ArrayList<>();
//        try {
//            tagCategoryTree = baseRedisService.getList(TAG_TREE_CACHE_KEY, TagCategory.class);
//        } catch (JsonProcessingException e) {
//            log.error("StoreTagServiceImpl-getTagTree获取缓存异常: ", e);
//            throw new RuntimeException(e);
//        }
//        if (CollectionUtils.isNotEmpty(tagCategoryTree)) {
//            return tagCategoryTree;
//        }
//
//        // 从数据库获取未删除的所有标签
//        LambdaQueryWrapper<TagCategory> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(TagCategory::getDeleteFlag, CommonConstant.DELETE_FLAG_UNDELETE);
//        List<TagCategory> allTags = tagCategoryMapper.selectList(queryWrapper);
//
//        // 构建树形结构
//        tagCategoryTree = buildTagTree(allTags);
//
//        // 缓存结果
//        if (CollectionUtils.isNotEmpty(tagCategoryTree)) {
//            try {
//                baseRedisService.storeList(TAG_TREE_CACHE_KEY, tagCategoryTree);
//            } catch (JsonProcessingException e) {
//                log.error("StoreTagServiceImpl-getTagTree存储缓存异常: ", e);
//                throw new RuntimeException(e);
//            }
//        }
//
//        return tagCategoryTree;
//    }

    @Override
    public int deleteTag(TagCategory tagCategory) {
        if(tagCategory == null ||tagCategory.getId() == null){
            return 0;
        }

        int deleteTagResult = tagCategoryMapper.deleteById(tagCategory.getId());
        if (deleteTagResult > 0) {
            baseRedisService.delete(TAG_TREE_CACHE_KEY);
        }
        return deleteTagResult;
    }

    @Override
    public int updateTagCategory(TagCategory tagCategory) {
        if(tagCategory == null){
            return 0;
        }
        int updateResult = tagCategoryMapper.updateById(tagCategory);
        if (updateResult > 0){
            baseRedisService.delete(TAG_TREE_CACHE_KEY);
        }
        return updateResult;
    }

    @Override
    public List<TagCategoryVo> getBusinessRelationTagList(Integer businessSection) {
        if(businessSection!=null){
            List<TagCategoryVo> tagCategoryVoList = tagCategoryMapper.getBusinessRelationTagList(businessSection);
            return getCategories(tagCategoryVoList);
        }
        return Collections.emptyList();
    }


    private static List<TagCategoryVo> getCategories(List<TagCategoryVo> tagCategoryVoList) {
        tagCategoryVoList.forEach(tagCategoryVo -> {
            String labelButtonOptionOne = tagCategoryVo.getLabelButtonOptionOne();
            String labelButtonOptionTwo = tagCategoryVo.getLabelButtonOptionTwo();
            if(StringUtils.isNotBlank(labelButtonOptionOne)){
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<LabelButtonOptionVo> tagValueVoList1 = objectMapper.readValue(labelButtonOptionOne,
                            new TypeReference<List<LabelButtonOptionVo>>() {});
                    tagCategoryVo.setLabelButtonOption1(tagValueVoList1);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
            if(StringUtils.isNotBlank(labelButtonOptionTwo)){
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<LabelButtonOptionVo> tagValueVoList2 = objectMapper.readValue(labelButtonOptionTwo,
                            new TypeReference<List<LabelButtonOptionVo>>() {});
                    tagCategoryVo.setLabelButtonOption2(tagValueVoList2);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return tagCategoryVoList;
    }




    /**
     * 构造树形结构方法
     *
     * @param allTags 所有标签列表
     * @return 构造完成后的标签列表
     */
//    private List<TagCategory> buildTagTree(List<TagCategory> allTags) {
//        Map<Integer, List<TagCategory>> tagMap = allTags.stream()
//                .collect(Collectors.groupingBy(TagCategory::getParentTagId));
//        List<TagCategory> rootTags = tagMap.getOrDefault(0, Collections.emptyList());
//        rootTags.forEach(tag -> buildChildren(tag, tagMap));
//        return rootTags;
//    }

    /**
     * 构造树形结构方法
     *
     * @param parentTagCategory 父标签
     * @param tagMap 父标签ID分组MAP
     */
//    private void buildChildren(TagCategory parentTagCategory, Map<Integer, List<TagCategory>> tagMap) {
//        List<TagCategory> children = tagMap.getOrDefault(parentTagCategory.getId(), Collections.emptyList());
//        parentTagCategory.setChildrenTag(children);
//        children.forEach(child -> buildChildren(child, tagMap));
//    }


}
