package com.ghy.customer.service.impl;

import com.ghy.customer.domain.CustomerAddress;
import com.ghy.customer.mapper.CustomerAddressMapper;
import com.ghy.customer.service.CustomerAddressService;
import com.ghy.system.service.ISysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.utils.http.HttpUtils;

@Slf4j
@Service
public class CustomerAddressServiceImpl implements CustomerAddressService {

    @Resource
    private CustomerAddressMapper customerAddressMapper;

    @Resource
    private ISysAreaService iSysAreaService;
    
    private static final Logger logger = LoggerFactory.getLogger(CustomerAddressServiceImpl.class);

    @Override
    public List<CustomerAddress> getCustomerAddressList(CustomerAddress customerAddress) {
        logger.info("查询地址的参数{}",customerAddress);
        if (customerAddress.getIsDelete()==null) {
            customerAddress.setIsDelete(0L);
        }
        List<CustomerAddress> addressList = customerAddressMapper.getCustomerAddressList(customerAddress);
        logger.info("查询后的地址的值{}",addressList);
        if(customerAddress.getNeedNameFlag()){
            return addressList;
        }
        for (CustomerAddress address : addressList) {
            address.setCountryName(iSysAreaService.selectById(address.getCountryId()).getAreaName());
            address.setCityName(iSysAreaService.selectById(address.getCityId()).getAreaName());
            address.setProvinceName(iSysAreaService.selectById(address.getProvinceId()).getAreaName());
            if(address.getStreetId()!=null){
                address.setStreetName(iSysAreaService.selectById(address.getStreetId()).getAreaName());
            }
        }
        return addressList;
    }

    @Override
    public int deleteByIds(String[] ids) {
        return customerAddressMapper.deleteByIds(ids);
    }

    @Override
    public int deleteByCustomerAddressId(Long customerAddressId) {
        return customerAddressMapper.deleteByCustomerAddressId(customerAddressId);
    }

    @Override
    public List<CustomerAddress> selectByCustomerId(Long customerId) {
        return customerAddressMapper.selectByCustomerId(customerId);
    }

    @Override
    public CustomerAddress selectByCustomerAddressId(Long customerAddressId) {
        CustomerAddress address= customerAddressMapper.selectByCustomerAddressId(customerAddressId);
        address.setCountryName(iSysAreaService.selectById(address.getCountryId()).getAreaName());
        address.setCityName(iSysAreaService.selectById(address.getCityId()).getAreaName());
        address.setProvinceName(iSysAreaService.selectById(address.getProvinceId()).getAreaName());
        if(address.getStreetId()!=null){
            address.setStreetName(iSysAreaService.selectById(address.getStreetId()).getAreaName());
        }
        return address;
    }

    @Override
    public int insertCustomerAddress(CustomerAddress customerAddress) {
        // 在插入前自动获取经纬度
        setGeocodingForAddress(customerAddress);
        return customerAddressMapper.insertCustomerAddress(customerAddress);
    }

    @Override
    public int updateCustomerAddress(CustomerAddress customerAddress) {
        // 在更新前自动获取经纬度
        setGeocodingForAddress(customerAddress);
        return customerAddressMapper.updateCustomerAddress(customerAddress);
    }

    @Override
    public CustomerAddress selectByCustomerAndAddress(Long customerId, Long provinceId, Long cityId, Long countryId, String address) {
        return customerAddressMapper.selectByCustomerAndAddress(customerId, provinceId, cityId, countryId, address);
    }

    @Override
    public List<CustomerAddress> selectByIds(List<Long> customerAddressIds) {
        if (customerAddressIds == null || customerAddressIds.isEmpty()) {
            return null;
        }
        return customerAddressMapper.selectByIds(customerAddressIds);
    }
    
    /**
     * 为地址设置经纬度信息
     * 
     * @param customerAddress 客户地址对象
     */
    private void setGeocodingForAddress(CustomerAddress customerAddress) {
        try {
            // 如果已经有经纬度信息，则跳过
            if (customerAddress.getLongitude() != null && customerAddress.getLatitude() != null) {
                logger.info("地址已有经纬度信息，跳过获取");
                return;
            }
            
            // 获取地址名称信息
            String provinceName = null;
            String cityName = null;
            String countryName = null;
            String streetName = null;
            
            if (customerAddress.getProvinceId() != null) {
                try {
                    provinceName = iSysAreaService.selectById(customerAddress.getProvinceId()).getAreaName();
                } catch (Exception e) {
                    logger.warn("获取省份名称失败: {}", e.getMessage());
                }
            }
            
            if (customerAddress.getCityId() != null) {
                try {
                    cityName = iSysAreaService.selectById(customerAddress.getCityId()).getAreaName();
                } catch (Exception e) {
                    logger.warn("获取城市名称失败: {}", e.getMessage());
                }
            }
            
            if (customerAddress.getCountryId() != null) {
                try {
                    countryName = iSysAreaService.selectById(customerAddress.getCountryId()).getAreaName();
                } catch (Exception e) {
                    logger.warn("获取区县名称失败: {}", e.getMessage());
                }
            }
            
            if (customerAddress.getStreetId() != null) {
                try {
                    streetName = iSysAreaService.selectById(customerAddress.getStreetId()).getAreaName();
                } catch (Exception e) {
                    logger.warn("获取街道名称失败: {}", e.getMessage());
                }
            }
            
            // 调用百度地理编码接口获取经纬度
            try {
                JSONObject requestBody = new JSONObject();
                requestBody.put("provinceName", provinceName);
                requestBody.put("cityName", cityName);
                requestBody.put("countryName", countryName);
                requestBody.put("streetName", streetName);
                requestBody.put("address", customerAddress.getAddress());
                
                // 调用百度地理编码接口
                String url = "https://gmhl.gmjlb.com/tool/baidu/geocode";
                String result = HttpUtils.sendPost(url, requestBody.toJSONString());
                
                JSONObject responseJson = JSONObject.parseObject(result);
                if (responseJson.getInteger("code") == 200) {
                    JSONObject data = responseJson.getJSONObject("data");
                    BigDecimal longitude = data.getBigDecimal("longitude");
                    BigDecimal latitude = data.getBigDecimal("latitude");
                    
                    customerAddress.setLongitude(longitude);
                    customerAddress.setLatitude(latitude);
                    logger.info("成功获取地址经纬度: 经度={}, 纬度={}", longitude, latitude);
                } else {
                    logger.warn("百度地理编码接口调用失败: {}", responseJson.getString("msg"));
                }
            } catch (Exception e) {
                logger.error("调用百度地理编码接口异常: {}", e.getMessage(), e);
            }
            
        } catch (Exception e) {
            logger.error("获取地址经纬度失败: {}", e.getMessage(), e);
        }
    }
}
