package com.artfess.yhxt.yjjy.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

import com.artfess.yhxt.push.HttpUtil;
import com.artfess.yhxt.yjjy.manager.DiseasesYjjyManager;
import com.artfess.yhxt.yjjy.manager.SiteInspectionYjjyManager;
import com.artfess.yhxt.yjjy.model.DiseasesYjjy;
import com.artfess.yhxt.yjjy.model.SiteInspectionYjjy;
import com.artfess.yhxt.yjjy.service.YjjyyManagerService;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhx
 * @create 2022/5/29
 */
@Service
public class YjjyManagerImpl implements YjjyyManagerService {
    //获取巡查记录列表url
    private String urlRoadCheckWork = "http://10.5.1.48:16001/zdpm/extapi/getRoadCheckWorkList";
    //获取巡查点记录
    private String urlRoadCheckWorkDetail = "http://10.5.1.48:16001/zdpm/extapi/getRoadCheckWorkDetail";
    //sQueryKey：t8m5py6eKdqpAi7lQBIbNQ==
    private String sQueryKey = "t8m5py6eKdqpAi7lQBIbNQ==";

    @Resource
    private DiseasesYjjyManager diseasesYjjyManager;
    @Resource
    private SiteInspectionYjjyManager siteInspectionYjjyManager;

    @Override
    public void synchronizationYjjy() {
        try {
            ArrayList<SiteInspectionYjjy> siteInspectionYjjiess = new ArrayList<SiteInspectionYjjy>();
            ArrayList<DiseasesYjjy> diseasesYjjiess = new ArrayList<DiseasesYjjy>();
            HashMap<String, Object> params = new HashMap<>();
            params.put("sQueryKey", sQueryKey);
            params.put("start", 0);
            params.put("size", 100);

            // 获取当前日期的前一天
            Calendar date = Calendar.getInstance();
            date.add(Calendar.DATE, -7);
            Date time = date.getTime();
            System.out.println(time);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
            params.put("dBeginTimeBegin", URLEncoder.encode(format, "utf-8"));

            this.synchronization(siteInspectionYjjiess, diseasesYjjiess, params, urlRoadCheckWork, urlRoadCheckWorkDetail, sQueryKey);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }


    }

