package com.ruoyi.web.service.Impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.ElasticConstants;
import com.ruoyi.framework.config.ElasticSearchClient;
import com.ruoyi.system.domain.HuiHAisInfo;
import com.ruoyi.system.domain.SyncPost;
import com.ruoyi.system.domain.vo.AisShipInfo;
import com.ruoyi.system.mapper.GasCommonMapper;
import com.ruoyi.system.service.IAisInfoService;
import com.ruoyi.web.service.IGasCommonService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

/**
 * @Description: TODO
 * @Author: huangcheng
 * @Date: 2021/8/30
 * @Version V1.0
 */
@Service
@Slf4j
public class GasCommonServiceImpl implements IGasCommonService {

    @Autowired
    private GasCommonMapper gasCommonMapper;
    @Autowired
    private ElasticSearchClient client;
    @Value("${spring.profiles.active}")
    private String env;
    @Value("${black.snapImgUrl}")
    private String blackImgUrl;
    @Autowired
    private IAisInfoService aisInfoService;

    public final static Map<String, String> orgMap = new HashMap<String, String>() {{
        put("南京三桥", "南京海事局");
        put("南京四桥", "南京海事局");
        put("润扬大桥", "扬州海事局");
        put("泰州大桥", "泰州海事局");
        put("江阴大桥", "江阴海事局");
        put("苏通大桥", "常熟海事局");
    }};
    public final static Map<String, String> heiyanDeviceMap = new HashMap<String, String>() {{
        put("南京三桥", "1106");
        put("润扬大桥", "2104");
        put("江阴大桥", "6106");
        put("苏通大桥", "9108");
    }};

