package com.ruoyi.web.controller.client;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Region;
import com.ruoyi.system.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 地区信息接口
 */
@RequestMapping("/client/region")
@RestController
public class ClientRegionController {

    @Autowired
    private IRegionService regionService;

    /**
     * 获取省份列表
     */
    @GetMapping("/provinces")
    public AjaxResult getProvinces() {
        Region region = new Region();
        region.setLevel(1); // 省级
        List<Region> provinces = regionService.selectRegionList(region);
        return AjaxResult.success(provinces);
    }

    /**
     * 根据父级编码获取子地区列表
     */
    @GetMapping("/children/{parentCode}")
    public AjaxResult getChildrenByParentCode(@PathVariable("parentCode") String parentCode) {
        Region region = new Region();
        region.setParentCode(parentCode);
        List<Region> children = regionService.selectRegionList(region);
        return AjaxResult.success(children);
    }


    /**
     * 根据地区编码获取完整地址（省市区）
     */
    @GetMapping("/address/{code}")
    public AjaxResult getFullAddress(@PathVariable("code") String code) {
        // 获取当前地区
        Region currentRegion = regionService.selectRegionByCode(code);
        if (currentRegion == null) {
            return AjaxResult.error("地区编码不存在");
        }
        
        List<String> addressParts = new ArrayList<>();
        addressParts.add(currentRegion.getName());
        
        // 获取父级地区
        String parentCode = currentRegion.getParentCode();
        while (parentCode != null) {
            Region parentRegion = regionService.selectRegionByCode(parentCode);
            if (parentRegion == null) {
                break;
            }
            addressParts.add(0, parentRegion.getName());
            parentCode = parentRegion.getParentCode();
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("address", String.join(" ", addressParts));
        result.put("addressParts", addressParts);
        
        return AjaxResult.success(result);
    }
}