    private void synchronization(ArrayList<SiteInspectionYjjy> siteInspectionYjjies, ArrayList<DiseasesYjjy> diseasesYjjies, HashMap<String, Object> params,
                                 String urlRoadCheckWork, String urlRoadCheckWorkDetail, String sQueryKey) throws Exception {
        while (true) {
            //获取巡检信息
            String jsonRoadCheckWork = HttpUtil.get(urlRoadCheckWork, params);

            ObjectMapper mapper = new ObjectMapper();
            //将数据读取成json
            JsonNode root = mapper.readTree(jsonRoadCheckWork);
            JsonNode data = root.get("data");

            JSONArray objects = JSONUtil.parseArray(data.toString());
            if (objects.size() > 0) {

                List<Map> maps = JSONUtil.toList(objects, Map.class);

                //TODO  设置属性
                for (Map map : maps) {
                    SiteInspectionYjjy siteInspectionYjjy = new SiteInspectionYjjy();

                    //id
                    Object nId = map.get("nId");

                    if (ObjectUtils.isNotEmpty(nId)) siteInspectionYjjy.setId(nId.toString());
                    //jobNumber
                    Object sNo = map.get("sNo");
                    if (ObjectUtils.isNotEmpty(sNo)) siteInspectionYjjy.setSNo(sNo.toString());
                    //天气
                    Object sWeather = map.get("sWeather");
                    if (ObjectUtils.isNotEmpty(sWeather)) siteInspectionYjjy.setSWeather(sWeather.toString());
                    //开始里程
                    Object nBeginLong = map.get("nBeginLong");
                    if (ObjectUtils.isNotEmpty(nBeginLong)) siteInspectionYjjy.setNBeginLong(nBeginLong.toString());
                    //结束里程
                    Object nEndLong = map.get("nEndLong");
                    if (ObjectUtils.isNotEmpty(nEndLong)) siteInspectionYjjy.setNEndLong(nEndLong.toString());
                    //巡查里程
                    Object nRunLong = map.get("nRunLong");
                    if (ObjectUtils.isNotEmpty(nRunLong)) siteInspectionYjjy.setNRunLong(nRunLong.toString());

                    //开始时间
                    Object dBeginTime = map.get("dBeginTime");
                    if (ObjectUtils.isNotEmpty(dBeginTime)) {
                        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        LocalDateTime parse = LocalDateTime.parse(dBeginTime.toString(), dateTimeFormatter);
                        siteInspectionYjjy.setDBeginTime(parse);
                    }
                    //结束时间
                    Object dEndTime = map.get("dEndTime");
                    if (ObjectUtils.isNotEmpty(dEndTime)) {
                        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        LocalDateTime parse = LocalDateTime.parse(dEndTime.toString(), dateTimeFormatter);
                        siteInspectionYjjy.setDEndTime(parse);
                    }

                    //巡检用时
                    Object nTime = map.get("nTime");
                    if (ObjectUtils.isNotEmpty(nTime)) siteInspectionYjjy.setNTime(nTime.toString());

                    //巡检状态
                    Object sStatus = map.get("sStatus");
                    if (ObjectUtils.isNotEmpty(sStatus)) siteInspectionYjjy.setSStatus(sStatus.toString());


                    //根据巡检id查询病害
                    HashMap<String, Object> paramDiseasesYjjys = new HashMap<>();
                    paramDiseasesYjjys.put("sQueryKey", sQueryKey);
                    paramDiseasesYjjys.put("nId", nId);
                    String jsonDiseasesYjjys = HttpUtil.get(urlRoadCheckWorkDetail, paramDiseasesYjjys);

                    JsonNode jsonNode = mapper.readTree(jsonDiseasesYjjys);

                    JsonNode dataDiseases = jsonNode.get("data");
                    //todo 设置巡检属性
                    JsonNode sType = dataDiseases.get("sType");


                    if (sType != null) siteInspectionYjjy.setSType(StringUtils.strip(sType.toString(),"\""));
                    JsonNode sRoad = dataDiseases.get("sRoad");
                    if (sRoad != null) siteInspectionYjjy.setSRoad(StringUtils.strip(sRoad.toString(),"\""));
                    //巡检类型
                    JsonNode sClass = dataDiseases.get("sClass");
                    if (sClass != null) siteInspectionYjjy.setSClass(StringUtils.strip(sClass.toString(),"\""));
                    //sKind
                    JsonNode sKind = dataDiseases.get("sKind");
                    if (sKind != null) siteInspectionYjjy.setSKind(StringUtils.strip(sKind.toString(),"\""));
                    //巡检内容
                    JsonNode sTaskValue = dataDiseases.get("sTaskValue");
                    if (sTaskValue != null) siteInspectionYjjy.setSTaskValue(StringUtils.strip(sTaskValue.toString(),"\""));
                    //巡检人
                    JsonNode sDoPersonName = dataDiseases.get("sDoPersonName");
                    if (sDoPersonName != null) siteInspectionYjjy.setSDoPersonName(StringUtils.strip(sDoPersonName.toString(),"\""));

                    JsonNode recordList = dataDiseases.get("recordList");

                    if (recordList!=null) {
                        JSONArray objectsDiseasesYjjys = JSONUtil.parseArray(recordList.toString());
                        if (objectsDiseasesYjjys.size() > 0) {
                            List<Map> mapsDiseasesYjjys = JSONUtil.toList(objectsDiseasesYjjys, Map.class);
                            for (Map mapsDiseasesYjjy : mapsDiseasesYjjys) {
                                DiseasesYjjy diseasesYjjy = new DiseasesYjjy();
                                if (ObjectUtils.isNotEmpty(nId)) diseasesYjjy.setNId(nId.toString());
                                Object nIdDiseases = mapsDiseasesYjjy.get("nId");

                                if (ObjectUtils.isNotEmpty(nIdDiseases)) diseasesYjjy.setId(nIdDiseases.toString());

                                Object sRoadDiseases = mapsDiseasesYjjy.get("sRoad");
                                if (ObjectUtils.isNotEmpty(sRoadDiseases)) diseasesYjjy.setSRoad(sRoadDiseases.toString());
                                Object sValue = mapsDiseasesYjjy.get("sValue");
                                if (ObjectUtils.isNotEmpty(sValue)) diseasesYjjy.setSValue(sValue.toString());
                                Object sStatusDiseases = mapsDiseasesYjjy.get("sStatus");
                                if (ObjectUtils.isNotEmpty(sStatusDiseases))
                                    diseasesYjjy.setSStatus(sStatusDiseases.toString());
                                Object sCheckMessage = mapsDiseasesYjjy.get("sCheckMessage");
                                if (ObjectUtils.isNotEmpty(sCheckMessage))
                                    diseasesYjjy.setSCheckMessage(sCheckMessage.toString());
                                Object sDoResult = mapsDiseasesYjjy.get("sDoResult");
                                if (ObjectUtils.isNotEmpty(sDoResult)) diseasesYjjy.setSDoreSult(sDoResult.toString());
                                Object sDir = mapsDiseasesYjjy.get("sDir");
                                if (ObjectUtils.isNotEmpty(sDir)) diseasesYjjy.setSDir(sDir.toString());
                                Object sTypeDiseases = mapsDiseasesYjjy.get("sType");
                                if (ObjectUtils.isNotEmpty(sTypeDiseases))
                                    diseasesYjjy.setSType(sTypeDiseases.toString());
                                Object sKindDiseases = mapsDiseasesYjjy.get("sKind");
                                if (ObjectUtils.isNotEmpty(sKindDiseases))
                                    diseasesYjjy.setSKind(sKindDiseases.toString());
                                Object sName = mapsDiseasesYjjy.get("sName");
                                if (ObjectUtils.isNotEmpty(sName)) diseasesYjjy.setSName(sName.toString());
                                Object sDoPerson = mapsDiseasesYjjy.get("sDoPerson");
                                if (ObjectUtils.isNotEmpty(sDoPerson)) diseasesYjjy.setSDoPerson(sDoPerson.toString());
                                Object sDoValue = mapsDiseasesYjjy.get("sDoValue");
                                if (ObjectUtils.isNotEmpty(sDoValue)) diseasesYjjy.setSDoValue(sDoValue.toString());


                                Object sLongitude = mapsDiseasesYjjy.get("sLongitude");
                                if (ObjectUtils.isNotEmpty(sLongitude))
                                    diseasesYjjy.setSLongitude(sLongitude.toString());
                                Object sLatitude = mapsDiseasesYjjy.get("sLatitude");
                                if (ObjectUtils.isNotEmpty(sLatitude)) diseasesYjjy.setSLatitude(sLatitude.toString());

                                Object dCreateDate = mapsDiseasesYjjy.get("dCreateDate");
                                if (ObjectUtils.isNotEmpty(dCreateDate)) {
                                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    LocalDateTime parse = LocalDateTime.parse(dCreateDate.toString(), dateTimeFormatter);
                                    diseasesYjjy.setDCreateDate(parse);
                                }



                                //todo 设置属性
                                if (StringUtils.isNotEmpty(diseasesYjjy.getId()) && StringUtils.isNotEmpty(diseasesYjjy.getSRoad())) {
                                    diseasesYjjies.add(diseasesYjjy);
                                }
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(siteInspectionYjjy.getId())&& StringUtils.isNotEmpty(siteInspectionYjjy.getSRoad())) {
                        siteInspectionYjjies.add(siteInspectionYjjy);
                    }
                }

                ArrayList<DiseasesYjjy> collectDiseases = diseasesYjjies.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        DiseasesYjjy::getId))), ArrayList::new));
                diseasesYjjyManager.saveOrUpdateBatch(collectDiseases);

