package com.zfire.mall.manager.logic.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.config.*;
import com.zfire.mall.manager.convert.TradeConfigConvert;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.TradeCategoryConfig;
import com.zfire.mall.manager.plus.service.TradeCategoryConfigService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author qinrongjun
 * @description
 * @date 2023/7/26 14:18 星期三
 */
@RequiredArgsConstructor
@Service
public class TradeConfigLogic {
    private final TradeCategoryConfigService tradeCategoryConfigService;

    public final static String DEFAULT_TOP_LEVEL_ID = "0";

    public boolean del(String id) {
        Integer count = tradeCategoryConfigService.lambdaQuery()
                .eq(TradeCategoryConfig::getParentId, id)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("当前节点存在下级不能删除");
        }
        return tradeCategoryConfigService.removeById(id);
    }

    public boolean add(TradeConfigAddParam param, AdminUserCom adminUser) {
        TradeCategoryConfig tradeCategoryConfig = TradeConfigConvert.INSTANCE.toDO(param, adminUser.getUserName());
        return tradeCategoryConfigService.save(tradeCategoryConfig);
    }

    public boolean edit(TradeConfigEditParam param, AdminUserCom adminUser) {
        TradeCategoryConfig tradeCategoryConfig = TradeConfigConvert.INSTANCE.toDO(param, adminUser.getUserName());
        return tradeCategoryConfigService.updateById(tradeCategoryConfig);
    }

    public IPage<TradeConfigListVO> list(TradeConfigListParam param) {
        Page<TradeCategoryConfig> page = tradeCategoryConfigService.lambdaQuery()
                .like(StringUtils.isNotBlank(param.getKeyword()),TradeCategoryConfig::getName, param.getKeyword())
                .eq(StringUtils.isBlank(param.getKeyword()), TradeCategoryConfig::getParentId, StringUtils.isNotBlank(param.getParentId()) ? param.getParentId() : "0")
                .page(new Page<>(param.getPageNum(), param.getPageSize()));
        return buildPageVO(page);
    }

    /**
     * 根据id查询名称
     * @param idList
     * @return
     */
    public Map<String, String> nameByIdMap(List<String> idList) {
        return tradeCategoryConfigService.lambdaQuery()
                .select(TradeCategoryConfig::getName, TradeCategoryConfig::getId)
                .in(TradeCategoryConfig::getId, idList)
                .list()
                .stream()
                .collect(Collectors.toMap(TradeCategoryConfig::getId, TradeCategoryConfig::getName));

    }

    private Page<TradeConfigListVO> buildPageVO(Page<TradeCategoryConfig> page) {
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new Page<>(page.getCurrent(), page.getSize());
        }
        Set<String> parentIdList = page.getRecords()
                .stream()
                .map(TradeCategoryConfig::getParentId)
                .filter(parentId -> !DEFAULT_TOP_LEVEL_ID.equals(parentId))
                .collect(Collectors.toSet());
        Map<String, String> parentNameByIdMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(parentIdList)) {
             parentNameByIdMap = tradeCategoryConfigService.lambdaQuery()
                    .select(TradeCategoryConfig::getId, TradeCategoryConfig::getName)
                    .in(TradeCategoryConfig::getId, parentIdList)
                    .list()
                    .stream()
                    .collect(Collectors.toMap(TradeCategoryConfig::getId, TradeCategoryConfig::getName));
        }
        return TradeConfigConvert.INSTANCE.toPageVO(page, parentNameByIdMap);
    }

    public List<TradeConfigListLevelVO> listLevel(String keyword) {
        List<TradeCategoryConfig> tradeCategoryConfigList = tradeCategoryConfigService.lambdaQuery()
                .like(StringUtils.isNotBlank(keyword),TradeCategoryConfig::getName, keyword)
                .list();
        return buildLevelPageVO(tradeCategoryConfigList, StringUtils.isNotBlank(keyword));

    }

    private List<TradeConfigListLevelVO> buildLevelPageVO(List<TradeCategoryConfig> records, boolean isSearch) {
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        Map<String, List<TradeCategoryConfig>> childByParentIdMap = records.stream().collect(Collectors.groupingBy(TradeCategoryConfig::getParentId));
        List<TradeCategoryConfig> levelOneList = childByParentIdMap.remove(DEFAULT_TOP_LEVEL_ID);
        // 1. 不是搜索,直接组装上下级
        if (!isSearch) {
            return CollectionUtils.isEmpty(levelOneList) ? Collections.emptyList() : TradeConfigConvert.INSTANCE.toLevelVOList(levelOneList, childByParentIdMap);
        }
        // 2. 搜索
        // 没有子级, 直接返回父级
        if (MapUtils.isEmpty(childByParentIdMap)) {
            return CollectionUtils.isEmpty(levelOneList) ? Collections.emptyList() : TradeConfigConvert.INSTANCE.toVOList(levelOneList);
        }
        // 有子级, 拿子级的父级
        Set<String> parentIdList = childByParentIdMap.keySet();
        List<TradeCategoryConfig> parentList = tradeCategoryConfigService.lambdaQuery()
                .in(TradeCategoryConfig::getId, parentIdList)
                .list();
        // 搜索得到的父级,添加进父级集合,得到完整的树形结构父级数据
        if (CollectionUtils.isNotEmpty(levelOneList)) {
            parentList.addAll(levelOneList);
        }
        return TradeConfigConvert.INSTANCE.toLevelVOList(parentList, childByParentIdMap);
    }
}
