package com.ruoyi.ibs.custmap.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.custmap.domain.entity.DeptAddress;
import com.ruoyi.ibs.custmap.mapper.DeptAddressMapper;
import com.ruoyi.ibs.grid.domain.dto.BaiduResponseDTO;
import com.ruoyi.ibs.grid.domain.vo.AddressResultVO;
import com.ruoyi.ibs.grid.service.AddressAnalyseService;
import com.ruoyi.ibs.grid.service.BaiduApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2025/5/26
 **/
@Service
@Slf4j
public class DeptAddressService {

    @Resource
    private DeptAddressMapper deptAddressMapper;

    @Resource
        private BaiduApiService baiduApiService;

    @Resource
    private AddressAnalyseService addressAnalyseService;

    public DeptAddress selectDeptAddressById() {
        return deptAddressMapper.selectById(SecurityUtils.getDeptId());
    }

    public void initDeptAddress() {
        List<DeptAddress> deptAddresses = deptAddressMapper.selectList(new LambdaQueryWrapper<>());
        for (DeptAddress deptAddress : deptAddresses) {
            if (Objects.nonNull(deptAddress.getLat()) || Objects.isNull(deptAddress.getAddress())){
                continue;
            }
            BaiduResponseDTO geocoding = baiduApiService.geocoding(deptAddress.getAddress());
            log.info(geocoding.toString());
            if (Objects.isNull(geocoding.getResult())){
                continue;
            }
            deptAddress.setLng(geocoding.getResult().getLocation().getLng());
            deptAddress.setLat(geocoding.getResult().getLocation().getLat());

            AddressResultVO addressResultVO = addressAnalyseService.pointInGeometry(deptAddress.getLng(), deptAddress.getLat());
            if (addressResultVO.getStatus() == 0) {
                deptAddress.setCity(addressResultVO.getCity());
            }
            deptAddressMapper.updateById(deptAddress);
        }
    }


}
