package com.shcd.service.dredging.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shcd.entity.dredging.*;
import com.shcd.mapper.dredging.BasiceMapper;
import com.shcd.service.dredging.*;
import com.shcd.utils.geo.CoordinateUtils;
import io.micrometer.core.ipc.http.OkHttpSender;
import kong.unirest.MultipartMode;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sun.net.www.http.HttpClient;

import javax.net.ssl.HostnameVerifier;
import java.sql.Wrapper;
import java.util.*;

@Service
@Slf4j
public class DredgingServiceImpl implements DredgingService {
    //
    @Value("${dredgingTokenUrl}")
    private String dredgingTokenUrl;
//    @Value("${dredgingClientId}")
//    private String dredgingClientId;
//    @Value("${dredgingClientSecret}")
//    private String dredgingClientSecret;
    @Value("${dredgingProjectUrl}")
    private String dredgingProjectUrl;
    @Value("${dredgingElectricFenUrl}")
    private String dredgingElectricFenUrl;
    @Value("${dredgingWorkOrderUrl}")
    private String dredgingWorkOrderUrl;
    @Value("${dredgingWorkTraceUrl}")
    private String dredgingWorkTraceUrl;
    @Value("${dredgingWorkCameraUrl}")
    private String dredgingWorkCameraUrl;

    @Autowired
    private DredgingSpoilAreaService dredgingSpoilAreaService;
    @Autowired
    private DredgingProjectShipService dredgingProjectShipService;
    @Autowired
    private ElectronicWarningService electronicWarningService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private DredgingProjectOverviewService dredgingProjectOverviewService;
    @Autowired
    private DredgingElectronicFenceService dredgingElectronicFenceService;

