package com.ruoyi.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.vo.AisShipInfo;
import com.ruoyi.system.domain.vo.ShipEepReportRecInfo;
import com.ruoyi.system.service.IAisInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * @Description: TODO
 * @Author: huangcheng
 * @Date: 2021/9/26
 * @Version V1.0
 */
@Service
@Slf4j
public class AisInfoServiceImpl implements IAisInfoService {

    @Value("${spring.profiles.active}")
    private String profile;
    @Value("${third.shipEepReportRecInfo}")
    private String shipEepReportRecInfoUrl;
    @Value("${third.shipBaseInfo}")
    private String shipBaseInfo;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取船舶进出港记录
     *
     * @param startTime
     * @param endTime
     * @param mmsi
     * @param shipId
     * @param shipNameCn
     * @return
     */
    @Override
    public ShipEepReportRecInfo getShipEepReportRecInfo(String startTime, String endTime, String mmsi, String shipId, String shipNameCn) {
        if ("prod".equals(profile) && StrUtil.isNotBlank(mmsi) && mmsi.length() == 9) {
            Map<String, Object> params = new HashMap<>();
            params.put("startTime", startTime);
            params.put("endTime", endTime);
            params.put("mmsi", mmsi);
//            params.put("shipId", shipId);
//            params.put("shipNameCn", shipNameCn);
            try {
                String para = HttpUtil.toParams(params);
                String getResult = HttpUtil.get(shipEepReportRecInfoUrl + "?" + para);
                log.debug("入参：{}，获取进出港数据：{}", para, getResult);
                JSONObject jsonObject = JSON.parseObject(getResult);
                if (jsonObject != null && 200 == jsonObject.getInteger("code")) {
                    JSONArray result = jsonObject.getJSONArray("result");
                    if (result != null && !result.isEmpty()) {
                        Map<String, String> stringStringMap = Convert.toMap(String.class, String.class, result.get(0));
                        String expectTime = stringStringMap.get("expect_time");
                        return ShipEepReportRecInfo.builder()
                                .berthName(stringStringMap.get("berth_name"))
                                .nextPortName(stringStringMap.get("next_port_name"))
                                .expectTime(StrUtil.isNotBlank(expectTime) && expectTime.length() >= 16 ? expectTime.replace("T", " ").substring(0, 16) : "")
                                .build();
                    }
                }
            } catch (Exception e) {
                log.error("获取船舶停靠信息异常");
            }

        }
        return null;
    }

    @Override
    public AisShipInfo getShipInfo(String shipnameCn, String mmsi, String shipId, String shipNo) {
        log.debug("当前环境：{}", profile);
        if ("prod".equals(profile) && StrUtil.isNotBlank(mmsi) && mmsi.length() == 9) {
            // 先从缓存找
            AisShipInfo baseInfo = redisCache.getCacheMapValue("ais:base", mmsi);
            if (ObjectUtil.isNotEmpty(baseInfo)) {
                return baseInfo;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("mmsi", mmsi);
            try {
                String url = shipBaseInfo + "?" + HttpUtil.toParams(params);
                String getResult = HttpUtil.get(url);
                log.debug("调用地址：{}。获取船舶数据：{}", url, getResult);
                JSONObject jsonObject = JSON.parseObject(getResult);
                if (jsonObject != null && 200 == jsonObject.getInteger("code")) {
                    JSONArray result = jsonObject.getJSONArray("data");
                    if (result != null && !result.isEmpty()) {
                        Map<String, String> stringStringMap = Convert.toMap(String.class, String.class, result.get(0));
                        AisShipInfo build = AisShipInfo.builder().shipName(stringStringMap.get("shipnameCn")).shipRegionType(stringStringMap.get("shipRegionType")).build();
                        if (StrUtil.isNotBlank(stringStringMap.get("shipnameCn"))) {
                            redisCache.setCacheMapValue("ais:base", mmsi, build);
                        }
                        return build;
                    }
                }
            } catch (Exception e) {
                log.error("获取船舶基本信息异常");
            }
        }
        return null;
    }

}