package com.ruoyi.base.area.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.base.area.domain.SysCnArea;
import com.ruoyi.base.area.domain.bo.SysCnAreaBo;
import com.ruoyi.base.area.domain.vo.SysCnAreaVo;
import com.ruoyi.base.area.mapper.SysCnAreaMapper;
import com.ruoyi.base.area.service.ISysCnAreaService;
import com.ruoyi.base.area.service.PrefixConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 行政区域Service业务层处理
 *
 * @author ruoyi
 * @date 2023-06-25
 */
@RequiredArgsConstructor
@Service
public class SysCnAreaServiceImpl implements ISysCnAreaService {

    private final SysCnAreaMapper baseMapper;

    /**
     * 查询行政区域
     *
     * @param id 行政区域主键
     * @return 行政区域
     */
    @Override
    public SysCnAreaVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询行政区域列表
     * @param bo 行政区域
     * @return 行政区域
     */
    @Override
    public TableDataInfo<SysCnAreaVo> queryPageList(SysCnAreaBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysCnArea> lqw = buildQueryWrapper(bo);
        Page<SysCnAreaVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询行政区域列表
     *
     * @param bo 行政区域
     * @return 行政区域
     */
    @Override
    public List<SysCnAreaVo> queryList(SysCnAreaBo bo) {
        LambdaQueryWrapper<SysCnArea> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysCnArea> buildQueryWrapper(SysCnAreaBo bo) {
        LambdaQueryWrapper<SysCnArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLabel()), SysCnArea::getLabel, bo.getLabel());
        lqw.eq(StringUtils.isNotBlank(bo.getValue()), SysCnArea::getValue, bo.getValue());
        lqw.eq(StringUtils.isNotBlank(bo.getParent()), SysCnArea::getParent, bo.getParent());
        lqw.eq(StringUtils.isNotBlank(bo.getLongitude()), SysCnArea::getLongitude, bo.getLongitude());
        lqw.eq(StringUtils.isNotBlank(bo.getLatitude()), SysCnArea::getLatitude, bo.getLatitude());
        lqw.eq(bo.getLevel() != null, SysCnArea::getLevel, bo.getLevel());
        return lqw;
    }

    /**
     * 新增行政区域
     *
     * @param bo 行政区域
     * @return 结果
     */
    @Override
    public Boolean insertByBo(SysCnAreaBo bo) {
        SysCnArea add = BeanUtil.toBean(bo, SysCnArea.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改行政区域
     *
     * @param bo 行政区域
     * @return 结果
     */
    @Override
    public Boolean updateByBo(SysCnAreaBo bo) {
        SysCnArea sysCnArea = baseMapper.selectById(bo.getId());
        SysCnArea update = BeanCopyUtils.copy(bo, sysCnArea);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysCnArea entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除行政区域
     *
     * @param ids 需要删除的行政区域主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    private void cacheTree() {
        List<SysCnArea> all = this.baseMapper.selectList(new LambdaQueryWrapper<SysCnArea>().lt(SysCnArea::getLabel, 4)
            .orderByAsc(SysCnArea::getLabel).orderByAsc(SysCnArea::getInitial).orderByAsc(SysCnArea::getPinyin));
        Map<String, List<SysCnArea>> collect = all.stream().collect(Collectors.groupingBy(SysCnArea::getParent));

        List<SysCnArea> first = collect.get(SysCnArea.CN.getValue());
        first.stream().forEach(o -> {
            List<SysCnArea> two = collect.get(o.getValue());
            if (CollectionUtil.isNotEmpty(two)) {
                two.stream().forEach(t -> {
                    List<SysCnArea> three = collect.get(t.getValue());
                    if (CollectionUtil.isNotEmpty(three)) {
                        t.setChildren(three);
                    }
                });
                o.setChildren(two);
            }
        });
        SysCnArea.CN.setChildren(first);
        RedisUtils.setCacheObject(PrefixConstants.AREA_THREE_LEVEL, JSONUtil.toJsonStr(SysCnArea.CN));
    }

    @Override
    public JSONObject getTreeLbs() {

        String treeStr = RedisUtils.getCacheObject(PrefixConstants.AREA_THREE_LEVEL);
        if (treeStr == null || treeStr == "") {
            this.cacheTree();
            treeStr = RedisUtils.getCacheObject(PrefixConstants.AREA_THREE_LEVEL);
        }

        return JSON.parseObject(treeStr);
    }

    @Override
    public List<SysCnArea> getChildren(String parentCode) {
        return this.baseMapper.selectList(new LambdaQueryWrapper<SysCnArea>()
            .eq(SysCnArea::getParent, parentCode).orderByAsc(SysCnArea::getInitial).orderByAsc(SysCnArea::getPinyin));
    }

    @Override
    public List<SysCnArea> getPath(String code) {
        List<SysCnArea> path = new ArrayList<>();
        while (true) {
            SysCnArea current = this.getByCode(code);
            if (current != null) {
                path.add(current);
                if (!current.getParent().equals(SysCnArea.CN.getValue())) {
                    code = current.getParent();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        Collections.reverse(path);
        return path;
    }

    @Override
    public SysCnArea getByCode(String code) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<SysCnArea>().eq(SysCnArea::getValue, code).last("limit 1"));

    }

    @Override
    public SysCnArea getByLabel(Integer level, String label) {
        return this.baseMapper.selectOne(
            new LambdaQueryWrapper<SysCnArea>()
                .eq(SysCnArea::getLevel, level)
                .eq(SysCnArea::getLabel, label)
                .last("limit 1")
        );
    }

    @Override
    public SysCnArea getByValue(String value) {
        return this.baseMapper.selectOne(
            new LambdaQueryWrapper<SysCnArea>()
                .eq(SysCnArea::getValue, value)
                .last("limit 1")
        );
    }

    @Override
    public void refreshPinYi() {
        List<SysCnArea> sysCnAreas = this.baseMapper.selectList(new LambdaQueryWrapper<SysCnArea>());
        for (SysCnArea sysCnArea : sysCnAreas) {
            sysCnArea.setPinyin(PinyinUtil.getPinyin(sysCnArea.getLabel()));
            sysCnArea.setInitial(StrUtil.sub(sysCnArea.getPinyin(), 0, 1).toUpperCase(Locale.ROOT));
            this.baseMapper.updateById(sysCnArea);
        }
    }

    @Override
    public Map<String, List<SysCnArea>> allCity() {
        String cityInitialStr = RedisUtils.getCacheObject(PrefixConstants.CITY_INITIAL);
        if (cityInitialStr == null || cityInitialStr == "") {
            List<SysCnArea> sysCnAreas = this.baseMapper.selectList(new LambdaQueryWrapper<SysCnArea>()
                .eq(SysCnArea::getLevel, 2)
                .orderByAsc(SysCnArea::getInitial)
                .orderByAsc(SysCnArea::getPinyin)
            );
            //按首字母分组并且按首字母和拼音排序
            Map<String, List<SysCnArea>> collect = sysCnAreas.stream().collect(Collectors.groupingBy(SysCnArea::getInitial));
            RedisUtils.setCacheObject(PrefixConstants.CITY_INITIAL, JSONUtil.toJsonStr(collect));
            return collect;
        }
        // 把从 Redis 中取出的 cityInitialStr 转换成 Map<String, List<SysCnArea>>
        try {
            // 使用 Hutool 的 JSONUtil 进行类型转换
            Map<String, List<SysCnArea>> map = JSONUtil.toBean(cityInitialStr, Map.class);
            return map;
        } catch (Exception e) {
            return Collections.emptyMap();
        }
    }


}
