package com.njcn.process.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csb.sdk.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.process.mapper.SupvFileMapper;
import com.njcn.process.mapper.SupvPlanMapper;
import com.njcn.process.mapper.SupvProblemMapper;
import com.njcn.process.mapper.SupvReportMMapper;
import com.njcn.process.pojo.param.SendParam;
import com.njcn.process.pojo.po.SupvFile;
import com.njcn.process.pojo.po.SupvPlan;
import com.njcn.process.pojo.po.SupvProblem;
import com.njcn.process.pojo.po.SupvReportM;
import com.njcn.process.service.SupvPushGwService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.utils.RestTemplateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * pqs
 *
 * @author cdf
 * @date 2023/6/28
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SupvPushGwServiceImpl implements SupvPushGwService {

    private final SupvPlanMapper supvPlanMapper;

    private final SupvProblemMapper supvProblemMapper;

    private final SupvFileMapper supvFileMapper;

    private final SupvReportMMapper supvReportMMapper;

    private final DicDataFeignClient dicDataFeignClient;

    private final DeptFeignClient deptFeignClient;

    private final FileStorageUtil fileStorageUtil;

    private final UserFeignClient userFeignClient;

    @Override
    public String pushPlan(List<String> planIds) {
        LambdaQueryWrapper<SupvPlan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SupvPlan::getPlanId, planIds);
        List<SupvPlan> supvPlanList = supvPlanMapper.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(supvPlanList)) {
            return "为查询数据,请查询数据是否存在!";
        }
        List<PvTerminalTreeVO> deptList = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> mapCode = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getCode, Function.identity()));
        Map<String, PvTerminalTreeVO> mapList = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, Function.identity()));

        List<DictData> supvDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPV_TYPE.getCode()).getData();
        Map<String, DictData> mapType = supvDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> supvStateDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPV_STAGE.getCode()).getData();
        Map<String, DictData> mapSupvState = supvStateDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> supveffectDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EFFECT_STATUS.getCode()).getData();
        Map<String, DictData> mapSupvEffect = supveffectDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> supvObjTypeDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPV_OBJ_TYPE.getCode()).getData();
        Map<String, DictData> mapSubvObjType = supvObjTypeDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> supvVoltageDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> mapVoltage = supvVoltageDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<String> userIds = supvPlanList.stream().map(SupvPlan::getCreateBy).distinct().collect(Collectors.toList());
        List<User> userList = userFeignClient.getUserByIdList(userIds).getData();
        Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));


        for (SupvPlan supvPlan : supvPlanList) {

            PvTerminalTreeVO pvTerminalTreeVO = null;
            if (mapCode.containsKey(supvPlan.getSupvOrgId())) {
                pvTerminalTreeVO = mapCode.get(supvPlan.getSupvOrgId());
                supvPlan.setSupvOrgName(pvTerminalTreeVO.getName());
                int deptLevel = pvTerminalTreeVO.getPids().split(StrUtil.COMMA).length;
                if (deptLevel == 2) {
                    //省
                    supvPlan.setProvinceName(pvTerminalTreeVO.getName());
                    supvPlan.setProvinceId(pvTerminalTreeVO.getCode());
                } else if (deptLevel == 3) {
                    //市
                    supvPlan.setCityName(pvTerminalTreeVO.getName());
                    supvPlan.setCityId(pvTerminalTreeVO.getCode());
                    if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                        PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                        supvPlan.setProvinceName(pvTerminalTreeOne.getName());
                        supvPlan.setProvinceId(pvTerminalTreeOne.getCode());
                    }
                } else if (deptLevel == 4) {
                    //县
                    if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                        supvPlan.setCountyName(pvTerminalTreeVO.getName());
                        supvPlan.setCountyId(pvTerminalTreeVO.getCode());
                        PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                        if (Objects.nonNull(pvTerminalTreeOne)) {
                            supvPlan.setCityName(pvTerminalTreeOne.getName());
                            supvPlan.setCityId(pvTerminalTreeOne.getCode());
                            if (mapList.containsKey(pvTerminalTreeOne.getPid())) {
                                PvTerminalTreeVO pvTerminalTreeTwo = mapList.get(pvTerminalTreeOne.getPid());
                                if (Objects.nonNull(pvTerminalTreeTwo)) {
                                    supvPlan.setProvinceName(pvTerminalTreeTwo.getName());
                                    supvPlan.setProvinceId(pvTerminalTreeTwo.getCode());
                                }
                            }
                        }
                    }
                }
            }

            //处理字典
            //监督类型编码
            if (mapType.containsKey(supvPlan.getSupvType())) {
                supvPlan.setSupvType(String.format("%02d", mapType.get(supvPlan.getSupvType()).getAlgoDescribe()));
            }

            //监督类型编码
            if (mapSupvState.containsKey(supvPlan.getSupvStage())) {
                supvPlan.setSupvStage(String.format("%02d", mapSupvState.get(supvPlan.getSupvStage()).getAlgoDescribe()));
            }

            //监督阶段
            if (mapSupvEffect.containsKey(supvPlan.getEffectStatus())) {
                supvPlan.setEffectStatus(String.format("%02d", mapSupvEffect.get(supvPlan.getEffectStatus()).getAlgoDescribe()));
            }

            //监督对象类型
            if (mapSubvObjType.containsKey(supvPlan.getSupvObjType())) {
                supvPlan.setSupvObjType(String.format("%02d", mapSubvObjType.get(supvPlan.getSupvObjType()).getAlgoDescribe()));
            }

            //电站等级
            if (mapVoltage.containsKey(supvPlan.getSubstationVoltageLevel())) {
                supvPlan.setSubstationVoltageLevelName(mapVoltage.get(supvPlan.getSubstationVoltageLevel()).getName());
                supvPlan.setSubstationVoltageLevel(String.format("%02d", mapVoltage.get(supvPlan.getSubstationVoltageLevel()).getAlgoDescribe()));

            }

            if (mapVoltage.containsKey(supvPlan.getObjVoltageLevel())) {
                DictData dictData = mapVoltage.get(supvPlan.getObjVoltageLevel());
                supvPlan.setObjVoltageLevel(String.format("%02d", dictData.getAlgoDescribe()));
                supvPlan.setObjVoltageLevelName(dictData.getName());
            }

            //判断用户是否存在
            if (map.containsKey(supvPlan.getPlanUserId())) {
                supvPlan.setPlanUserName(map.get(supvPlan.getPlanUserId()).getName());
            }
            //添加计划单位名称
            if (mapCode.containsKey(supvPlan.getPlanOrgId())) {
                pvTerminalTreeVO = mapCode.get(supvPlan.getPlanOrgId());
                supvPlan.setPlanOrgName(pvTerminalTreeVO.getName());
            }

            supvPlan.setSupvObjId(IdUtil.simpleUUID());
        }
        if (supvPlanList.size() > 100) {
            throw new BusinessException("一次最多上送100条数据");
        }


        SendParam param = new SendParam();
        param.setStats(supvPlanList);
        param.setProvinceId("13B9B47F1E483324E05338297A0A0595");
        String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
        log.info(Thread.currentThread().getName() + "获取返回体 接收电能质量技术监督工作计划数据接口数据：" + s + "结束----！");
        Map<String, String> send = send(param, getUrl(1), "pqPlanCreate");
