package com.ningdatech.kqapi.scheduler.task;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import cn.hutool.json.JSONUtil;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.http.HttpClientService;
import com.ningdatech.http.HttpResponseContent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ningdatech.kqapi.common.util.NdDateUtils;
import com.ningdatech.kqapi.irs.manage.IrsManage;
import com.ningdatech.kqapi.zzsfw.model.entity.DscSxAdsShareItemQltQlsxCommonIDVKq;
import com.ningdatech.kqapi.zzsfw.service.IDscSxAdsShareItemQltQlsxCommonIDVKqService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.StopWatch;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * 事项同步定时任务
 * @since 2024/08/21 09:53
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ItemSynTestTask {

    @Value("${hostname}")
    public String HOST;

    private final IDscSxAdsShareItemQltQlsxCommonIDVKqService kqService;
    private final IrsManage irsManage;
    private final HttpClientService httpClient;


    String transmitListUrl = "https://qyxspt.kq.gov.cn:33060/kq/api/v1/irs/item-basic-info-list";
    String transmitDetailUrl = "https://qyxspt.kq.gov.cn:33060/kq/api/v1/irs/item-basic-info-detail";

    public void synData() {
        log.info("事项数据 ===================== 同步开始");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 每天凌晨5点同步前一天新更新的数据
        // 默认一页返回
        int pageNum = 1;
        // irs接口最大返回数据量1000条
        int pageSize = 1000;

        List<DscSxAdsShareItemQltQlsxCommonIDVKq> records = Lists.newArrayList();
        // 根据事项表中最后更新日期 循环更新至前一天的事项数据
        String start = kqService.getNewestUpdateDate();
        String end = NdDateUtils.format(LocalDateTime.now().minusDays(1), NdDateUtils.DEFAULT_DATE_FORMAT);
        LocalDate startDate = LocalDate.parse(start);
        LocalDate endDate = LocalDate.parse(end);

        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            // 循环拉取较前一天已同步数据 新更新的数据
            boolean flag = true;
            while (flag) {
                //Object listObject = irsManage.itemBasicInfoList(startDate, endDate, pageSize, pageNum);

                String listUrl = transmitListUrl + "?startDate=" + startDate + "&endDate=" + endDate +
                        "&pageSize=" + pageSize + "&pageNum=" + pageNum;
                log.info("listUrl :{}", listUrl);
                HttpResponseContent listContent = httpClient.doGet(listUrl, null, null);
                log.info("列表接口返回值：{}", JSONUtil.toJsonStr(listContent));
                String listObject = listContent.getStringBody();
                if (listObject == null || StringUtils.isBlank(listObject)) {
                    throw new BizException("列表接口转发调用失败!");
                }
                JSONObject listJsonObject = null;
                try {
                    listJsonObject = JSONObject.parseObject(listObject);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                Object object = listJsonObject.get("data");
                // 如果数据正常返回
                if (object instanceof JSONArray) {
                    //JSONArray listJsonArray = (JSONArray)listObject;
                    JSONArray listJsonArray = listJsonObject.getJSONArray("data");
                    log.info("事项列表数量为：{}", listJsonArray.size());
                    getSaveRecords(listJsonArray, records);
                    // 如果listJsonArray数据量等于1000 需要继续拉取数据
                    if (listJsonArray.size() == pageSize) {
                        pageNum++;
                    } else {
                        flag = false;
                    }
                } else {
                    log.error("事项列表数据异常：{}", listObject);
                    return;
                }
            }
        }
        log.info("{} - {} 数据列表数量为：{}", startDate, endDate, records.size());
        kqService.saveBatch(records);
        log.info("事项同步成功，更新时间：{}", endDate);
        stopWatch.stop();
        log.info("事项数据 ===================== 同步总共耗时 :{} s", stopWatch.getTotalTimeSeconds());
    }

    private void getSaveRecords(JSONArray listJsonArray, List<DscSxAdsShareItemQltQlsxCommonIDVKq> records) {
        if (CollUtil.isNotEmpty(listJsonArray)) {
            List<DscSxAdsShareItemQltQlsxCommonIDVKq> dataList = Lists.newArrayList();
            for (Object item : listJsonArray) {
                JSONObject itemJsonObject = (JSONObject) item;
                DscSxAdsShareItemQltQlsxCommonIDVKq itemData = null;
                // 先将列表中返回的非敏感信息进行赋值
                itemData = JSON.parseObject(itemJsonObject.toJSONString(), DscSxAdsShareItemQltQlsxCommonIDVKq.class);
                String rowGuid = itemJsonObject.getString("rowguid" );
                if (StringUtils.isNotBlank(rowGuid)) {
                    //Object detailObject = irsManage.itemBasicInfoDetail(rowGuid);
                    String detailUrl = transmitDetailUrl + "?rowGuid=" + rowGuid;
                    log.info("detailUrl :{}", detailUrl);

                    HttpResponseContent detailContent = httpClient.doGet(detailUrl, null, null);
                    log.info("详情接口返回值：{}", JSONUtil.toJsonStr(detailContent));
                    String detailObject = detailContent.getStringBody();
                    if (detailObject == null || StringUtils.isBlank(detailObject)) {
                        throw new BizException("列表接口转发调用失败!" );
                    }
                    JSONObject detailJsonObject = null;
                    try {
                        detailJsonObject = JSONObject.parseObject(detailObject);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    Object object = detailJsonObject.get("data");

                    if (object instanceof JSONArray){
                        //JSONArray detailJsonArray = (JSONArray) detailObject;
                        JSONArray detailJsonArray = detailJsonObject.getJSONArray("data");
                        List<DscSxAdsShareItemQltQlsxCommonIDVKq> idvKqList = detailJsonArray.toJavaList(DscSxAdsShareItemQltQlsxCommonIDVKq.class);
                        if (CollUtil.isNotEmpty(idvKqList)) {
                            // 如果列表不为空，则取最新的一条数据
                            idvKqList.sort((o1, o2) -> o2.getUpdateDate().compareTo(o1.getUpdateDate()));
                            DscSxAdsShareItemQltQlsxCommonIDVKq detailItemData = idvKqList.get(0);
                            // 将敏感数据进行赋值
                            CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true);
                            BeanUtil.copyProperties(detailItemData, itemData,copyOptions);
                        }
                    }
                }
                if (Objects.nonNull(itemData)) {
                    dataList.add(itemData);
                }
            }
            // 保存数据
            if (CollUtil.isNotEmpty(dataList)) {
                records.addAll(dataList);
            }
        }
    }
}