    @Autowired
    private DDredgingShipService dDredgingShipService;
    @Override
    @Transactional
    public String importData(DredgingImportRule dredgingImportRule) {
        //首先获取token
        try {
            HttpResponse execute = getToken();
            if (Boolean.parseBoolean(execute.body())) {
                HashMap<String, String> projectId = new HashMap<>();
                projectId.put("ProjectId", dredgingImportRule.getProjectOverviewId());
                String projectIdJSON = JSONObject.toJSONString(projectId);
                HttpResponse dredgingProject = HttpUtil.createPost(dredgingProjectUrl).body(projectIdJSON).setFollowRedirects(true).timeout(30000).execute();
                if (StringUtils.isNotBlank(dredgingProject.body())) {
                    HashMap projectInfos = JSONObject.parseObject(dredgingProject.body(), HashMap.class);
                    if (CollectionUtils.isEmpty(projectInfos)) {
                        return "无数据,不进行删除操作!";
                    }
                    SnowflakeGenerator snowflakeGenerator = new SnowflakeGenerator();
                    //主表内容解析存储
                    DredgingProjectOverview projectOver = new DredgingProjectOverview();
                    projectOver.setId(dredgingImportRule.getProjectOverviewId());
                    projectOver.setUpdateTime(new Date());
                    projectOver.setProjectName(projectInfos.get("ProjectName").toString());
                    projectOver.setQuantities(projectInfos.get("Quantities").toString());
                    projectOver.setYear(dredgingImportRule.getYear());
                    projectOver.setProjectStartTime(dredgingImportRule.getStartTime());
                    projectOver.setProjectEndTime(dredgingImportRule.getEndTime());
                    dredgingProjectOverviewService.saveOrUpdate(projectOver);
                    //抛泥区信息存储
                    //先删除
                    dredgingSpoilAreaService.removeById(dredgingImportRule.getProjectOverviewId());
                    List<DredgingSpoilArea> spoilAreas = JSONObject.parseArray(projectInfos.get("SpoilAreas").toString(), DredgingSpoilArea.class);
                    spoilAreas.forEach(i -> i.setOverviewId(dredgingImportRule.getProjectOverviewId()));
                    dredgingSpoilAreaService.saveBatch(spoilAreas);
                    //船舶信息存储
                    List<DredgingProjectShips> dredgingProjectShips = JSONObject.parseArray(projectInfos.get("Ships").toString(), DredgingProjectShips.class);
                    dredgingProjectShips.forEach(i -> i.setOverviewId(dredgingImportRule.getProjectOverviewId()));
                    //先删除信息
                    dredgingProjectShipService.removeById(dredgingImportRule.getProjectOverviewId());
                    //船舶数据防止重复
                    dredgingProjectShipService.saveBatch(dredgingProjectShips);
                    //电子围栏信息存储
                    HttpResponse ele = HttpUtil.createPost(dredgingElectricFenUrl).body(projectIdJSON).timeout(30000).setFollowRedirects(true).execute();
                    if (StringUtils.isNotBlank(ele.body())) {
                        HashMap fence = JSONObject.parseObject(ele.body(), HashMap.class);
                        //存储
                        DredgingElectronicFence dredgingElectronicFence = new DredgingElectronicFence();
                        dredgingElectronicFence.setProjectOverviewId(dredgingImportRule.getProjectOverviewId());
                        dredgingElectronicFence.setName(fence.get("Name").toString());
                        dredgingElectronicFence.setShape(fence.get("Shape").toString());
                        dredgingElectronicFence.setId(fence.get("Id").toString());
                        dredgingElectronicFenceService.removeById(dredgingElectronicFence.getProjectOverviewId());
                        dredgingElectronicFenceService.save(dredgingElectronicFence);
                        List<ElectronicWarning> warnings = JSONObject.parseArray(fence.get("Warnings").toString(), ElectronicWarning.class);
                        warnings.forEach(i -> {
                            i.setFenceId(dredgingElectronicFence.getId());
                            i.setProjectOverviewId(dredgingImportRule.getProjectOverviewId());
                            if (StringUtils.isNotBlank(i.getLon()) && StringUtils.isNotBlank(i.getLat())) {
                                try {
                                    double[] doubles = CoordinateUtils.gps84_To_SHXY(Double.parseDouble(i.getLon()), Double.parseDouble(i.getLat()));
                                    i.setMapx(doubles[0]);
                                    i.setMapy(doubles[1]);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("坐标转换异常" + e.getMessage());
                                }
                            }
                        });
                        electronicWarningService.removeById(dredgingImportRule.getProjectOverviewId());
                        electronicWarningService.saveBatch(warnings);
                    } else {
                        log.info("电子围栏信息为空");
                    }
                    //工单信息存储
                    //log.error(dredgingWorkOrderUrl);
                    HttpResponse workOrder = HttpUtil.createPost(dredgingWorkOrderUrl).body(projectIdJSON).timeout(30000).setFollowRedirects(true).execute();
                    if (StringUtils.isNotBlank(workOrder.body())) {
                        List<DredgingWorkOrder> dredgingWorkOrders = JSONObject.parseArray(workOrder.body(), DredgingWorkOrder.class);
                        dredgingWorkOrders.forEach(i -> i.setProjectOverviewId(dredgingImportRule.getProjectOverviewId()));
                        workOrderService.removeById(dredgingImportRule.getProjectOverviewId());
                        workOrderService.saveBatch(dredgingWorkOrders);
                        HashMap<String, String> map = new HashMap<>();
                        for (DredgingWorkOrder dredgingWorkOrder : dredgingWorkOrders) {
                            map.put(dredgingWorkOrder.getDredgeCode(),dredgingWorkOrder.getDredgeName());
                            map.put(dredgingWorkOrder.getTransportCode(),dredgingWorkOrder.getTransportName());
                        }
                        ArrayList<DDredgingShip> dDredgingShips = new ArrayList<>();
                        for (Map.Entry<String, String> entry : map.entrySet()) {
                            DDredgingShip dDredgingShip = new DDredgingShip();
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException e) {
                                log.error("线程休眠问题{}",e.getMessage());
                            }
                            dDredgingShip.setId(snowflakeGenerator.next().toString());
                            dDredgingShip.setShipCode(entry.getKey());
                            dDredgingShip.setShipName(entry.getValue());
                            dDredgingShip.setIsDelete(0);
                            dDredgingShips.add(dDredgingShip);
                        }
                        if (!CollectionUtils.isEmpty(dDredgingShips)){
                            dDredgingShipService.saveOrUpdateBatch(dDredgingShips);
                        }
                        //工单轨迹
                        for (DredgingWorkOrder dredgingWorkOrder : dredgingWorkOrders) {
                            HashMap<String, String> workOrderParams = new HashMap<>();
                            workOrderParams.put("TransportCode",dredgingWorkOrder.getTransportCode());
                            workOrderParams.put("WorkOrderCode",dredgingWorkOrder.getWorkCode());
                            String workOrderListJson = JSONObject.toJSONString(workOrderParams);
                            HttpResponse workTrace = HttpUtil.createPost(dredgingWorkTraceUrl).body(workOrderListJson)
                                    .setFollowRedirects(true).timeout(30000).execute();
                            if (StringUtils.isBlank(workTrace.body())) {
                                log.info("工单轨迹信息为空");
                            } else {
                                //存储
                                HashMap all = JSONObject.parseObject(workTrace.body(), HashMap.class);
                                List<ChannelWork> channelWorks = JSONObject.parseArray(all.get("WorkOrderShipHistorys").toString(), ChannelWork.class);
                                channelService.removeById(dredgingWorkOrder.getWorkCode());
                                channelWorks.forEach(i -> {
                                    i.setOrderId(dredgingWorkOrder.getWorkCode());
                                    i.setTransportCode(dredgingWorkOrder.getTransportCode());
                                    i.setId(snowflakeGenerator.next().toString());
                                    if (StringUtils.isNotBlank(i.getLon()) && StringUtils.isNotBlank(i.getLat())) {
                                        try {
                                            double[] doubles = CoordinateUtils.gps84_To_SHXY(Double.parseDouble(i.getLon()), Double.parseDouble(i.getLat()));
                                            i.setMapx(doubles[0]);
                                            i.setMapy(doubles[1]);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            log.info("工单轨迹信息坐标转换失败" + e.getMessage());
                                        }
                                    }
                                });
                                channelService.saveBatch(channelWorks);
                            }
                        }
                    }

                    //更新船舶绑定的videId
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("projectId",dredgingImportRule.getProjectOverviewId());
                        HttpResponse response = HttpUtil.createPost(dredgingWorkCameraUrl).body(jsonObject.toString()).setConnectionTimeout(30000).execute();
                        List<HashMap> hashMaps = JSONArray.parseArray(response.body(), HashMap.class);
                        List<DredgingProjectShips> projectShips = dredgingProjectShipService.list(Wrappers.<DredgingProjectShips>lambdaQuery().eq(DredgingProjectShips::getOverviewId, dredgingImportRule.getProjectOverviewId()));
                        for (DredgingProjectShips projectShip : projectShips) {
                            for (HashMap hashMap : hashMaps) {
                                if (hashMap.get("ShipCode").equals(projectShip.getCode())){
                                    projectShip.setVideoId(hashMap.get("Code").toString());
                                    break;
                                }
                            }
                        }
                        dredgingProjectShipService.updateBatchById(projectShips);
                    } catch (HttpException e) {
                        log.error("获取船舶id异常{}",e.getMessage());
                    }
                } else {
                    //这里代表主表的信息不存在，没必要继续进行
                    return null;
                }
            }
        } catch (Exception e) {
            log.error("数据导入异常{}",e.getMessage());
            return null;
        }
        return null;
    }

    private HttpResponse getToken() {
        return HttpUtil.createPost(dredgingTokenUrl).timeout(30000).execute();
    }

    @Autowired
    private BasiceMapper basiceMapper;

    @Override
    public List<DredgingImportRule> getAllProjectId() {
        return basiceMapper.getAllProjectId();
    }
}
