package com.njzscloud.supervisory.gps.jike.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.supervisory.config.JikeProperties;
import com.njzscloud.supervisory.gps.jike.JikeApiClient;
import com.njzscloud.supervisory.gps.jike.JikeResponse;
import com.njzscloud.supervisory.gps.jike.result.JikeMediaResult;
import com.njzscloud.supervisory.gps.jike.result.JikeTrackResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 即刻物联测试接口
 */
@Slf4j
@RestController
@RequestMapping("/gps/jike")
public class JikeTestController {

    private final JikeProperties jikeProperties;

    public JikeTestController(JikeProperties jikeProperties) {
        this.jikeProperties = jikeProperties;
    }

    /**
     * 测试接口连通性
     */
    @RequestMapping("/ping")
    public R<?> ping() {
        try {
            JikeApiClient client = new JikeApiClient(jikeProperties);
            String response = client.doGet("/open-api/health/ping1", "");
            log.info("Jike ping response: {}", response);
            return R.success(JSON.parseObject(response));
        } catch (Exception e) {
            log.error("Jike ping error", e);
            return R.failed();
        }
    }

    /**
     * 历史轨迹查询测试
     * /open-api/gps-trace/list
     *
     * @param carNum 车牌号
     * @param stime  开始时间(格式: yyyy-MM-dd HH:mm:ss)
     * @param etime  结束时间(格式: yyyy-MM-dd HH:mm:ss)
     */
    @RequestMapping("/track_list_test")
    public R<?> trackListTest(
            @RequestParam(required = false) String carNum,
            @RequestParam(required = false) String imei,
            @RequestParam String stime,
            @RequestParam String etime) {
        try {
            JikeApiClient client = new JikeApiClient(jikeProperties);

            Map<String, String> params = new HashMap<>();
            if (carNum != null && !carNum.isEmpty()) {
                params.put("carNum", carNum);
            }
            if (imei != null && !imei.isEmpty()) {
                params.put("imei", imei);
            }
            // 转换为毫秒时间戳
            params.put("stime", String.valueOf(DateUtil.parse(stime).getTime()));
            params.put("etime", String.valueOf(DateUtil.parse(etime).getTime()));

            log.info("Jike track list request params: {}", params);

            String response = client.doGet("/open-api/gps-trace/list", params);
            log.info("Jike track list response: {}", response);

            JikeResponse<List<JikeTrackResult>> result = JSON.parseObject(
                    response,
                    new TypeReference<JikeResponse<List<JikeTrackResult>>>() {}
            );

            if (result.isSuccess()) {
                return R.success(result.getData());
            } else {
                log.error("调用失败: " + result.getHeader().getMessage());
                return R.failed();
            }
        } catch (Exception e) {
            log.error("Jike track list error", e);
            return R.failed();
        }
    }

    /**
     * 多媒体查询测试
     * /open-api/event/interval/media
     *
     * @param carNum 车牌号
     * @param stime  开始时间(格式: yyyy-MM-dd HH:mm:ss)
     * @param etime  结束时间(格式: yyyy-MM-dd HH:mm:ss)
     */
    @RequestMapping("/media_list_test")
    public R<?> mediaListTest(
            @RequestParam(required = false) String carNum,
            @RequestParam(required = false) String imei,
            @RequestParam String stime,
            @RequestParam String etime) {
        try {
            JikeApiClient client = new JikeApiClient(jikeProperties);

            Map<String, String> params = new HashMap<>();
            if (carNum != null && !carNum.isEmpty()) {
                params.put("carNum", carNum);
            }
            if (imei != null && !imei.isEmpty()) {
                params.put("imei", imei);
            }
            // 转换为毫秒时间戳
            params.put("stime", String.valueOf(DateUtil.parse(stime).getTime()));
            params.put("etime", String.valueOf(DateUtil.parse(etime).getTime()));

            // 构建参数字符串
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!first) {
                    sb.append("&");
                }
                sb.append(entry.getKey()).append("=").append(entry.getValue());
                first = false;
            }
            String queryString = sb.toString();

            log.info("Jike media list queryString: {}", queryString);

            String response = client.doGet("/open-api/event/interval/media", queryString);
            log.info("Jike media list response: {}", response);

            JikeResponse<List<JikeMediaResult>> result = JSON.parseObject(
                    response,
                    new TypeReference<JikeResponse<List<JikeMediaResult>>>() {}
            );

            if (result.isSuccess()) {
                return R.success(result.getData());
            } else {
                log.error("调用失败: " + result.getHeader().getMessage());
                return R.failed();
            }
        } catch (Exception e) {
            log.error("Jike media list error", e);
            return R.failed();
        }
    }
}
