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.LambdaQueryWrapper;
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.PqTypicalSourceCreatePOMapper;
import com.njcn.harmonic.pojo.dto.PqTypicalSourceCreateDTO;
import com.njcn.harmonic.pojo.param.SendQueryParam;
import com.njcn.harmonic.pojo.param.UploadParam;
import com.njcn.harmonic.pojo.po.send.PqTypicalSourceCreatePO;
import com.njcn.harmonic.service.send.PqTypicalSourceCreatePOService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
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.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2023/12/12  15:16【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PqTypicalSourceCreatePOServiceImpl extends ServiceImpl<PqTypicalSourceCreatePOMapper, PqTypicalSourceCreatePO> implements PqTypicalSourceCreatePOService {

    private final DeptFeignClient deptFeignClient;

    @Override
    public Page<PqTypicalSourceCreatePO> queryPage(SendQueryParam.SendPageParam param) {
        Page<PqTypicalSourceCreatePO> page = new Page<> (param.getPageNum ( ), param.getPageSize ( ));

        List<String> deptIds = deptFeignClient.getDepSonSelfCodetByCode(param.getDeptIndex()).getData();
        LambdaQueryWrapper<PqTypicalSourceCreatePO> deptLevel = getDeptLevel(param);
        deptLevel.orderByDesc(PqTypicalSourceCreatePO::getProvinceName);

        Page<PqTypicalSourceCreatePO> pqTypicalSourceCreatePOPage = this.getBaseMapper().selectPage(page, deptLevel);

        return pqTypicalSourceCreatePOPage;
    }
    /**
     * 获取当前单位的层级
     */
    public LambdaQueryWrapper<PqTypicalSourceCreatePO> getDeptLevel(SendQueryParam.SendPageParam param) {
        Dept dept = deptFeignClient.getDeptByCode(param.getDeptIndex()).getData();
        List<String> list = Arrays.stream(dept.getPids().split(",")).map(String::trim).collect(Collectors.toList());
        LambdaQueryWrapper<PqTypicalSourceCreatePO> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        switch (list.size()) {
            //国、省
            case 1:
                List<Dept> l1 = deptFeignClient.getDirectSonSelf(dept.getId()).getData();
                String orgId = l1.stream().filter(o->!Objects.equals(o.getId(),dept.getId())).findFirst().orElse(null).getCode();
                lambdaQueryWrapper.eq(PqTypicalSourceCreatePO::getProvinceId,orgId)
                        .between(PqTypicalSourceCreatePO::getStatisticalDate,param.getSearchBeginTime(),param.getSearchEndTime())
                        .eq(!Objects.isNull(param.getSearchState()),PqTypicalSourceCreatePO::getIsUploadHead,param.getSearchState());
                break;
            case 2:
                lambdaQueryWrapper.eq(PqTypicalSourceCreatePO::getProvinceId,param.getDeptIndex())
                        .between(PqTypicalSourceCreatePO::getStatisticalDate,param.getSearchBeginTime(),param.getSearchEndTime())
                        .eq(!Objects.isNull(param.getSearchState()),PqTypicalSourceCreatePO::getIsUploadHead,param.getSearchState());
                break;
            //市
            case 3:
                lambdaQueryWrapper.eq(PqTypicalSourceCreatePO::getCityId, param.getDeptIndex())
                        .between(PqTypicalSourceCreatePO::getStatisticalDate,param.getSearchBeginTime(),param.getSearchEndTime())
                        .eq(!Objects.isNull(param.getSearchState()),PqTypicalSourceCreatePO::getIsUploadHead,param.getSearchState());
                break;
            //县
            case 4:
                lambdaQueryWrapper.eq(PqTypicalSourceCreatePO::getCountyId, param.getDeptIndex())
                        .between(PqTypicalSourceCreatePO::getStatisticalDate,param.getSearchBeginTime(),param.getSearchEndTime())
                        .eq(!Objects.isNull(param.getSearchState()),PqTypicalSourceCreatePO::getIsUploadHead,param.getSearchState());
                break;
            default:
                break;
        }
        return lambdaQueryWrapper;
    }

    @Override
    public String send(UploadParam uploadParam) {

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

            List<String> trIds = temp.stream().map(PqTypicalSourceCreateDTO::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(PqTypicalSourceCreatePO::getId,ids).set(PqTypicalSourceCreatePO::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  "当前时间段国网上送请求过多，请稍后再试";
        }
    }
}
