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

import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.service.sysmgr.dto.sysmgr.TsmChinaRegionReqDTO;
import com.crunii.micro.service.sysmgr.dto.sysmgr.TsmChinaRegionVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * youth-cq.
 * 全国统计用区划代码和城乡划分编码
 * @author leixb
 * @since 2023-12-05 16:50
 **/
@Repository
public class TsmChinaRegionDao {
    
    @Resource(name = "mainJT")
    protected BaseJdbcTemplate jdbcTemplate;
    
    /** 层级：1-省级；2-市；3-区县；4-街道；5-社区/村 */
    private static final String[] LEVEL = {"1", "2", "3", "4", "5"};
    
    /**
     * 根据查询条件查询区域信息
     *
     * @param req 查询条件
     * @return 区域信息列表
     */
    public List<TsmChinaRegionVO> findRegion(TsmChinaRegionReqDTO req) {
        StringBuilder sql = new StringBuilder(" SELECT code, name, region_level, province_code, city_code, area_code, street_code FROM tsm_china_region WHERE 1 = 1 ");
        List<Object> params = new ArrayList<>();
        String regionLevel = req.getRegionLevel();
        sql.append(" AND region_level = ? ");
        params.add(req.getRegionLevel());
        if (LEVEL[1].equals(regionLevel)) {
            sql.append(" AND province_code =? ");
            params.add(req.getParentCode());
        }
        if (LEVEL[2].equals(regionLevel)) {
            sql.append(" AND city_code =? ");
            params.add(req.getParentCode());
        }
        if (LEVEL[3].equals(regionLevel)) {
            sql.append(" AND area_code =? ");
            params.add(req.getParentCode());
        }
        if (LEVEL[4].equals(regionLevel)) {
            sql.append(" AND street_code =? ");
            params.add(req.getParentCode());
        }
        return jdbcTemplate.queryForBeans(TsmChinaRegionVO.class, sql.toString(), params.toArray());
    }

}