//        Map<String, String> send = new HashMap<>();
        log.info(Thread.currentThread().getName() + "获取返回体 接收电能质量技术监督工作计划数据接口响应结果：" + 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)) {
                for (SupvPlan supvPlan : supvPlanList) {
                    SupvPlan supvPlanPO = new SupvPlan();
                    supvPlanPO.setPlanId(supvPlan.getPlanId());
                    supvPlanPO.setIsUploadHead(1);
                    supvPlanMapper.updateById(supvPlanPO);
                }
                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 {
            throw new BusinessException("出现未知错误");
        }
    }

    @Override
    public String pushQuestion(List<String> problemIds,Integer type) {
        LambdaQueryWrapper<SupvProblem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SupvProblem::getProblemId, problemIds);
        List<SupvProblem> supvProblemList = supvProblemMapper.selectList(lambdaQueryWrapper);

        List<DictData> monitorTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITOR_TYPE.getCode()).getData();
        Map<String, DictData> mapMonitorType = monitorTypeList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> problemTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPV_PROBLEM_TYPE.getCode()).getData();
        Map<String, DictData> mapProblemType = problemTypeList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<DictData> reList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.RECTIFICATION_MEASURE.getCode()).getData();
        Map<String, DictData> mapRe = reList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));


        for (SupvProblem supvProblem : supvProblemList) {

            Dept dept = deptFeignClient.getDeptByCode(supvProblem.getDutyOrgId()).getData();
            supvProblem.setDutyOrgName(dept.getName());


            if (mapMonitorType.containsKey(supvProblem.getMonitorType())) {
                supvProblem.setMonitorType(String.format("%02d", mapMonitorType.get(supvProblem.getMonitorType()).getAlgoDescribe()));
            }
            if (mapProblemType.containsKey(supvProblem.getProblemType())) {
                supvProblem.setProblemType(String.format("%02d", mapProblemType.get(supvProblem.getProblemType()).getAlgoDescribe()));
            }
            if (mapRe.containsKey(supvProblem.getRectificationMeasure())) {
                supvProblem.setRectificationMeasure(String.format("%02d", mapRe.get(supvProblem.getRectificationMeasure()).getAlgoDescribe()));
            }
            supvProblem.setProvinceId("13B9B47F1E483324E05338297A0A0595");
        }

        if (supvProblemList.size() > 100) {
            throw new BusinessException("一次最多上送100条数据");
        }

        //TODO
        // 目前一个问题对应一个措施，上送一个问题需要调用问题接口和整改措施接口
        SendParam param = new SendParam();
        param.setStats(supvProblemList);
        param.setProvinceId("13B9B47F1E483324E05338297A0A0595");
        String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
        log.info(Thread.currentThread().getName() + "获取返回体 删除电能质量技术监督工作计划接口数据：" + s + "结束----！");
        Map<String, String> send;
        if(type==0){
            send = send(param, getUrl(2), "pqProblemCreate");
            log.info(Thread.currentThread().getName() + "获取返回体 接收电能质量技术监督实施问题数据接口响应结果：" + send + "结束----！");
        }else{
            send = send(param, getUrl(3), "pqProblemUpdate");
            log.info(Thread.currentThread().getName() + "获取返回体 接收电能质量技术监督实施问题整改数据接口响应结果：" + send + "结束----！");
        }
