package com.pangu.base.service.impl;

import com.pangu.base.domain.Region;
import com.pangu.base.mapper.RegionMapper;
import com.pangu.base.service.IRegionService;
import com.pangu.common.utils.DateUtils;
import com.pangu.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 区域管理Service实现
 * @author pangu
 */
@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<Region> selectRegionTree() {
        // 查询所有区域
        List<Region> regionList = regionMapper.selectRegionList(new Region());
        // 构建树形结构
        return buildRegionTree(regionList);
    }

    /**
     * 构建区域树
     */
    private List<Region> buildRegionTree(List<Region> regionList) {
        List<Region> rootList = new ArrayList<>();
        Map<Long, Region> regionMap = regionList.stream()
                .collect(Collectors.toMap(Region::getRegionId, r -> r));

        for (Region region : regionList) {
            if (region.getParentId() == null || region.getParentId() == 0) {
                rootList.add(region);
            } else {
                Region parent = regionMap.get(region.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(region);
                }
            }
        }
        return rootList;
    }

    @Override
    public List<Region> selectRegionList(Region region) {
        return regionMapper.selectRegionList(region);
    }

    @Override
    public Region selectRegionById(Long regionId) {
        return regionMapper.selectRegionById(regionId);
    }

    @Override
    public int insertRegion(Region region) {
        // 设置层级和祖级列表
        if (region.getParentId() == null || region.getParentId() == 0) {
            region.setParentId(0L);
            region.setLevel(1);
            region.setAncestors("0");
        } else {
            Region parent = regionMapper.selectRegionById(region.getParentId());
            if (parent != null) {
                region.setLevel(parent.getLevel() + 1);
                region.setAncestors(parent.getAncestors() + "," + parent.getRegionId());
            }
        }

        // 生成区域编码
        region.setRegionCode(generateRegionCode(region));
        region.setCreateTime(DateUtils.getNowDate());
        return regionMapper.insertRegion(region);
    }

    /**
     * 生成区域编码
     */
    private String generateRegionCode(Region region) {
        if (region.getParentId() == null || region.getParentId() == 0) {
            // 省级：REG + 2位序号
            String maxCode = regionMapper.selectMaxCodeByLevel(1);
            if (StringUtils.isEmpty(maxCode)) {
                return "REG01";
            }
            int num = Integer.parseInt(maxCode.substring(3)) + 1;
            return String.format("REG%02d", num);
        } else {
            // 市/区级：父编码 + 2位序号
            Region parent = regionMapper.selectRegionById(region.getParentId());
            String maxCode = regionMapper.selectMaxCodeByParent(region.getParentId());
            if (StringUtils.isEmpty(maxCode)) {
                return parent.getRegionCode() + "01";
            }
            String suffix = maxCode.substring(parent.getRegionCode().length());
            int num = Integer.parseInt(suffix) + 1;
            return parent.getRegionCode() + String.format("%02d", num);
        }
    }

    @Override
    public int updateRegion(Region region) {
        region.setUpdateTime(DateUtils.getNowDate());
        return regionMapper.updateRegion(region);
    }

    @Override
    public int deleteRegionById(Long regionId) {
        return regionMapper.deleteRegionById(regionId);
    }

    @Override
    public boolean hasChildRegion(Long regionId) {
        int count = regionMapper.countChildByParentId(regionId);
        return count > 0;
    }

    @Override
    public Long getRegionIdByPath(String regionPath) {
        if (StringUtils.isEmpty(regionPath)) {
            return null;
        }
        
        // 解析区域路径：湖北省-武汉市-武昌区
        String[] parts = regionPath.split("-");
        if (parts.length == 0) {
            return null;
        }
        
        // 从最后一级开始查询（区 -> 市 -> 省）
        String regionName = parts[parts.length - 1];
        List<Region> regions = regionMapper.selectRegionList(new Region());
        
        for (Region region : regions) {
            if (regionName.equals(region.getRegionName())) {
                return region.getRegionId();
            }
        }
        
        return null;
    }
}
