package com.hzs.retail.sale.controller.api;

import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.retail.sale.vo.RetailAddressVO;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.third.delivery.IDeliveryServiceApi;
import com.hzs.third.delivery.dto.DeliveryDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;

/**
 * @Description: 新零售地址管理控制器
 * @Author: jiang chao
 * @Time: 2024/12/26 16:54
 * @Classname: ApiRetailAddressController
 * @PackageName: com.hzs.retail.sale.controller.api
 */
@Slf4j
@RestController
@RequestMapping("/api/retail-address")
public class ApiRetailAddressController {

    @DubboReference
    IDeliveryServiceApi iDeliveryServiceApi;
    @DubboReference
    IAreaServiceApi iAreaServiceApi;

    /**
     * 自动获取地址
     *
     * @param address 地址信息
     * @return
     */
    @GetMapping("/auto-address")
    public AjaxResult autoAddress(@RequestParam String address) {
        DeliveryDTO deliveryDTO = iDeliveryServiceApi.autoAddress(address);
        if (null == deliveryDTO) {
            return AjaxResult.error("地址解析失败");
        }

        // 根据省区市编码，获取地址ID
        Map<String, BdArea> areaMap = iAreaServiceApi.getAreaMapByCode(Arrays.asList(deliveryDTO.getProvinceCode(), deliveryDTO.getCityCode(), deliveryDTO.getCountyCode())).getData();
        // 收货省
        Integer recProvince = null;
        if (null != areaMap.get(deliveryDTO.getProvinceCode())) {
            recProvince = areaMap.get(deliveryDTO.getProvinceCode()).getPkId();
        }
        // 收货市
        Integer recCity = null;
        if (null != areaMap.get(deliveryDTO.getCityCode())) {
            recCity = areaMap.get(deliveryDTO.getCityCode()).getPkId();
        }
        // 收货县
        Integer recCounty = null;
        if (null != areaMap.get(deliveryDTO.getCountyCode())) {
            recCounty = areaMap.get(deliveryDTO.getCountyCode()).getPkId();
        }

        // 返回地址信息
        return AjaxResult.success(RetailAddressVO.builder()
                .recName(deliveryDTO.getPerson())
                .recPhone(deliveryDTO.getPhoneNum())
                .recProvince(recProvince)
                .recCity(recCity)
                .recCounty(recCounty)
                .recAddress(deliveryDTO.getDetail())
                .build());
    }

}