    @SneakyThrows
    @Override
    @Async
    public void sync(SyncPost syncPost) {
        String schema = syncPost.getSchema();
        String table = syncPost.getTable();
        if (StrUtil.isNotBlank(syncPost.getStartTime())) {
            syncPost.setStartTime(syncPost.getStartTime() + " 00:00:00");
        }
        if (StrUtil.isNotBlank(syncPost.getEndTime())) {
            syncPost.setEndTime(syncPost.getEndTime() + " 23:59:59");
        }
        if (StrUtil.equalsIgnoreCase(schema, "ais_database") && (StrUtil.equalsIgnoreCase(table, "sem_instrument"))) {
            // 嗅探站点信息
            List<Map<String, Object>> map = gasCommonMapper.querySemInstrument(table);
            for (Map<String, Object> stringObjectMap : map) {
                saveOrUpdate(ElasticConstants.AIS_SEM_INSTRUMENT, Convert.toStr(stringObjectMap.get("id")), stringObjectMap);
            }
        } else if (StrUtil.equalsIgnoreCase(schema, "ais_database") && StrUtil.equalsIgnoreCase(table, "illegal_ship")) {
            // 嗅探违规船舶信息
            List<Map<String, Object>> map = gasCommonMapper.queryIllegalShip(syncPost);
            for (Map<String, Object> stringObjectMap : map) {
                stringObjectMap.put("mmsi", stringObjectMap.get("shipMmsi"));
                stringObjectMap.put("createTime", stringObjectMap.get("peakTime"));
                if (NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(stringObjectMap.get("sPercent")), Convert.toBigDecimal("0.1"))) {
                    stringObjectMap.put("illegalStatus", 2);
                } else {
                    stringObjectMap.put("illegalStatus", 1);
                }
                stringObjectMap.put("shipRegionType", 0);
                stringObjectMap.put("illegalType", "xiutan");
                stringObjectMap.put("uploadFlag", 0);
                Map<String, Object> sem = client.getDocById(ElasticConstants.AIS_SEM_INSTRUMENT, Convert.toStr(stringObjectMap.get("semId")), "name,category");
                if (sem != null && ObjectUtil.equal(sem.get("code"), 200)) {
                    Map<String, String> data = Convert.toMap(String.class, String.class, sem.get("data"));
                    stringObjectMap.put("semName", data.get("name"));
                    stringObjectMap.put("monitorPointName", data.get("category"));
                }
                stringObjectMap.put("deviceId", stringObjectMap.get("semId"));
                stringObjectMap.put("orgName", orgMap.get(Convert.toStr(stringObjectMap.get("monitorPointName"))));
                stringObjectMap.put("so2Percent", stringObjectMap.get("sPercent"));
                saveOrUpdate(ElasticConstants.AIS_ILLEGAL_SHIP, Convert.toStr(stringObjectMap.get("id")), stringObjectMap);
            }
        } else if (StrUtil.equalsIgnoreCase(schema, "smoke_api") && StrUtil.equalsIgnoreCase(table, "ship_recognition")) {
            // 黑烟嫌疑船舶
            List<Map<String, Object>> map = gasCommonMapper.queryShipRecognition(syncPost);
            for (Map<String, Object> afterDataMap : map) {
                if (ObjectUtil.isNotEmpty(afterDataMap.get("rcgSoot")) && NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(afterDataMap.get("rcgSoot")), Convert.toBigDecimal("1"))) {
                    afterDataMap.put("illegalStatus", 3);
                } else {
                    afterDataMap.put("illegalStatus", 1);
                }
                afterDataMap.put("mmsi", afterDataMap.get("aisMmsi"));
                // 查询检测点和船舶信息
                AisShipInfo shipInfo = aisInfoService.getShipInfo("", Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (shipInfo != null) {
                    afterDataMap.put("shipName", shipInfo.getShipName());
                    afterDataMap.put("shipRegionType", shipInfo.getShipRegionType());
                }
                // 对于没有从ais系统拿到船名的情况下，直接取rcgShipName
                if (ObjectUtil.isEmpty(afterDataMap.get("shipName"))) {
                    afterDataMap.put("shipName", afterDataMap.get("rcgShipName"));
                }
                afterDataMap.put("monitorPointName", afterDataMap.get("snapPos"));
                afterDataMap.put("uploadFlag", 0);
                afterDataMap.put("illegalType", "heiyan");
                afterDataMap.put("createTime", afterDataMap.get("snapTimeFmt"));
                afterDataMap.put("orgName", orgMap.get(Convert.toStr(afterDataMap.get("snapPos"))));
                afterDataMap.put("deviceId", heiyanDeviceMap.get(Convert.toStr(afterDataMap.get("snapPos"))));
                if ("prod".equals(env)) {
                    String imgUrl = HttpUtil.get(blackImgUrl + Convert.toStr(afterDataMap.get("id")));
                    JSONObject response = JSON.parseObject(imgUrl);
                    if (200 == response.getInteger("code")) {
                        List<String> newImgList = new ArrayList<>();
                        JSONArray imgUrlList = response.getJSONObject("data").getJSONArray("imgUrlList");
                        String sootImgUrl = response.getJSONObject("data").getString("sootImgUrl");
                        if (imgUrlList != null) {
                            for (Object o : imgUrlList) {
                                // 只保存细节、全貌开头的图片
                                String s = Convert.toStr(o);
//                                if (StrUtil.containsAny(s, "全貌", "细节")) {
                                newImgList.add("http://" + s);
//                                }
                            }
                        }
                        afterDataMap.put("sootImgUrl", StrUtil.isNotBlank(sootImgUrl) ? "http://" + sootImgUrl : "");
                        afterDataMap.put("allImgUrl", newImgList);
                    }
                }
                saveOrUpdate(ElasticConstants.HEIYAN_SHIP_RECOGNITION, Convert.toStr(afterDataMap.get("id")), afterDataMap);
            }
        } else if (StrUtil.equalsIgnoreCase(schema, "ship") && StrUtil.equalsIgnoreCase(table, "common_record")) {
            // 光谱嫌疑船舶
            List<Map<String, Object>> map = gasCommonMapper.queryAlert(syncPost);
            for (Map<String, Object> stringObjectMap : map) {
                if (NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(stringObjectMap.get("so2Percent")), Convert.toBigDecimal("0.1"))) {
                    stringObjectMap.put("illegalStatus", 2);
                } else {
                    stringObjectMap.put("illegalStatus", 1);
                }
                stringObjectMap.put("illegalType", "guangpu");
                stringObjectMap.put("shipRegionType", 0);
                stringObjectMap.put("uploadFlag", 0);
                stringObjectMap.put("orgName", orgMap.get(Convert.toStr(stringObjectMap.get("monitorPointName"))));
                saveOrUpdate(ElasticConstants.SO2_ALERT, Convert.toStr(stringObjectMap.get("id")), stringObjectMap);
            }
        } else if (StrUtil.equalsIgnoreCase(schema, "ship") && StrUtil.equalsIgnoreCase(table, "monitor_point")) {
            // 光谱监测点
            List<Map<String, Object>> map = gasCommonMapper.queryMonitorPoint(syncPost);
            for (Map<String, Object> stringObjectMap : map) {
                saveOrUpdate(ElasticConstants.SO2_MONITOR_POINT, Convert.toStr(stringObjectMap.get("id")), stringObjectMap);
            }
        }
    }

    @SneakyThrows
    private void saveOrUpdate(String indexName, String id, Map<String, Object> map) {
        boolean b = client.existsById(indexName, id);
        if (b) {
            // 更新操作
            client.updateDocument(indexName, id, map);
        } else {
            // 新增操作
            client.createDocument(indexName, id, map);
        }
    }

    @SneakyThrows
    @Override
    @Async
    public void dealAis(String message) {
        HuiHAisInfo aisBaseInfo = JSONUtil.toBean(message, HuiHAisInfo.class);
        gasCommonMapper.saveHuiHAisInfo(aisBaseInfo);
    }
}
