package com.pj.project.tb_district;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service: tb_district -- 全国地区表
 *
 * @author qzyReal
 */
@Service
public class TbDistrictService extends ServiceImpl<TbDistrictMapper, TbDistrict> implements IService<TbDistrict> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbDistrictMapper tbDistrictMapper;

    /**
     * 增
     */
    int add(TbDistrict t) {
        return tbDistrictMapper.add(t);
    }

    /**
     * 删
     */
    int delete(Integer id) {
        return tbDistrictMapper.delete(id);
    }

    /**
     * 改
     */
    int update(TbDistrict t) {
        return tbDistrictMapper.update(t);
    }

    /**
     * 查
     */
    TbDistrict getById(Integer id) {
        return tbDistrictMapper.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbDistrict> getList(SoMap so) {
        return tbDistrictMapper.getList(so);
    }


    public List<TbDistrict> GetListProvince() {
        QueryWrapper<TbDistrict> ew = new QueryWrapper<>();
        ew.eq("pid", 1);
        return this.list(ew);
    }

    public List<TbDistrict> GetListCity(Long areaId) {
        QueryWrapper<TbDistrict> ew = new QueryWrapper<>();
        ew.eq("pid", areaId);
        return this.list(ew);
    }

    TimedCache<String, List<TbDistrict>> timedCache = CacheUtil.newTimedCache(999999999);

    public List<TbDistrict> getTreeData() {
        List<TbDistrict> cacheList = timedCache.get("address");
        if (cacheList != null && cacheList.size() > 0) {
            return cacheList;
        }
        List<TbDistrict> list = this.GetListProvince();
        list.forEach(tbDistrict -> {
            List<TbDistrict> cityList = this.GetListCity(tbDistrict.getId());
            tbDistrict.setChildren(cityList);
            cityList.forEach(city -> {
                List<TbDistrict> areaList = this.GetListCity(city.getId());
                city.setChildren(areaList);
            });
        });
        timedCache.put("address", list);
        return list;
    }
}
