/**
 * Copyright &copy; 2021-2026 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.sys.service;

import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.core.service.TreeService;
import com.jeeplus.sys.domain.Area;
import com.jeeplus.sys.mapper.AreaMapper;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 区域Service
 *
 * @author jeeplus
 * @version 2021-05-16
 */
@Service
@Transactional
public class AreaService extends TreeService <AreaMapper, Area> {

    @Autowired
    private AreaMapper areaMapper;

    @Cacheable(cacheNames = CacheNames.SYS_CACHE_AREA_LIST)
    public List <Area> findAll() {
        return super.list ( );
    }

    @CacheEvict(cacheNames = CacheNames.SYS_CACHE_AREA_LIST, allEntries = true)
    public boolean saveOrUpdate(Area area) {
        return super.saveOrUpdate ( area );
    }

    @CacheEvict(cacheNames = CacheNames.SYS_CACHE_AREA_LIST, allEntries = true)
    public boolean removeWithChildrenById(String id) {
        return super.removeWithChildrenById ( id );
    }

    @Cacheable(cacheNames = CacheNames.SYS_CACHE_AREA_LIST)
    public List<String> getParent(String extId) {
        if (StringUtils.isEmpty(extId)){
            return null;
        }
        List<Area> all = this.findAll();
        HashMap<String, String> hashMap = new HashMap<>();
        for (Area area : all) {
            hashMap.put(area.getId(),area.getName());
        }
        Area area = areaMapper.selectById(extId);
        ArrayList<String> areas = new ArrayList<>();
        String[] split = area.getParentIds().split(",");
        for (int i = 0; i < split.length; i++) {
            if (split[i].equals("")){
                break;
            }else {
                if (split[i].equals(0)){
                    continue;
                }else {
                    areas.add(hashMap.get(split[i]));
                }
            }
        }
        areas.add(hashMap.get(extId));
        return areas;
    }
}
