package com.jeequan.jeepay.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.model.DBApiMapConfig;
import com.jeequan.jeepay.db.entity.LocationCache;
import com.jeequan.jeepay.service.mapper.LocationCacheMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LocationCacheService extends ServiceImpl<LocationCacheMapper, LocationCache> {

    @Autowired private SysConfigService sysConfigService;

    public LocationCache getByAddress(String address) {
        LambdaQueryWrapper<LocationCache> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(LocationCache::getAddress, address);
        LocationCache existCache = getBaseMapper().selectOne(qWrapper);

        if (!refreshFlag(existCache)) {
            return existCache;
        }

        LocationCache entity = null;
        try {

            DBApiMapConfig apiMapConfig = sysConfigService.getDBApiMapConfig();

            String url = "https://restapi.amap.com/v3/geocode/geo";
            Map<String, Object> param = new HashMap<>();
            param.put("address", address);
            param.put("key", apiMapConfig.getApiMapWebServiceKey());

            String respStr = HttpUtil.get(url, param);

            JSONObject respJSON = JSON.parseObject(respStr);

            String location = respJSON.getJSONArray("geocodes").getJSONObject(0).getString("location");
            String[] locations = location.split(",");

            entity = new LocationCache();
            entity.setAddress(address);
            //
            entity.setLongitude(locations[0]);
            entity.setLatitude(locations[1]);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            saveOrUpdate(entity);

        } catch (Exception e) {
            log.error("获取经纬度异常", e);
        }

        return entity;
    }

    /**
     * 判断是否需要更新
     *
     * @param entity
     * @return
     */
    private boolean refreshFlag(LocationCache entity) {
        if (entity == null) {
            return true;
        }

        // 后续可根据时间等刷新经纬度

        return false;
    }
}
