package com.njcn.harmonic.service.send.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.harmonic.mapper.send.ConverterIndexStatisticsPOMapper;
import com.njcn.harmonic.pojo.dto.ConverterIndexStatisticsDTO;
import com.njcn.harmonic.pojo.param.SendQueryParam;
import com.njcn.harmonic.pojo.param.UploadParam;
import com.njcn.harmonic.pojo.po.send.ConverterIndexStatisticsPO;
import com.njcn.harmonic.service.send.ConverterIndexStatisticsPOService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.enums.GWSendEnum;
import com.njcn.web.pojo.param.SendParam;
import com.njcn.web.utils.GwSendUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2023/12/11  11:35【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ConverterIndexStatisticsPOServiceImpl extends ServiceImpl<ConverterIndexStatisticsPOMapper, ConverterIndexStatisticsPO> implements ConverterIndexStatisticsPOService {

    private final DeptFeignClient deptFeignClient;
    @Override
    public Page<ConverterIndexStatisticsPO> queryPage(SendQueryParam.SendPageParam param) {
        Page<ConverterIndexStatisticsPO> page = new Page<> (param.getPageNum ( ), param.getPageSize ( ));

        List<String> deptIds = deptFeignClient.getDepSonSelfCodetByCode(param.getDeptIndex()).getData();
        QueryWrapper<ConverterIndexStatisticsPO> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(ConverterIndexStatisticsPO::getProvinceId,deptIds).
                between(ConverterIndexStatisticsPO::getStatisticalDate,param.getSearchBeginTime(),param.getSearchEndTime());
        Page<ConverterIndexStatisticsPO> converterdetailstatisticsPOPage = this.getBaseMapper().selectPage(page, wrapper);

        return converterdetailstatisticsPOPage;
    }

    @Override
    public String send(UploadParam uploadParam) {
        List<ConverterIndexStatisticsPO> list;
        //指定数据上送,不管之前有没有上送,都重新上送一次
        //(预防之前送上过,修改数据后需要再次上送)
        if (CollectionUtil.isNotEmpty(uploadParam.getList())){
            list = this.lambdaQuery()
                    .eq(ConverterIndexStatisticsPO::getStatisticalDate,uploadParam.getTime())
                    .in(ConverterIndexStatisticsPO::getId,uploadParam.getList())
                    .list();
        }
        //未指定数据上送,则将所有未上送的数据,上送上去
        else {
            list = this.lambdaQuery()
                    .eq(ConverterIndexStatisticsPO::getStatisticalDate,uploadParam.getTime())
                    .eq(ConverterIndexStatisticsPO::getIsUploadHead,0)
                    .list();
        }
        List<ConverterIndexStatisticsDTO> dtoList = BeanUtil.copyToList(list, ConverterIndexStatisticsDTO.class);
        //以尺寸100分片
        List<List<ConverterIndexStatisticsDTO>> pendingIds = ListUtils.partition(dtoList, 100);
        pendingIds.forEach(temp->{
            SendParam sendParam = new SendParam();
            sendParam.setStats(temp);
            String s = JSONObject.toJSONStringWithDateFormat(sendParam, JSON.DEFFAULT_DATE_FORMAT);
            log.info(Thread.currentThread().getName() + "获取返回体 换流站指标统计明细数据接口数据：" + s + "开始----！");
            Map<String, String> send = GwSendUtil.send(sendParam, GWSendEnum.SUBSTATION_MONITOR);
            log.info(Thread.currentThread().getName() + "获取返回体换流站指标统计明细数据接口响应结果：" + send + "结束----！");

            List<String> trIds = temp.stream().map(ConverterIndexStatisticsDTO::getId).distinct().collect(Collectors.toList());
            returnInformation(1, trIds, send);
        });

        return "成功";

    }

    /**
     * 国网上送返回信息
     *
     * @param num
     * @param ids
     * @param send
     * @return
     */
    private String returnInformation(Integer num, List<String> ids, Map<String, String> send) {
        if (send.containsKey("succeed")) {
            String succeed = send.get("succeed");
            if (succeed.indexOf("\\\"") != -1) {
                succeed = succeed.replace("\\\"", "\"");
            }
            Map mapData = JSON.parseObject(succeed, Map.class);
            String status = mapData.get("status").toString();
            if ("000000".equals(status)) {
                //修改信息状态
                this.lambdaUpdate().in(ConverterIndexStatisticsPO::getId,ids).set(ConverterIndexStatisticsPO::getIsUploadHead,num).update();
                String result = mapData.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String count = mapCount.get("count").toString();
                return "操作成功:成功数据" + count + "条";
            } else {
                String errors = mapData.get("errors").toString();
                throw new BusinessException("操作失败:" + status + "_" + errors);
            }
        } else {
//            updateIsUploadHead(num, ids);
            throw new BusinessException("当前时间段国网上送请求过多，请稍后再试");
//           return  "当前时间段国网上送请求过多，请稍后再试";
        }
    }
}
