package com.usky.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usky.common.core.exception.BusinessException;
import com.usky.ems.domain.EmsSystemDictRegion;
import com.usky.ems.mapper.EmsSystemDictRegionMapper;
import com.usky.ems.service.EmsSystemDictRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * 省市区字典服务
 */
@Service
public class EmsSystemDictRegionServiceImpl implements EmsSystemDictRegionService {

    @Autowired
    private EmsSystemDictRegionMapper emsSystemDictRegionMapper;

    @Override
    public Map<String, String> checkAndBuildMap(String provinceCode, String cityCode, String districtCode) {
        if (!StringUtils.hasText(provinceCode) || !StringUtils.hasText(cityCode) || !StringUtils.hasText(districtCode)) {
            throw new BusinessException("省市区编码不能为空");
        }
        EmsSystemDictRegion province = emsSystemDictRegionMapper.selectOne(
                new LambdaQueryWrapper<EmsSystemDictRegion>().eq(EmsSystemDictRegion::getCode, provinceCode).last("LIMIT 1"));
        EmsSystemDictRegion city = emsSystemDictRegionMapper.selectOne(
                new LambdaQueryWrapper<EmsSystemDictRegion>().eq(EmsSystemDictRegion::getCode, cityCode).last("LIMIT 1"));
        EmsSystemDictRegion district = emsSystemDictRegionMapper.selectOne(
                new LambdaQueryWrapper<EmsSystemDictRegion>().eq(EmsSystemDictRegion::getCode, districtCode).last("LIMIT 1"));
        if (province == null || city == null || district == null) {
            throw new BusinessException("省市区编码无效");
        }
        if (!Objects.equals(city.getParent(), province.getCode())) {
            throw new BusinessException("市级编码与省级不匹配");
        }
        if (!Objects.equals(district.getParent(), city.getCode())) {
            throw new BusinessException("区级编码与市级不匹配");
        }
        Map<String, String> map = new HashMap<>(4);
        map.put(provinceCode, province.getName());
        map.put(cityCode, city.getName());
        map.put(districtCode, district.getName());
        return map;
    }

    @Override
    public List<EmsSystemDictRegion> listByParentCode(String parentCode) {
        if (!StringUtils.hasText(parentCode)) {
            throw new BusinessException("父级编码不能为空");
        }
        return emsSystemDictRegionMapper.selectList(
                new LambdaQueryWrapper<EmsSystemDictRegion>().eq(EmsSystemDictRegion::getParent, parentCode));
    }
}