//        Map<String, String> send = new HashMap<>();

        if (send.containsKey("succeed")) {
            String succeed = send.get("succeed");
            if(succeed.indexOf("\\\"")!=-1){
                succeed = succeed.replace("\\\"", "\"");
            }
            Map map = JSON.parseObject(succeed, Map.class);
            String status = map.get("status").toString();
            if ("000000".equals(status)) {
                for (SupvProblem supvProblem : supvProblemList) {
                    SupvProblem supvProblemPO = new SupvProblem();
                    supvProblemPO.setProblemId(supvProblem.getProblemId());
                    supvProblemPO.setIsUploadHead(1);
                    supvProblemMapper.updateById(supvProblemPO);
                }
                String result = map.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String count = mapCount.get("count").toString();
                return "操作成功:成功数据"+count+"条";
            }else {
                String errors = map.get("errors").toString();
                throw new BusinessException("操作失败:"+status+"_"+errors);
            }
        } else {
            throw new BusinessException("出现未知错误");
        }

    }

    @Override
    public String pushFile(List<String> busIds) throws IOException {
        StringBuilder stringBuilder=new StringBuilder();
        LambdaQueryWrapper<SupvFile> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SupvFile::getBusiId, busIds);
        List<SupvFile> supvFiles = supvFileMapper.selectList(lambdaQueryWrapper);
        if (supvFiles.size() > 100) {
            throw new BusinessException("一次最多上送100条数据");
        }
        JSONArray objects = new JSONArray(Collections.singletonList(supvFiles));
        String s = objects.toString();
        log.info(Thread.currentThread().getName() + "获取返回体 推送附件接口：" + s + "结束----！");
        //TODO 调用上送接口
        for (int i = 0; i < supvFiles.size(); i++) {
//            Map<String, String> sendFile = sendFile(getUrl(4), supvFiles.get(i));
            Map<String, String> sendFile = new HashMap<>();
            log.info(Thread.currentThread().getName() + "获取返回体 总部提供附件接收接口,省公司调用此接口,完成附件上报响应结果：" + sendFile + "结束----！");
            if (sendFile.containsKey("succeed")) {
                String succeed = sendFile.get("succeed");
                if(succeed.indexOf("\\\"")!=-1){
                    succeed = succeed.replace("\\\"", "\"");
                }
                Map map = JSON.parseObject(succeed, Map.class);
                String status = map.get("status").toString();
                if ("000000".equals(status)) {
                    String result = map.get("result").toString();
                    Map mapCount = JSON.parseObject(result, Map.class);
                    String count = mapCount.get("count").toString();
                    stringBuilder.append( "第"+i+"次操作成功:成功数据"+count+"条");
                } else {
                    String errors = map.get("errors").toString();
                    stringBuilder.append("第"+i+"次操作失败:"+status+"_"+errors);
                }
            } else {
                stringBuilder.append("第"+i+"次出现未知错误");
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public String pushMonthReportStatistic(List<String> monthReportId) {
        LambdaQueryWrapper<SupvReportM> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SupvReportM::getMonthReportId, monthReportId);
        List<SupvReportM> supvReportMList = supvReportMMapper.selectList(lambdaQueryWrapper);

        if (supvReportMList.size() > 100) {
            throw new BusinessException("一次最多上送100条数据");
        }
        //TODO 调用上送接口
        SendParam param = new SendParam();
        param.setStats(supvReportMList);
        param.setProvinceId("13B9B47F1E483324E05338297A0A0595");
        String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
        log.info(Thread.currentThread().getName() + "获取返回体 取消电能质量技术监督工作计划接口数据：" + s + "结束----！");
        Map<String, String> send = send(param, getUrl(5), "pqMonthReportCreate");
//        Map<String, String> send = new HashMap<>();
        log.info(Thread.currentThread().getName() + "获取返回体 取消电能质量技术监督工作计划接口响应结果：" + send + "结束----！");
        if (send.containsKey("succeed")) {
            String succeed = send.get("succeed");
            if(succeed.indexOf("\\\"")!=-1){
                succeed = succeed.replace("\\\"", "\"");
            }
            Map map = JSON.parseObject(succeed, Map.class);
            String status = map.get("status").toString();
            if ("000000".equals(status)) {
                for (SupvReportM supvReportM : supvReportMList) {
                    SupvReportM supvReportMPO = new SupvReportM();
                    supvReportMPO.setMonthReportId(supvReportM.getMonthReportId());
                    supvReportMPO.setIsUploadHead(1);
                    supvReportMMapper.updateById(supvReportMPO);
                }
                String result = map.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String count = mapCount.get("count").toString();
                return "操作成功:成功数据"+count+"条";
            } else {
                String errors = map.get("errors").toString();
                throw new BusinessException("操作失败:"+status+"_"+errors);
            }
        } else {
            throw new BusinessException("出现未知错误");
        }
    }

    @Override
    public String deletePlan(List<String> planIds) {
        //判断是否已经取消上送
        LambdaQueryWrapper<SupvPlan> supvPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        supvPlanLambdaQueryWrapper.in(SupvPlan::getIsUploadHead, Stream.of(0, 2).collect(Collectors.toList())).in(SupvPlan::getPlanId, planIds);
        int count = supvPlanMapper.selectCount(supvPlanLambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException("请选择已上送计划");
        }

        List<SupvPlan> supvPlanList = new ArrayList<>();
        for (String id : planIds) {
            SupvPlan supvPlan = new SupvPlan();
            supvPlan.setPlanId(id);
            supvPlan.setProvinceId("13B9B47F1E483324E05338297A0A0595");
            supvPlanList.add(supvPlan);
        }

        //TODO
        SendParam param = new SendParam();
        param.setStats(supvPlanList);
        param.setProvinceId("13B9B47F1E483324E05338297A0A0595");
        String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
        log.info(Thread.currentThread().getName() + "获取返回体 删除电能质量技术监督工作计划接口数据：" + s + "结束----！");
        Map<String, String> send = send(param, getUrl(6), "pqPlanDelete");
//        Map<String, String> send = new HashMap<>();
        log.info(Thread.currentThread().getName() + "获取返回体 删除电能质量技术监督工作计划接口响应结果：" + send + "结束----！");
        if (send.containsKey("succeed")) {
            String succeed = send.get("succeed");
            if(succeed.indexOf("\\\"")!=-1){
                succeed = succeed.replace("\\\"", "\"");
            }
            Map map = JSON.parseObject(succeed, Map.class);
            String status = map.get("status").toString();
            if ("000000".equals(status)) {
                for (SupvPlan supvPlan : supvPlanList) {
                    supvPlan.setIsUploadHead(2);
                    supvPlanMapper.updateById(supvPlan);
                }
                String result = map.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String countNum = mapCount.get("count").toString();
                return "操作成功:成功数据"+countNum+"条";
            } else {
                String errors = map.get("errors").toString();
                throw new BusinessException("操作失败:"+status+"_"+errors);
            }
        } else {
            throw new BusinessException("出现未知错误");
        }
    }

    public static Map<String, String> send(SendParam param, String url, String serviceName) {
        Map<String, String> map = new LinkedHashMap<>();
        ContentBody cb;
        if (ObjectUtil.isNull(param)) {
            cb = new ContentBody("");
        } else {
            String s = JSONObject.toJSONStringWithDateFormat(param, JSON.DEFFAULT_DATE_FORMAT);
            log.info(Thread.currentThread().getName() + "1.信息:" + s);
            cb = new ContentBody(s);
        }
        //ContentBody传递，要求使用post方式进行调用
        //如果需要传递请求参数 可以拼接到请求URL中，或者设置paramsMap参数由SDK内部进行拼接
        HttpParameters.Builder builder = HttpParameters.newBuilder();

        builder.requestURL(url) // 设置请求的URL,可以拼接URL请求参数
                .api("zongbuSync") // 设置服务名
                .version("1.0.0") // 设置版本号
                .method("post") // 设置调用方式, 必须为 post
                .contentType("application/json; charset=UTF-8") //设置请求content-type
                .accessKey("7d4cb2c0afb5468ca56e0654b1a442ef").secretKey("lW2xr6zKjbaqVDOSgQpcGrM6Rg0=");// 设置accessKey 和 设置secretKey


        builder.contentBody(cb);
        String token = LoginToken();
        builder.putHeaderParamsMap("x-token", token);
        builder.putHeaderParamsMap("serviceName", serviceName);
        //进行调用，返回结果
        try {
            HttpReturn ret = HttpCaller.invokeReturn(builder.build());
            String responseStr = ret.getResponseStr();//获取响应的文本串
            map.put("succeed", responseStr);
        } catch (HttpCallerException e) {
            // error process
            log.info(Thread.currentThread().getName() + "错误信息:" + e);
            map.put("error", e.toString());
        }
        return map;
    }

    public static String LoginToken() {
        String token = null;
        String clientId = "942a9278671711eda2e10ae0b5517f6c";
        String clientSecret = "3Psd2VEhsA3dVsSPHW0ll5r/03kAqlA2P4w2IiWPA8UWSadcX0we2wffjyTUYGsK";

        String userUrl = "http://25.36.214.86:32234/psr-auth/oauth/accessToken?grant_type={grant_type}&client_id={client_id}&client_secret={client_secret}";
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "credentials");
        map.put("client_id", clientId);
        map.put("client_secret", clientSecret);
        ResponseEntity<Map> userEntity = RestTemplateUtil.get(userUrl, Map.class, map);

        if (userEntity.getStatusCodeValue() == 200) {
            log.info(Thread.currentThread().getName() + "数据：" + userEntity.getBody() + "结束----！");
            //获取返回体
            Map body = userEntity.getBody();
            token = body.get("access_token").toString();
        }else{
            throw new BusinessException("获取数据token出现未知异常！请检查ip端口是否正确！");
        }
        return token;
    }

    public Map<String,String> sendFile(String url,  SupvFile supvFile) throws IOException {
        String path = supvFile.getFileUrl();
        if (StrUtil.isBlank(path)) {
            throw new BusinessException("获取文件上传路径为空！请检查原始路径是否存在");
        }
        String attachmentName = supvFile.getAttachmentName();
        if (StrUtil.isNotBlank(attachmentName)) {
            int i = attachmentName.lastIndexOf(".");
            if (i != -1) {
                attachmentName = attachmentName.substring(0, i);
            }
        } else {
            throw new BusinessException("不存在文件，文件名称");
        }

        InputStream fileStream = fileStorageUtil.getFileStream(path);
        if (ObjectUtil.isNull(fileStream)) {
            throw new BusinessException("文件服务器，文件不存在");
        }

        Map<String,String> map=new LinkedHashMap<>();

        //ContentBody传递，要求使用post方式进行调用
        //如果需要传递请求参数 可以拼接到请求URL中，或者设置paramsMap参数由SDK内部进行拼接
        HttpParameters.Builder builder = HttpParameters.newBuilder();

        builder.requestURL("http://25.36.214.86:32234/CSB/WMCenter/powerQuality/file/create") // 设置请求的URL,可以拼接URL请求参数
                .api("zongbuSync") // 设置服务名
                .version("1.0.0") // 设置版本号
                .method("post") // 设置调用方式, 必须为 post
                .contentType("application/x-www-form-urlencoded;charset=utf-8") //设置请求content-type
                .accessKey("7d4cb2c0afb5468ca56e0654b1a442ef").secretKey("lW2xr6zKjbaqVDOSgQpcGrM6Rg0="); // 设置accessKey 和 设置secretKey


        String token = LoginToken();
        log.info(Thread.currentThread().getName() + "3.错误信息:"+token);
        builder.putHeaderParamsMap("x-token",token);
        builder.putHeaderParamsMap("serviceName", "pqFileCreate");

        String uploadTime = supvFile.getUploadTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 设置form请求参数
        builder.putParamsMap("uuid", supvFile.getFileUrl())
                .putParamsMap("attachmentName", supvFile.getAttachmentName())
                .putParamsMap("provinceId", "13B9B47F1E483324E05338297A0A0595")
                .putParamsMap("attachmentType", supvFile.getAttachmentType())
                .putParamsMap("busiId", supvFile.getBusiId())
                .putParamsMap("uploaderName", supvFile.getUploaderName())
                .putParamsMap("uploadTime", uploadTime)
                .putParamsMap("uploaderId", supvFile.getUploaderId());
        //设置上传文件
        builder.addAttachFile("file", attachmentName,fileStream);

        //进行调用，返回结果
        try {
            HttpReturn ret = HttpCaller.invokeReturn(builder.build());
            String responseStr = ret.getResponseStr();//获取响应的文本串
            map.put("succeed",responseStr);
        } catch (HttpCallerException e) {
            // error process
            log.info(Thread.currentThread().getName() + "错误信息:"+e);
            map.put("error",e.toString());
        }
        return map;
    }


    /**
     * 文件上送提交
     *
     * @param url
     * @param token
     * @return
     */
    public Map postFileUrl(String url, String token, SupvFile supvFile) throws IOException {
        Map body = new HashMap();
        Map<String, String> mapHeader = new HashMap<>();
        mapHeader.put("Content-Type", "multipart/form-data");
        String path = supvFile.getFileUrl();
        if (StrUtil.isBlank(path)) {
            throw new BusinessException("获取文件上传路径为空！请检查原始路径是否存在");
        }
        String suffix = path.substring(path.lastIndexOf("."));
        String attachmentName = supvFile.getAttachmentName();
        if (StrUtil.isNotBlank(attachmentName)) {
            int i = attachmentName.lastIndexOf(".");
            if (i != -1) {
                attachmentName = attachmentName.substring(0, i);
            }
        } else {
            throw new BusinessException("不存在文件，文件名称");
        }

        InputStream fileStream = fileStorageUtil.getFileStream(path);
        if (ObjectUtil.isNull(fileStream)) {
            throw new BusinessException("文件服务器，文件不存在");
        }
        byte[] fileBytes = IOUtils.toByteArray(fileStream);
        File files = File.createTempFile(attachmentName, suffix);
        FileOutputStream stream = new FileOutputStream(files);
        stream.write(fileBytes);
        stream.close();


        FileSystemResource resource = new FileSystemResource(files);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("uuid", supvFile.getUuid());
        param.add("file", resource);
        param.add("attachmentName", supvFile.getAttachmentName());
        param.add("attachmentType", supvFile.getAttachmentType());
        param.add("busiId", supvFile.getBusiId());
        param.add("uploaderName", supvFile.getUploaderName());
        String uploadTime = supvFile.getUploadTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        param.add("uploadTime", uploadTime);
        param.add("uploaderId", supvFile.getUploaderId());

        ResponseEntity<Map> userEntity = RestTemplateUtil.post(url, mapHeader, param, Map.class, new ArrayList<>());
        files.deleteOnExit();
        if (userEntity.getStatusCodeValue() == 200) {
            //获取返回体
            body = userEntity.getBody();
            log.info(Thread.currentThread().getName() + "获取返回体 getResourceData：" + body + "结束----！");
        }
        return body;
    }

    /**
     * 根据type获取上送地址
     *
     * @param type
     * @return
     */
    public static String getUrl(Integer type) {
        String url = "http://25.36.214.86:32234/CSB";

        switch (type) {
            case 1:
                /**
                 * 接收电能质量技术监督工作计划数据接口
                 */
                url += "/WMCenter/powerQuality/plan/create";
                break;
            case 2:
                /**
                 * 接收电能质量技术监督实施问题数据接口
                 */
                url += "/WMCenter/powerQuality/problem/create";
                break;
            case 3:
                /**
                 * 接收电能质量技术监督实施问题整改数据接口
                 */
                url += "/WMCenter/powerQuality/problem/update";
                break;
            case 4:
                /**
                 * 总部提供附件接收接口,省公司调用此接口,完成附件上报
                 */
                url += "/WMCenter/powerQuality/file/create";
                break;
            case 5:
                /**
                 * 接收电能质量技术监督月报统计数据接口
                 */
                url += "/WMCenter/powerQuality/monthReport/create";
                break;
            case 6:
                /**
                 * 删除电能质量技术监督工作计划接口
                 */
                url += "/WMCenter/powerQuality/plan/delete";
                break;
        }
        return url;
    }

}
