package com.testor.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.dict.type.model.domain.SysDictType;
import com.testor.biz.sys.dict.type.service.SysDictTypeService;
import com.testor.common.util.StreamUtils;
import com.testor.module.sys.service.NewSysDictDataService;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class NewSysDictDataServiceImpl implements NewSysDictDataService {

    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Override
    public SysDictData getDictTypeDetail(String dictDataId, String dictType, String dictKey) {
        if (StringHelper.isNotEmpty(dictDataId)) {
            SysDictData data = (SysDictData) this.sysDictDataService.getById(dictDataId);
            return data;
        } else if (StringHelper.isNotEmpty(dictType) && StringHelper.isNotEmpty(dictKey)) {
            SysDictType one = (SysDictType) this.sysDictTypeService.getOne((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("dict_type", dictType)).ne("status", "1"));
            SysDictData data = null;
            if (ObjectHelper.isNotEmpty(one)) {
                String dictId = one.getDictId();
                data = (SysDictData) this.sysDictDataService.getOne((Wrapper) ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper()).eq("dict_id", dictId)).eq("dict_key", dictKey)).ne("status", "1")).last("LIMIT 1"));
            }
            if (ObjectHelper.isNotEmpty(data)) {
                return data;
            }
        }
        return null;
    }

    @Override
    public List<SysDictData> getDictByType(String dictType) {
        SysDictType one = this.sysDictTypeService.getOne(new QueryWrapper<SysDictType>().eq("dict_type", dictType).ne("status", "1"));
        if (ObjectHelper.isNotEmpty(one)) {
            String dictId = one.getDictId();
            return sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, dictId).ne(SysDictData::getStatus, "1"));
        }
        return Collections.emptyList();
    }

    @Override
    public String getDictId(String type, String dictValue, String separator) {
        // 根据type获取字典数据
        List<SysDictData> dictByType = getDictByType(type);
        // 将字典数据转换为Map，key为dictValue，value为dictDataId
        Map<String, String> map = StreamUtils.toMap(dictByType, SysDictData::getDictValue, SysDictData::getDictDataId);
        // 判断dictValue中是否包含separator
        if (StringUtils.containsAny(dictValue, separator)) {
            // 如果包含，则将dictValue按照separator分割，并从map中获取对应的value，最后将value拼接起来
            return Arrays.stream(dictValue.split(separator))
                    .map(v -> map.getOrDefault(v, StringUtils.EMPTY))
                    .collect(Collectors.joining(separator));
        } else {
            // 如果不包含，则直接从map中获取对应的value
            return map.getOrDefault(dictValue, StringUtils.EMPTY);
        }
    }

    @Override
    public String getDictIdByKey(String dictType, String dictKey) {
        SysDictType one = this.sysDictTypeService.getOne(new QueryWrapper<SysDictType>().eq("dict_type", dictType).ne("status", "1"));
        if (ObjectHelper.isNotEmpty(one)) {
            SysDictData sysDictData = sysDictDataService.getOne(new QueryWrapper<SysDictData>().eq("dict_id", one.getDictId()).eq("dict_key", dictKey).ne("status", "1"));
            if (ObjectHelper.isNotEmpty(sysDictData)) {
                return sysDictData.getDictDataId();
            }
        }
        return null;
    }

    @Override
    public String getDictValue(String id, String separator) {
        SysDictData data = this.sysDictDataService.getById(id);
        if (ObjectHelper.isNotEmpty(data)) {
            return data.getDictValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String getDictDetailedValue(String id, String separator) {
        return buildDictValuePath(id, "", separator);
    }

    /**
     * 递归构建字典值路径
     *
     * @param dictDataId 当前字典数据的ID
     * @param path 当前拼接的路径
     * @return 拼接的字典值路径
     */
    private String buildDictValuePath(String dictDataId, String path,String separator) {
        SysDictData dictData = sysDictDataService.getById(dictDataId);
        if (dictData == null) {
            return path;  // 如果没有找到字典数据，返回当前路径
        }

        // 如果parentId不是0，则继续递归查找父级
        if (!"0".equals(dictData.getParentId())) {
            String parentPath = buildDictValuePath(dictData.getParentId(), path, separator);
            return parentPath + separator + dictData.getDictValue();
        }

        // 如果是顶级节点，直接拼接当前节点的值
        return dictData.getDictValue() + (path.isEmpty() ? "" : separator + path);
    }

    @Override
    public SysDictData getDictByParentIdAndValue(String parentId, String value) {
        return sysDictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getParentId, parentId).eq(SysDictData::getDictValue, value));
    }

    @Override
    public SysDictData getDictByTypeAndValue(String type, String value) {
        SysDictType dictType = this.sysDictTypeService.getOne(new QueryWrapper<SysDictType>().eq("dict_type", type).ne("status", "1"));
        if (ObjectHelper.isNotEmpty(dictType)) {
            return sysDictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, dictType.getDictId()).eq(SysDictData::getDictValue, value));
        }
        return null;
    }

    @Override
    public List<String> getDictIdsByParentKeyAndType(String parentKey, String type) {
        SysDictType dictType = this.sysDictTypeService.getOne(new QueryWrapper<SysDictType>().eq("dict_type", type).ne("status", "1"));
        if (ObjectHelper.isNotEmpty(dictType)) {
            //获取父级
            SysDictData parentDict = sysDictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, dictType.getDictId()).eq(SysDictData::getDictKey, parentKey));
            if (ObjectHelper.isNotEmpty(parentDict)) {
                String dictDataId = parentDict.getDictDataId();
                //获取子级
                List<SysDictData> dictDataList = sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getParentId, dictDataId));
                if (ObjectHelper.isNotEmpty(dictDataList)) {
                    return dictDataList.stream().map(SysDictData::getDictDataId).collect(Collectors.toList());
                }
            }
        }
        return Collections.emptyList();
    }

    @Override
    public SysDictData getDictDataById(String dictDataId) {
        return sysDictDataService.getById(dictDataId);
    }

    @Override
    public List<SysDictData> getDictId(String dictId) {
        List<SysDictType> list = this.sysDictTypeService.list(new QueryWrapper<SysDictType>().eq("dict_id", dictId));
        if (ObjectHelper.isNotEmpty(list)) {
            return sysDictDataService.list(new QueryWrapper<SysDictData>().eq("dict_id", dictId));
        }
        return Collections.emptyList();
    }

    /**
     * 根据字典ID获取所有字典值（优化版）
     * @param dictId 字典ID
     * @return 字典值列表
     */
    public List<String> getDictValuesByDictId(String dictId) {
        // 直接查询字典数据表，不需要先检查字典类型表
        List<SysDictData> dictDataList = sysDictDataService.list(
                new QueryWrapper<SysDictData>()
                        .eq("dict_id", dictId)
                        .orderByAsc("tree_sort") // 按排序字段排序
        );

        if (ObjectHelper.isNotEmpty(dictDataList)) {
            return dictDataList.stream()
                    .map(SysDictData::getDictValue)
                    .filter(value -> value != null && !value.trim().isEmpty())
                    .collect(Collectors.toList());
        }

        return Collections.emptyList();
    }

}
