package com.cool.store.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.RegionAreaConfigDao;
import com.cool.store.dao.RegionDao;
import com.cool.store.entity.RegionDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.ThirdRegionTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.RegionMapper;
import com.cool.store.service.RegionService;
import com.cool.store.utils.RedisConstantUtil;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.constant.Constants;
import com.cool.store.vo.RegionPathNameVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.cool.store.enums.ErrorCodeEnum.PARAMS_VALIDATE_ERROR;

/**
 * @ClassName RegionServiceImpl
 * @Description 区域服务
 */
@Slf4j
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RedisConstantUtil redisConstantUtil;
    @Resource
    private RedisUtilPool redisUtilPool;
    @Resource
    private RegionMapper regionMapper;
    @Resource
    private RegionDao regionDao;
    @Resource
    private RegionAreaConfigDao regionAreaConfigDao;


    @Override
    public RegionPathNameVO getAllRegionName(Long regionId) {
        RegionDO regionDO = regionMapper.getByRegionId(regionId);
        if(regionDO == null){
            return null;
        }

        if(regionDO.getDeleted() || StringUtils.isBlank(regionDO.getRegionPath()) || CommonConstants.LONG_ONE.equals(regionDO.getId())){
            return RegionPathNameVO.builder().allRegionName(regionDO.getName()).regionNameList(Arrays.asList(regionDO.getName())).build();
        }
        //若果在缓存中存在，从缓存中去取
        String regionNameListStr = redisUtilPool.getString(redisConstantUtil.getRegionNameListKey(String.valueOf(regionId)));
        if(StringUtils.isNotBlank(regionNameListStr)){
            RegionPathNameVO regionPathNameVO = JSONObject.parseObject(regionNameListStr, RegionPathNameVO.class);
            if(regionPathNameVO == null){
                regionPathNameVO = new RegionPathNameVO();
            }
            return regionPathNameVO;
        }
        String regionPath = regionDO.getRegionPath().substring(1, regionDO.getRegionPath().length() - 1);
        String[] regionIdArr = regionPath.split(Constants.FORWARD_SLASH);
        List<RegionDO> regionDOList = regionMapper.getRegionByRegionIds(Arrays.asList(regionIdArr));
        Map<Long, String> regionNameMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(regionDOList)){
            regionNameMap = regionDOList.stream().collect(Collectors.toMap(RegionDO::getId,RegionDO::getName));
        }
        List<String> regionNameList = new ArrayList<>();
        StringBuilder allRegionName = new StringBuilder();
        for (String id : regionIdArr){
            if(StringUtils.isBlank(id) || !regionNameMap.containsKey(Long.valueOf(id))){
                continue;
            }
            allRegionName.append(regionNameMap.get(Long.valueOf(id))).append(Constants.M_LINE);
            regionNameList.add(regionNameMap.get(Long.valueOf(id)));
        }
        allRegionName.append(regionDO.getName());
        regionNameList.add(regionDO.getName());
        RegionPathNameVO regionPathNameVO = RegionPathNameVO.builder().allRegionName(allRegionName.toString()).regionNameList(regionNameList).build();
        //放在缓存中存5分钟
        redisUtilPool.setString(redisConstantUtil.getRegionNameListKey(String.valueOf(regionId)), JSONUtil.toJsonStr(regionPathNameVO), 5 * 60);
        return regionPathNameVO;
    }

    @Override
    public String getBelongWarRegionName(Long regionId) {
        RegionDO regionDO = regionMapper.getByRegionId(regionId);
        if(regionDO != null){
            return regionDO.getName();
        }
        return "";
    }

    @Override
    public Map<Long, String> getBelongWarRegionNameMap(List<Long> regionIds) {
        if(CollectionUtils.isEmpty(regionIds)){
            return Maps.newHashMap();
        }
        List<RegionDO> regionList = regionMapper.getByIds(regionIds);
        return regionList.stream().collect(Collectors.toMap(RegionDO::getId, RegionDO::getName));
    }

    /**
     * 根据意向区域找大区id
     * @param wantShopAreaId
     * @return
     */
    @Override
    public Long getBigRegionIdByAreaId(Long wantShopAreaId) {
        // 根据意向省市获取战区id
        Long warRegionId = regionAreaConfigDao.getByWantShopAreaId(wantShopAreaId);
        if(Objects.isNull(warRegionId)){
            return 0L;
        }
        return  warRegionId;
//        RegionDO warRegion = regionMapper.getByRegionId(warRegionId);
//        if(warRegion == null){
//            throw new ServiceException(ErrorCodeEnum.REGION_NOT_EXIST);
//        }
//        //  根据战区id获取大区id
//        String warRegionPath = warRegion.getRegionPath().substring(1, warRegion.getRegionPath().length() - 1);
//        String[] warRegionIdArr = warRegionPath.split(Constants.FORWARD_SLASH);
//        List<RegionDO> regionDOList = regionMapper.getRegionByRegionIds(Arrays.asList(warRegionIdArr));
//        for (RegionDO regionDO : regionDOList){
//            if(ThirdRegionTypeEnum.LARGE_REGION.getCode().equals(regionDO.getThirdRegionType())){
//                return regionDO.getId();
//            }
//        }
//        return 0L;
    }

    @Override
    public List<RegionDO> listByThirdRegionType(Long parentId, String thirdRegionType) {
        if(Objects.isNull(parentId) && StringUtils.isBlank(thirdRegionType)){
            throw new ServiceException(PARAMS_VALIDATE_ERROR);
        }
        return regionDao.listByThirdRegionType(parentId, thirdRegionType);
    }

    @Override
    public List<String> getSubRegionIdsByRegionIds(List<String> regionIds) {
        if(CollectionUtils.isEmpty(regionIds)){
            return Lists.newArrayList();
        }
        List<String> subRegionIds = regionMapper.getSubRegionIdsByRegionIds(regionIds);
        if(CollectionUtils.isNotEmpty(subRegionIds)){
            regionIds.addAll(subRegionIds);
        }
        return regionIds;
    }
}