                ArrayList<SiteInspectionYjjy> collectSiteInspection = siteInspectionYjjies.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        SiteInspectionYjjy::getId))), ArrayList::new));
                siteInspectionYjjyManager.saveOrUpdateBatch(collectSiteInspection);

            }
            System.out.println("start============"+params.get("start").toString());
            if (objects.size() == 0) {
                System.out.println("start======break======"+params.get("start").toString());
                break;
            }

/*            if (Integer.parseInt(params.get("start").toString())==2) {
                System.out.println("start======break======"+params.get("start").toString());
                break;
            }*/
            params.put("start", Integer.parseInt(params.get("start").toString()) + 1);
        }

    }

    public static void main(String[] args) throws JsonProcessingException {

 /*       String json = "[{\"nId\":16365,\"sNo\":\"XC0120211200000070\",\"sCode\":\"c1d0a2d5-ee5e-4495-bdbf-03277d0ce378\",\"sUnitFlag\":\"1000000007\",\"dUpDate\":\"2021-12-21 16:56:25\",\"sRoadCheckWorkPlanNo\":\"aa668171-4003-4bc1-ac2b-9444c5dc6738\",\"sPlateNo\":\"渝AJ05B8\",\"sWeather\":\"阴\",\"nBeginLong\":75301,\"nEndLong\":75489,\"nRunLong\":188000,\"dBeginTime\":\"2021-12-21 08:22:40\",\"dEndTime\":\"2021-12-21 16:56:25\",\"nTime\":481,\"nCheckPoint\":35,\"nErrorPoint\":3,\"nErrorDoPoint\":3,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":23679,\"sNo\":\"XC0120211200000084\",\"sCode\":\"855273dd-f3a5-4459-a5cc-3017eceac85a\",\"sUnitFlag\":\"1000000003\",\"dUpDate\":\"2021-12-21 21:05:45\",\"sRoadCheckWorkPlanNo\":\"15bf7a46-d099-499c-a0bc-7f126c8ee8d9\",\"sPlateNo\":\"渝A7ER29\",\"sWeather\":\"阴\",\"nBeginLong\":225220,\"nEndLong\":225390,\"nRunLong\":170000,\"dBeginTime\":\"2021-12-21 19:48:10\",\"dEndTime\":\"2021-12-21 21:05:45\",\"nTime\":8,\"nCheckPoint\":5,\"nErrorPoint\":0,\"nErrorDoPoint\":0,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":32613,\"sNo\":\"XC0120211200000088\",\"sCode\":\"0925da29-ccba-4490-bbf5-68a8ec930146\",\"sUnitFlag\":\"1000000015\",\"dUpDate\":\"2021-12-22 08:51:58\",\"sRoadCheckWorkPlanNo\":\"1674cc35-baf6-4106-be50-90cdc5a924fc\",\"sPlateNo\":\"渝A18HO8\",\"sWeather\":\"雾\",\"nBeginLong\":53031,\"nEndLong\":0,\"nRunLong\":0,\"dBeginTime\":\"2021-12-22 08:45:17\",\"dEndTime\":\"\",\"nTime\":0,\"nCheckPoint\":0,\"nErrorPoint\":0,\"nErrorDoPoint\":0,\"nErrorUpPoint\":0,\"sStatus\":\"取消\",\"sCancelMemo\":\"其他原因备注填写\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":33137,\"sNo\":\"XC0120211200000093\",\"sCode\":\"95daeb5c-d622-4f5a-a8ff-b982eacc55e1\",\"sUnitFlag\":\"1000000005\",\"dUpDate\":\"2021-12-22 19:33:00\",\"sRoadCheckWorkPlanNo\":\"0100c843-c252-4e8f-b406-922e41f1ddc4\",\"sPlateNo\":\"渝AYX286\",\"sWeather\":\"雾\",\"nBeginLong\":29324,\"nEndLong\":29467,\"nRunLong\":143000,\"dBeginTime\":\"2021-12-22 09:32:11\",\"dEndTime\":\"2021-12-22 19:32:58\",\"nTime\":149,\"nCheckPoint\":16,\"nErrorPoint\":6,\"nErrorDoPoint\":6,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":1438,\"sNo\":\"XC0120211200000023\",\"sCode\":\"c4c76a20-66bb-4f44-8ca6-bb60cac935ef\",\"sUnitFlag\":\"1000000007\",\"dUpDate\":\"2021-12-17 18:41:44\",\"sRoadCheckWorkPlanNo\":\"b2ae137f-5b37-4425-86d2-2b28801f8428\",\"sPlateNo\":\"渝AJ05B8\",\"sWeather\":\"多云\",\"nBeginLong\":74328,\"nEndLong\":74494,\"nRunLong\":166000,\"dBeginTime\":\"2021-12-17 09:30:19\",\"dEndTime\":\"2021-12-17 18:41:44\",\"nTime\":351,\"nCheckPoint\":14,\"nErrorPoint\":3,\"nErrorDoPoint\":3,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":2121,\"sNo\":\"XC0120211200000049\",\"sCode\":\"84fcfa1c-27df-4c4b-a565-4f62e3e768f1\",\"sUnitFlag\":\"1000000003\",\"dUpDate\":\"2021-12-19 17:35:06\",\"sRoadCheckWorkPlanNo\":\"6d07bdd4-0372-48e9-86fe-c8433b1c5d2d\",\"sPlateNo\":\"渝A7ER29\",\"sWeather\":\"晴\",\"nBeginLong\":224310,\"nEndLong\":224460,\"nRunLong\":150000,\"dBeginTime\":\"2021-12-19 14:24:37\",\"dEndTime\":\"2021-12-19 17:35:08\",\"nTime\":46,\"nCheckPoint\":21,\"nErrorPoint\":3,\"nErrorDoPoint\":3,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":16700,\"sNo\":\"XC0120211200000071\",\"sCode\":\"8cc7bb3f-9418-4bd1-b1db-e090e9d1737e\",\"sUnitFlag\":\"1000000009\",\"dUpDate\":\"2021-12-21 16:32:01\",\"sRoadCheckWorkPlanNo\":\"2e94e9a4-bdf4-4b14-bf11-631bdb287258\",\"sPlateNo\":\"渝HY0915\",\"sWeather\":\"晴\",\"nBeginLong\":304299,\"nEndLong\":304414,\"nRunLong\":115000,\"dBeginTime\":\"2021-12-21 08:58:30\",\"dEndTime\":\"2021-12-21 16:32:01\",\"nTime\":195,\"nCheckPoint\":10,\"nErrorPoint\":0,\"nErrorDoPoint\":0,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":19851,\"sNo\":\"XC0120211200000079\",\"sCode\":\"08f29483-990e-40b4-8151-edbb86493825\",\"sUnitFlag\":\"1000000001\",\"dUpDate\":\"2021-12-21 17:33:37\",\"sRoadCheckWorkPlanNo\":\"219aef7e-ecc0-42fc-986c-5f1a0a9903b3\",\"sPlateNo\":\"渝B178Z5\",\"sWeather\":\"晴\",\"nBeginLong\":222222,\"nEndLong\":222292,\"nRunLong\":70000,\"dBeginTime\":\"2021-12-21 14:12:18\",\"dEndTime\":\"2021-12-21 17:33:37\",\"nTime\":195,\"nCheckPoint\":103,\"nErrorPoint\":0,\"nErrorDoPoint\":0,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":1268,\"sNo\":\"XC0120211200000002\",\"sCode\":\"f2f6f821-710a-49e9-b06a-8e4d6b5460ca\",\"sUnitFlag\":\"1000\",\"dUpDate\":\"2021-12-15 17:47:05\",\"sRoadCheckWorkPlanNo\":\"110cd731-3d76-41eb-a3e5-da222e9d79b9\",\"sPlateNo\":\"渝AJM885\",\"sWeather\":\"多云\",\"nBeginLong\":32892,\"nEndLong\":32938,\"nRunLong\":46000,\"dBeginTime\":\"2021-12-15 15:18:49\",\"dEndTime\":\"2021-12-15 17:47:06\",\"nTime\":98,\"nCheckPoint\":53,\"nErrorPoint\":0,\"nErrorDoPoint\":0,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"},{\"nId\":1354,\"sNo\":\"XC0120211200000013\",\"sCode\":\"2dbf38b4-262b-433c-ae86-338bba5d631e\",\"sUnitFlag\":\"1000000005\",\"dUpDate\":\"2021-12-16 19:34:24\",\"sRoadCheckWorkPlanNo\":\"fc8e5840-149c-4ad4-a1a0-3bda6f32f4b6\",\"sPlateNo\":\"渝AYX286\",\"sWeather\":\"晴\",\"nBeginLong\":28133,\"nEndLong\":28240,\"nRunLong\":107000,\"dBeginTime\":\"2021-12-16 10:31:10\",\"dEndTime\":\"2021-12-16 19:34:23\",\"nTime\":137,\"nCheckPoint\":16,\"nErrorPoint\":6,\"nErrorDoPoint\":6,\"nErrorUpPoint\":0,\"sStatus\":\"完成\",\"sCancelMemo\":\"\",\"sStopMemo\":\"\",\"sPlateCameraNo\":\"\",\"sPlateCameraName\":\"\"}]";
        JSONArray objects1 = JSONUtil.parseArray(json);
        System.out.println(objects1);*/
    }
}
