package com.ruoyi.system.timing;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.AMapConstants;
import com.ruoyi.common.core.domain.AMapResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.TElectronicFence;
import com.ruoyi.system.domain.TElectronicFenceKey;
import com.ruoyi.system.domain.TElectronicFenceService;
import com.ruoyi.system.domain.TShouhuanInfo;
import com.ruoyi.system.mapper.TDeviceListMapper;
import com.ruoyi.system.mapper.TElectronicFenceMapper;
import com.ruoyi.system.service.ITElectronicFenceKeyService;
import com.ruoyi.system.service.ITElectronicFenceServiceService;
import com.ruoyi.system.service.impl.TElectronicFenceServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @ClassName: GeofenceDeleteTiming
 * @Author: 于学智
 * @Description: 高德地图删除围栏定时任务
 * @CreateDate: 2023/9/14 18:22
 * @Version: 1.0
 * @E-mail:18722650553@139.com
 * @Link:https://github.com/18722650553
 */

@Component("geofenceDeleteTiming")
public class GeofenceDeleteTiming {
    private static final Logger log = LoggerFactory.getLogger(GeofenceDeleteTiming.class);

    @Autowired
    private TElectronicFenceMapper tElectronicFenceMapper;
    @Autowired
    private ITElectronicFenceKeyService iElectronicFenceKeyService;
    @Autowired
    private ITElectronicFenceServiceService iElectronicFenceServiceService;

    /**
     * 检测已删除的围栏信息
     */
    public void checkGeofenceDelete() {
        //获取表中已删除的围栏
        List<TElectronicFence> tElectronicFences = tElectronicFenceMapper.selectTElectronicFenceByDelState(1);
        if (tElectronicFences != null && !tElectronicFences.isEmpty()) {
            //获取单个要删除的围栏信息
            for (TElectronicFence fence : tElectronicFences) {
                //通过围栏serviceId获取service
                TElectronicFenceService fenceService = iElectronicFenceServiceService.selectTElectronicFenceServiceById(fence.getServiceId());
                if (fenceService == null) {
                    log.error("围栏对应的高德服务为空，围栏ID：{}.", fence.getServiceId());
                    continue;
                }
                TElectronicFenceKey tElectronicFenceKey = iElectronicFenceKeyService.selectTElectronicFenceKeyById(fenceService.getKeyId());
                if (tElectronicFenceKey == null) {
                    log.error("围栏对应的高德key为空，围栏ID：{}. 服务ID：{}", fence.getId(), fence.getServiceId());
                    continue;
                }
                //TODO 单个删除围栏，后期整合
                String result = sendGeoDel(tElectronicFenceKey.getAmapKey(), fenceService.getAmapSid(), fence.getGfid());
                if (!StringUtils.isEmpty(result)) {
                    List<Long> gfids = JSONObject.parseArray(result, Long.class);
                    gfids.add(1140869L);
                    if (gfids!=null&&!gfids.isEmpty()){
                        //数据库真是删除
                        tElectronicFenceMapper.deleteTElectronicFenceByGfids(gfids.toArray(new Long[0]));
                    }
                }
            }
        }
    }

    /**
     * 通过高德接口删除围栏
     *
     * @param fenceKey
     * @param fenceService
     * @param gfids
     * @return
     */
    private String sendGeoDel(String fenceKey, String fenceService, String gfids) {
        //创建圆形围栏
        Map<Object, Object> params = new HashMap();
        params.put("key", fenceKey);
        params.put("sid", fenceService);
        params.put("gfids", gfids);
        String paramsString = HttpUtils.getParamsToString(params);
        // 去掉最后一个"&"符号
        String result = HttpUtils.sendPost(AMapConstants.AMAP_TRACK_SERVICE_DELETE, paramsString);
        log.info("删除高德围栏Url：{} ,\n返回结果：{}", AMapConstants.AMAP_TRACK_SERVICE_DELETE + "?" + paramsString, result);
        AMapResult<Map<String, String>> aMapResult = JSONObject.parseObject(result, AMapResult.class);
        if (aMapResult != null && aMapResult.getData() != null && aMapResult.getData().containsKey("gfids")) {
            return String.valueOf(aMapResult.getData().get("gfids"));
        }
        log.info("删除高德围栏异常，key：{}，gfids：{} ，code：{} ,msg:{}", fenceKey, gfids, aMapResult.getErrmsg(), aMapResult.getErrdetail());
        return null;
    }
}
