package com.crunii.micro.service.sysmgr.service.impl;

import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.service.sysmgr.dto.sysmgr.TsmChinaRegionReqDTO;
import com.crunii.micro.service.sysmgr.dto.sysmgr.TsmChinaRegionResVO;
import com.crunii.micro.service.sysmgr.dto.sysmgr.TsmChinaRegionVO;
import com.crunii.micro.service.sysmgr.jdbc.TsmChinaRegionDao;
import com.crunii.micro.service.sysmgr.service.TsmChinaRegionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * youth-cq.
 * 全国统计用区划代码和城乡划分编码
 * @author leixb
 * @since 2023-12-05 16:48
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class TsmChinaRegionServiceImpl implements TsmChinaRegionService {
    
    private final TsmChinaRegionDao tsmChinaRegionDao;
    
    /** 层级：1-省级；2-市；3-区县；4-街道；5-社区/村 */
    private static final String[] LEVEL = {"1", "2", "3", "4", "5"};
    
    @Override
    public List<TsmChinaRegionResVO> findRegion(Worker worker, TsmChinaRegionReqDTO req) {
        if (StringUtils.isBlank(req.getRegionLevel())) {
            throw new BusinessException("层级为空！");
        }
        if (!LEVEL[0].equals(req.getRegionLevel()) && StringUtils.isBlank(req.getParentCode())) {
            throw new BusinessException("上级编码为空！");
        }
        List<TsmChinaRegionVO> resList = tsmChinaRegionDao.findRegion(req);
        List<TsmChinaRegionResVO> resVOList = new ArrayList<>();
        if (null == resList) {
            return resVOList;
        }
        resList.forEach(vo -> {
            TsmChinaRegionResVO resVO = new TsmChinaRegionResVO();
            resVO.setCode(vo.getCode());
            resVO.setName(vo.getName());
            resVO.setRegionLevel(vo.getRegionLevel());
            if (LEVEL[1].equals(vo.getRegionLevel())) {
                resVO.setParentCode(vo.getProvinceCode());
            } else if (LEVEL[2].equals(vo.getRegionLevel())) {
                resVO.setParentCode(vo.getCityCode());
            } else if (LEVEL[3].equals(vo.getRegionLevel())) {
                resVO.setParentCode(vo.getAreaCode());
            } else if (LEVEL[4].equals(vo.getRegionLevel())) {
                resVO.setParentCode(vo.getStreetCode());
            }
            resVOList.add(resVO);
        });
        return resVOList;
    }
    
}
