package com.cusc.nirvana.user.rnr.fp.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.encrypt.sign.HMAC;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.CmccCertTypeEnum;
import com.cusc.nirvana.user.rnr.fp.common.MbCodeEnum;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.common.cloud.SignConstants;
import com.cusc.nirvana.user.rnr.fp.common.config.EncryptionConfig;
import com.cusc.nirvana.user.rnr.fp.common.config.SmsPropertyConfig;
import com.cusc.nirvana.user.rnr.fp.common.util.WatermarkUtil;
import com.cusc.nirvana.user.rnr.fp.config.T1Config;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.service.*;
import com.cusc.nirvana.user.rnr.fp.util.*;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrRelationClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.constants.CertTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrBizzTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrFileType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderType;
import com.cusc.nirvana.user.rnr.mg.dto.*;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.DateUtils;
import com.cusc.nirvana.user.util.crypt.DataCryptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: T1上报服务
 * <br />
 * CreateDate 2022-06-07 20:13:25
 *
 * @author yuyi
 **/
@Service
@Slf4j
@RefreshScope
public class T1UploadServiceImpl implements IT1UploadService {

    public static final String SM4_KEY = "7faf0abf9e6c4aa0aa04eeccf3110e37";

    @Resource
    private T1Config t1Config;

    @Autowired
    private MgRnrRelationClient rnrRelationClient;

    @Autowired
    private MgRnrCardInfoClient rnrCardInfoClient;

    @Autowired
    private ISimVehicleRelService simVehicleRelService;

    @Autowired
    private EncryptionConfig encryptionConfig;

    @Autowired
    private IFileService fileService;

    @Autowired
    @Qualifier("noBalanceRestTemplateRnrFpT1")
    RestTemplate noBalanceRestTemplateRnrFpT1;

    @Resource
    private IFpCarInfoService iFpCarInfoService;

    @Resource
    private FpT1UploadStatusServiceImpl fpT1UploadStatusService;

    @Autowired
    private DataCryptService dataCryptService;

//    @Autowired
//    private SmsPropertyConfig smsPropertyConfig;

    @Autowired
    private RnrOrderClient orderClient;

    @Autowired
    private MgRnrInfoClient mgRnrInfoClient;

    @Value("${t1.chinaMobile.platformID:}")
    //由OneLink车联卡实名平台为各个车 企分配的标识
    private String platformID;

    @Value("${t1.chinaMobile.t1UserInfoKey:}")
    //开户信息的加密密钥由 OneLink 平台生成后，自动发送到指定邮箱。
    private String t1UserInfoKey = "7faf0abf9e6c4aa0aa04eeccf3110e37";

    @Autowired
    private CtccT1UploadService ctccSftpUtil;

    @Autowired
    private CmccT1UploadService cmccSftpUtil;

    @Autowired
    private OperatorService operatorService;

    @Value("${T1.power:true}")
    private Boolean power;

    private static  EncryptionKeyDTO encryptionKeyDTO;

    private static String requestIdCmss;

    private static  String companyCode;

    @Override
    public Response uploadUserInfoAndFile(MgCardNoticeDTO cardNoticeDTO) {
        if(cardNoticeDTO.getResultCode()!=3){
            return   Response.createSuccess("不用上报T1");
        }
        //初始化上报状态
        FpT1UploadStatusDTO t1UploadStatus = new FpT1UploadStatusDTO();
        t1UploadStatus.setIccid(cardNoticeDTO.getIccid());
        t1UploadStatus.setOrderId(cardNoticeDTO.getOrderId());
        t1UploadStatus.setTenantNo(cardNoticeDTO.getTenantNo());
        t1UploadStatus.setT1Request(JSON.toJSONString(cardNoticeDTO));
        t1UploadStatus = fpT1UploadStatusService.insertOrReset(t1UploadStatus);
        log.info("uploadUserInfoAndFile t1UploadStatus : {}", JSON.toJSONString(t1UploadStatus));

        MgRnrCardInfoDTO card = new MgRnrCardInfoDTO();
        card.setTenantNo(cardNoticeDTO.getTenantNo());
        card.setIotId(cardNoticeDTO.getVin());
        card.setOrderId(cardNoticeDTO.getOrderId());
        boolean isSuccess = false;


        //实名
        if (RnrBizzTypeEnum.Bind.getCode().equals(cardNoticeDTO.getRnrBizzType())) {
            card.setIccid(cardNoticeDTO.getIccid());
            isSuccess = userInfoUpload(card, true, "4", cardNoticeDTO.getManufacturerOrgId(), "A", cardNoticeDTO);
        }
        //更换责任人
        if (RnrBizzTypeEnum.INFO_CHANGE.getCode().equals(cardNoticeDTO.getRnrBizzType())) {
            card.setIccid(cardNoticeDTO.getIccid());
            isSuccess = userInfoUpload(card, true, "4", cardNoticeDTO.getManufacturerOrgId(), "M",cardNoticeDTO);
        }

        //解绑
        if (RnrBizzTypeEnum.Unbound.getCode().equals(cardNoticeDTO.getRnrBizzType())) {
            card.setIccid(cardNoticeDTO.getIccid());

            RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
            rnrOrderDTO.setUuid(cardNoticeDTO.getOrderId());

            Response<RnrOrderDTO> response = orderClient.getByUuid(rnrOrderDTO);
            if(!response.isSuccess() || null ==response.getData()){
                return Response.createSuccess("没有查到订单信息");
            }
            String vehicleStatus ="";
            if(RnrOrderType.COMPANY_CORPORATION_UNBIND.getCode().equals(response.getData().getOrderType())){
                vehicleStatus = "2";
            }else {
                vehicleStatus = "4";
            }

            isSuccess = userInfoUpload(card, false, vehicleStatus, cardNoticeDTO.getManufacturerOrgId(), "M",cardNoticeDTO);
        }

        //换件
        if (RnrBizzTypeEnum.ChangeBinding.getCode().equals(cardNoticeDTO.getRnrBizzType())) {

            FpT1UploadStatusDTO t1UploadStatusOld = new FpT1UploadStatusDTO();
            t1UploadStatusOld.setIccid(cardNoticeDTO.getOldIccid());
            t1UploadStatusOld.setOrderId(cardNoticeDTO.getOrderId());
            t1UploadStatusOld.setTenantNo(cardNoticeDTO.getTenantNo());
            t1UploadStatus = fpT1UploadStatusService.insertOrReset(t1UploadStatusOld);

            //老卡
            card.setIccid(cardNoticeDTO.getOldIccid());
            isSuccess = userInfoUpload(card, false, "7", cardNoticeDTO.getManufacturerOrgId(), "M",cardNoticeDTO);
            //新卡
            card.setIccid(cardNoticeDTO.getIccid());
            isSuccess = userInfoUpload(card, true, "4", cardNoticeDTO.getManufacturerOrgId(), "M",cardNoticeDTO);
        }
        if (isSuccess) {
            return Response.createSuccess();
        }
        return Response.createError("开户信息和上传文件至少有一个失败");
    }

    /**
     * 用户信息上报
     * isUploadUser : 是否上报用户信息。解绑和换件的老卡不需要，其他需要
     * vehicleStatus 1表示生产期，2表示测试期，3表示待售，4表示已售 5表示过户 6表示报废，7 表示其他
     * operType : 实名时为A，其他为M
     *
     * @return
     */
    private boolean userInfoUpload(MgRnrCardInfoDTO card, boolean isUploadUser, String vehicleStatus, String orgId,
                                   String operType,MgCardNoticeDTO cardNoticeDTO) {
        log.warn("userInfoUpload方法入参===MgRnrCardInfoDTO{},isUploadUser{},vehicleStatus{},orgId{},operType{}",JSON.toJSON(card),
                isUploadUser,vehicleStatus,orgId,operType);
        T1UserInfoDTO ret = new T1UserInfoDTO();

            //查询上报状态
            FpT1UploadStatusDTO t1Us = fpT1UploadStatusService.getByIccidAndOrderId(card.getIccid(),
                    card.getOrderId());
            String t1UploadStatusUuid = "";
            if(t1Us != null){
                t1UploadStatusUuid = t1Us.getUuid();
            }

        //运营商
        String serviceProvider = operatorService.get(cardNoticeDTO.getIccid());
        //通过iccid查询msisdn
        //Response<VinIccidDTO> iccidResp = simVehicleRelService.getVinByIccid(card.getIccid());
        //log.warn("iccidResp回参{}",JSON.toJSON(iccidResp));
        //if (!iccidResp.isSuccess() || iccidResp.getData() == null) {
        //    log.warn("userInfoUpload 通过卡获取msisdn失败，失败原因：{}", JSON.toJSONString(iccidResp));
        //    return false;
        //}
        String orderId = card.getOrderId();
        //VinIccidDTO iccidInfo = iccidResp.getData();
        //ret.setMSISDN(iccidInfo.getMsisdn());
        ret.setICCID(card.getIccid());
        if (vehicleStatus.equals("7")) {
            ret.setVIN("");
        } else {
            ret.setVIN(card.getIotId());
        }
        ret.setVehicleStatus(vehicleStatus);
        ret.setStatusUpdateTime(DateUtils.formatDate(LocalDateTime.now(), "yyyyMMddHHmmss"));
        ret.setAcceptTime(ret.getStatusUpdateTime());

        ret.setServiceProvider(operatorService.get(cardNoticeDTO.getIccid()));

        //通过卡查询到用户信息
        T1UserInfoReqDTO t1UserInfoReq = new T1UserInfoReqDTO();

        //通过租户查询
        FpT1VehicleCompanyDTO t1VehicleCompanyDTO = new FpT1VehicleCompanyDTO();
        t1VehicleCompanyDTO.setTenantNo(card.getTenantNo());
        t1VehicleCompanyDTO.setOrgId(orgId);
        encryptionKeyDTO = encryptionConfig.getKey(orgId);

        log.info("encryptionKeyDATO-----{}",JSON.toJSON(encryptionKeyDTO));
        if(null == encryptionKeyDTO){
            log.warn("查询车企密钥配置失败，查询参数： 租户编号：{}，组织id：{}", card.getTenantNo(), orgId);
            return false;
        }

        RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
        rnrOrderDTO.setUuid(orderId);
        Response<RnrOrderDTO> responseOrder = orderClient.getByUuid(rnrOrderDTO);
        if (!responseOrder.isSuccess() || null == responseOrder.getData()) {
            log.info("查询订单信息失败，查询参数： 订单id：{}", orderId);
            return false;
        }

        MgRnrInfoDTO mgRnrInfoDTO = new MgRnrInfoDTO();
        mgRnrInfoDTO.setUuid(responseOrder.getData().getRnrId());
        Response<MgRnrInfoDTO> mgRnrInfoDTOResponse = mgRnrInfoClient.getByUuid(mgRnrInfoDTO);

        if (!mgRnrInfoDTOResponse.isSuccess() || null == mgRnrInfoDTOResponse.getData()) {
            log.info("查询用户信息失败，查询参数： 订单id：{}", orderId);
            return false;
        }
        Integer CustomerType = mgRnrInfoDTOResponse.getData().getIsCompany();

        //移动用雪花算法
        if(power&& com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(serviceProvider)){
            requestIdCmss = (null!=encryptionKeyDTO.getPlatFormId()&&encryptionKeyDTO.getPlatFormId().length()>5)?encryptionKeyDTO.getPlatFormId().substring(0,5)+String.valueOf(SnowflakeIdWorker.nextId()):encryptionKeyDTO.getPlatFormId()+String.valueOf(SnowflakeIdWorker.nextId());
            t1UserInfoReq.setRequestID(requestIdCmss);
        }else if(power&& com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CTCC.getCode().equals(serviceProvider)){
            t1UserInfoReq.setRequestID(encryptionKeyDTO.getPlatFormId()+String.valueOf(SnowflakeIdWorker.nextId()));
        }else {
            t1UserInfoReq.setRequestID(CuscStringUtils.generateUuid());
        }

        t1VehicleCompanyDTO.setT1UserInfoKey(encryptionKeyDTO.getT1UserInfoKey());
        t1VehicleCompanyDTO.setT1InstructionKey(encryptionKeyDTO.getT1InstructionKey());
        t1VehicleCompanyDTO.setCompanyCode(encryptionKeyDTO.getCompanyCode());

        companyCode =  t1VehicleCompanyDTO.getCompanyCode();

        t1UserInfoReq.setCode(companyCode);
        t1UserInfoReq.setOperType(operType);

        if (!isUploadUser) {
            ret.setCustomerType(CustomerType == 0?"1":"2");
            String encryptUserInfo = RnrDataSm4Util.encryptEcbPadding(t1VehicleCompanyDTO.getT1UserInfoKey(),
                        JSON.toJSONString(ret),true, null);
            t1UserInfoReq.setEncryptUserInfo(encryptUserInfo);
            log.warn("上报开户信息{}",JSON.toJSON(t1UserInfoReq));
            T1CommonResponseDTO t1UserResult = null;
            if(MbCodeEnum.CMCC.getCode().equals(serviceProvider)){
                t1UserResult = this.t1UploadUserInfoCMCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
            }else if(MbCodeEnum.CTCC.getCode().equals(serviceProvider)){
                t1UserResult = this.t1UploadUserInfoCTCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
            }else {
                 t1UserResult = uploadT1UserInfo(t1UserInfoReq);
            }
            log.warn("开户信息回参{}",JSON.toJSON(t1UserResult));

            Response responses = null;
//            //换件 老卡
//            if(RnrBizzTypeEnum.ChangeBinding.getCode().equals(cardNoticeDTO.getRnrBizzType())){
//                response = this.T1CarInfo(cardNoticeDTO.getVin(),cardNoticeDTO.getManufacturerOrgId(),cardNoticeDTO.getTenantNo(),cardNoticeDTO.getIccid(),uuid);
//            }
            return this.getIsUploadUser(t1UserResult,card,t1UploadStatusUuid,cardNoticeDTO,responses);
        }

        Response<RnrRelationDTO> rnrRelationResp = rnrRelationClient.getRnrRelation(card);
        if (!rnrRelationResp.isSuccess() || rnrRelationResp.getData() == null) {
            log.warn("userInfoUpload 通过卡获取实名信息失败，失败原因：{}", JSON.toJSONString(rnrRelationResp));
            return false;
        }
        RnrRelationDTO rnrRelation = rnrRelationResp.getData();
        MgRnrInfoDTO info = rnrRelation.getInfo();
        if (info == null) {
            log.warn("userInfoUpload 通过卡获取Info信息失败，失败原因：实名信息为空。 {}", JSON.toJSONString(rnrRelation));
            return false;
        }

        if (info.getIsCompany() == 0) {
            // 个人
            ret.setCustomerType("1");
            ret.setCustomerName(info.getFullName());
            ret.setCustomerCertType(certTypeTransform(info.getCertType()));
            ret.setCustomerCertNumber(info.getCertNumber());
            ret.setCustomerCertAddress(info.getCertAddress());
            String endTimeStr = info.getExpiredDate();
            SimpleDateFormat simp = new SimpleDateFormat("yyyyMMdd");
            if(!StringUtils.isEmpty(endTimeStr)&&"长期".equals(endTimeStr)){
                log.info("时间长期=====");
                endTimeStr = "30000101";
            }
            endTimeStr = endTimeStr.replaceAll("-","");

            String startTimeStr = "";
            if(null!= info.getEffectiveDate()){
                startTimeStr = simp.format(info.getEffectiveDate());
            }
            ret.setCustomerCertDate(startTimeStr+"-"+endTimeStr);
            log.info("身份证有效期{}",ret.getCustomerCertDate());
//            ret.setCustomerCertDate(endTimeStr);
            ret.setCustomerPosterAddress(info.getContactAddress());
            ret.setCustomerPosterTelephone(info.getPhone());

            //是否有委托人
            if (!CollectionUtils.isEmpty(rnrRelation.getRnrLiaisonList())) {
                MgRnrLiaisonInfoDTO rnrLiaison = rnrRelation.getRnrLiaisonList().get(0);
                ret.setOperatorName(rnrLiaison.getLiaisonName());
                ret.setOperatorCertType(certTypeTransform(rnrLiaison.getLiaisonCertType()));
                ret.setOperatorCertNumber(rnrLiaison.getLiaisonCertNumber());
                ret.setOperatorCertAddress(rnrLiaison.getLiaisonCertAddress());
                ret.setOperatorPosterAddress(rnrLiaison.getLiaisonContactAddress());
                ret.setOperatorTelephone(rnrLiaison.getLiaisonPhone());
            }
        } else {
            //企业
            ret.setCustomerType("2");
            MgRnrCompanyInfoDTO companyInfo = rnrRelation.getCompanyInfo();
            if (companyInfo == null) {
                log.warn("userInfoUpload 企业实名获取企业信息失败，失败原因：企业信息为空。 {}", JSON.toJSONString(rnrRelation));
                return false;
            }
            if (companyInfo.getIsVehicleCompany().intValue() == 1) {
                //车企实名，修改车辆状态
                ret.setVehicleStatus("2");
            }

            ret.setCompanyName(companyInfo.getCompanyName());
            ret.setCompanyCertType(certTypeTransform(companyInfo.getCompanyCertType()));
            ret.setCompanyCertNumber(companyInfo.getCompanyCertNumber());
            ret.setCompanyCertAddress(companyInfo.getCompanyCertAddress());
            ret.setCompanyPosterAddress(companyInfo.getCompanyContactAddress());
            //公司责任人
            ret.setCorporationName(info.getFullName());
            ret.setCorporationCertType(certTypeTransform(info.getCertType()));
            ret.setCorporationCertNumber(info.getCertNumber());
            ret.setCorporationCertAddress(info.getCertAddress());
            ret.setCorporationPosterAddress(info.getContactAddress());
            ret.setCorporationTelephone(info.getPhone());
        }

        ret.setPhoName("KH_" + t1UserInfoReq.getRequestID() + "_" + t1UserInfoReq.getCode() + ".zip");
        ret.setServiceProvider(operatorService.get(cardNoticeDTO.getIccid()));

        boolean fileResult = true;
        if (!CollectionUtils.isEmpty(rnrRelation.getRnrFileList())) {
            //根据文件id，下载，压缩，上传
            T1FileReqDTO t1FileReqDTO = new T1FileReqDTO();
            t1FileReqDTO.setCode(t1VehicleCompanyDTO.getCompanyCode());
            t1FileReqDTO.setRequestID(t1UserInfoReq.getRequestID());
            t1FileReqDTO.setPlatformID(encryptionKeyDTO.getPlatFormId());

            fileResult = fileUpload(rnrRelation.getRnrFileList(), t1FileReqDTO,
                    t1VehicleCompanyDTO.getT1UserInfoKey(), t1UploadStatusUuid,cardNoticeDTO.getIccid());
        }

        //上报开户信息
        String encryptUserInfo = RnrDataSm4Util.encryptEcbPadding(t1VehicleCompanyDTO.getT1UserInfoKey(),
                JSON.toJSONString(ret),
                true, null);
        t1UserInfoReq.setEncryptUserInfo(encryptUserInfo);
        Response response = null;
        //换件 老卡
        if(RnrBizzTypeEnum.ChangeBinding.getCode().equals(cardNoticeDTO.getRnrBizzType())||RnrBizzTypeEnum.Bind.getCode().equals(cardNoticeDTO.getRnrBizzType())){
            response = this.T1CarInfo(cardNoticeDTO.getVin(),cardNoticeDTO.getManufacturerOrgId(),cardNoticeDTO.getTenantNo(),cardNoticeDTO.getIccid(),t1UploadStatusUuid);
        }

        T1CommonResponseDTO t1UserResult = null;


        if(MbCodeEnum.CMCC.getCode().equals(serviceProvider)){
            t1UserResult = this.t1UploadUserInfoCMCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
        }else if(MbCodeEnum.CTCC.getCode().equals(serviceProvider)){
            t1UserResult = this.t1UploadUserInfoCTCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
        }else {
            t1UserResult = uploadT1UserInfo(t1UserInfoReq);
        }
        //防止别的平台已经实名过了
        if(null != t1UserResult && "2".equals(t1UserResult.getOprRst()) && "该iccid未被解绑".equals(t1UserResult.getFailureCause())){
            t1UserInfoReq.setOperType("M");
            if(MbCodeEnum.CMCC.getCode().equals(serviceProvider)){
                t1UserResult = this.t1UploadUserInfoCMCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
            }else if(MbCodeEnum.CTCC.getCode().equals(serviceProvider)){
                t1UserResult = this.t1UploadUserInfoCTCC(card,ret,t1VehicleCompanyDTO,t1UserInfoReq);
            }else {
                t1UserResult = uploadT1UserInfo(t1UserInfoReq);
            }
        }

        if(t1UserResult !=null && t1UserResult.getOprRst().equals("1")){
            this.fpT1UpdateUsertatus(t1UploadStatusUuid,1,t1UserResult);
        }else {
            this.fpT1UpdateUsertatus(t1UploadStatusUuid,2,t1UserResult);
        }


        //更新数据库
        return this.getIsUploadFile(t1UserResult,card,cardNoticeDTO,response,fileResult);

    }

     /**
       * @author: jk
       * @description: 移动开户信息加密 AES
       * @date: 2022/8/9 10:38
       * @version: 1.0
       */
    public String encryptUserInfo(String t1UserInfoKey, String data) {
        byte[] key = AESUtil.MD5(t1UserInfoKey);
        //构建
        AES aes = SecureUtil.aes(key);
        //加密
        return aes.encryptHex(data);
    }
    /**
     * 如果换件和解绑需要三个状态都成功
     * @param t1UserResult
     * @param card
     * @param cardNoticeDTO
     * @param response
     * @param fileResult
     * @return
     */
    private Boolean getIsUploadFile(T1CommonResponseDTO t1UserResult ,MgRnrCardInfoDTO card,MgCardNoticeDTO cardNoticeDTO,Response response,boolean fileResult) {
        //如果换件和解绑需要三个状态都成功
        if (RnrBizzTypeEnum.ChangeBinding.getCode().equals(cardNoticeDTO.getRnrBizzType()) || RnrBizzTypeEnum.Bind.getCode().equals(cardNoticeDTO.getRnrBizzType())) {
            if (t1UserResult != null && t1UserResult.getOprRst().equals("1") && fileResult && response.isSuccess()) {
                this.updateCardStatus(card);
                return true;
            }
        }else {
            if (t1UserResult != null && t1UserResult.getOprRst().equals("1") && fileResult ) {
                this.updateCardStatus(card);
                return true;
            }
        }
        return false;
    }

    /**
     * 如果需要发送车辆信息，用户信息和车辆信息都需要上传成功才可以更新数据库
     * @param t1UserResult
     * @param card
     * @param uuid
     * @param cardNoticeDTO
     * @param response
     * @return
     */
    private Boolean getIsUploadUser(T1CommonResponseDTO t1UserResult ,MgRnrCardInfoDTO card,String uuid,MgCardNoticeDTO cardNoticeDTO,Response response){

        //如果需要发送车辆信息，用户信息和车辆信息都需要上传成功才可以更新数据库
//        if(RnrBizzTypeEnum.ChangeBinding.getCode().equals(cardNoticeDTO.getRnrBizzType())){
//            if (t1UserResult != null && t1UserResult.getOprRst().equals("1") && !response.isSuccess()) {
//                //修改卡card的T1状态
//                this.updateCardStatus(card);
//                //记录入库
//                this.fpT1UpdateUsertatus(uuid,1,t1UserResult);
//                return true;
//            }
//            this.fpT1UpdateUsertatus(uuid,2,t1UserResult);
//            return false;
//        }else {
            if (t1UserResult != null && t1UserResult.getOprRst().equals("1")) {
                //修改卡card的T1状态
                this.updateCardStatus(card);
                //记录入库
                this.fpT1UpdateUsertatus(uuid,1,t1UserResult);
                return true;
            }
            this.fpT1UpdateUsertatus(uuid,2,t1UserResult);
            return false;
//        }

    }

    /**
     * 更新卡状态
     * @param card
     */
    private void updateCardStatus(MgRnrCardInfoDTO card){
        MgRnrCardInfoDTO cardT1 = new MgRnrCardInfoDTO();
        cardT1.setTenantNo(card.getTenantNo());
        cardT1.setIccid(card.getIccid());
        cardT1.setIotId(card.getIotId());
        if(!StringUtils.isEmpty(card.getOrderId())){
            cardT1.setOrderId(card.getOrderId());
        }

        Response<List<MgRnrCardInfoDTO>> cardListResp = rnrCardInfoClient.queryByList(cardT1);
        if (cardListResp != null && !CollectionUtils.isEmpty(cardListResp.getData())) {
            for (MgRnrCardInfoDTO tmpCard : cardListResp.getData()) {
                cardT1 = new MgRnrCardInfoDTO();
                cardT1.setUuid(tmpCard.getUuid());
                cardT1.setT1UploadStatus(1);
                rnrCardInfoClient.update(cardT1);
            }
        }
    }

    /**
     * 更新用户上报状态
     * @param uuid
     * @param status
     * @param t1UserResult
     */
    private void fpT1UpdateUsertatus(String uuid,Integer status , T1CommonResponseDTO t1UserResult){
        FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
        fpT1UploadStatusDTO.setUuid(uuid);
        fpT1UploadStatusDTO.setUserStatus(status);
        fpT1UploadStatusDTO.setUserStatusResp(JSON.toJSONString(t1UserResult));
        fpT1UploadStatusService.update(fpT1UploadStatusDTO);
    }

    /**
     * 更新文件上传状态
     * @param uuid
     * @param status
     * @param t1UserResult
     */
    private void fpT1UpdateFiletatus(String uuid,Integer status , T1CommonResponseDTO t1UserResult){
        FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
        fpT1UploadStatusDTO.setUuid(uuid);
        fpT1UploadStatusDTO.setFileStatus(status);
        fpT1UploadStatusDTO.setFileStatusResp(JSON.toJSONString(t1UserResult));
        fpT1UploadStatusService.update(fpT1UploadStatusDTO);
    }

    /**
     * 车辆上报状态
     * @param uuid
     * @param status
     * @param t1UserResult
     */
    private void fpT1UpdateCartatus(String uuid,Integer status , T1CommonResponseDTO t1UserResult){
        FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
        fpT1UploadStatusDTO.setUuid(uuid);
        fpT1UploadStatusDTO.setCarStatus(status);
        fpT1UploadStatusDTO.setCarStatusResp(JSON.toJSONString(t1UserResult));
        fpT1UploadStatusService.update(fpT1UploadStatusDTO);
    }

    /**
     * @author: jk
     * @description: 车辆信息上报
     * @date: 2022/6/30 17:11
     * @version: 1.0
     */
    private Response T1CarInfo(String vin,String orgId,String tenantNo,String iccid,String uuid){
        log.info("车辆信息上报入参vin{},orgId{},tenantNo{},iccid{},uuid{}",vin,orgId,tenantNo,iccid,uuid);

        T1CarInfoDTO t1CarInfoDTO = new T1CarInfoDTO();
        t1CarInfoDTO.setRequestId(CuscStringUtils.generateUuid());
        t1CarInfoDTO.setCode(encryptionKeyDTO.getCompanyCode());


        FpCarInfoDTO fpCarInfoDTO = new FpCarInfoDTO();
        fpCarInfoDTO.setVin(dataCryptService.encryptData(vin));

        log.info("查询车辆信息入参{}",JSON.toJSON(fpCarInfoDTO));
        List<FpCarInfoDTO> fpCarInfoDTOList = iFpCarInfoService.queryByList(fpCarInfoDTO);
        log.info("查询车辆信息回参{}",JSON.toJSON(fpCarInfoDTOList));

        if(CollectionUtils.isEmpty(fpCarInfoDTOList)){
            return  Response.createError(ResponseCode.DATA_IS_NULL.getMsg(),ResponseCode.DATA_IS_NULL.getCode());
        }
        FpCarInfoDTO fpCarInfo = fpCarInfoDTOList.get(0);
        String encryptCarInfo = null;
        try {
            if (com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.get(iccid).getCode())) {
                Response<VinIccidDTO> iccidResp = simVehicleRelService.getVinByIccid(iccid);
                log.warn("t1UploadUserInfoCMCC方法iccidResp回参{}", JSON.toJSON(iccidResp));
                if (!iccidResp.isSuccess() || iccidResp.getData() == null) {
                    log.warn("t1UploadUserInfoCMCC 通过卡获取msisdn失败，失败原因：{}", JSON.toJSONString(iccidResp));
                }
                VinIccidDTO iccidInfo = iccidResp.getData();
                fpCarInfo.setMSISDN(iccidInfo.getMsisdn());
                encryptCarInfo = AESUtil.encryptStr(JSON.toJSONString(fpCarInfo), encryptionKeyDTO.getCmccTextOrPictureKey());
            } else {
                encryptCarInfo = RnrDataAesUtil.encodeByECB(Md5CaculateUtil.MD5(encryptionKeyDTO.getCarInfoKey()),
                        JSON.toJSONString(fpCarInfoDTOList.get(0)));
                t1CarInfoDTO.setServiceProvider(operatorService.get(iccid));
            }
        } catch (Exception e) {
            log.error("加密失败", e.getMessage());
            FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
            fpT1UploadStatusDTO.setUuid(uuid);
            fpT1UploadStatusDTO.setCarStatus(2);
            fpT1UploadStatusDTO.setCarStatusResp("加密失败");
            fpT1UploadStatusService.update(fpT1UploadStatusDTO);
            return Response.createSuccess("加密失败");
        }

        t1CarInfoDTO.setEncryptCarInfo(encryptCarInfo);

        log.info("车辆信息上报入参{}",JSON.toJSON(t1CarInfoDTO));

        T1CommonResponseDTO t1CommonResponseDTO = null;
        if (power&& com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.get(iccid).getCode())) {
            t1CommonResponseDTO = this.t1UploadCarInfoCMCC(t1CarInfoDTO);
        } else if (power&& com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CTCC.getCode().equals(com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.get(iccid).getCode())) {
            t1CommonResponseDTO = this.t1UploadCarInfoCTCC(t1CarInfoDTO);
        } else {
            //执行文件上传
            t1CommonResponseDTO = uploadT1CarInfo(t1CarInfoDTO);
        }

        log.info("车辆信息上报回参{}",JSON.toJSON(t1CommonResponseDTO));


        if (t1CommonResponseDTO == null || !t1CommonResponseDTO.getOprRst().equals("1") ) {
            FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
            fpT1UploadStatusDTO.setUuid(uuid);
            fpT1UploadStatusDTO.setCarStatus(2);
            fpT1UploadStatusDTO.setCarStatusResp(JSON.toJSONString(t1CommonResponseDTO));
            fpT1UploadStatusService.update(fpT1UploadStatusDTO);
            throw new CuscUserException(t1CommonResponseDTO.getRequestID(),t1CommonResponseDTO.getFailureCause());
        }
        FpT1UploadStatusDTO fpT1UploadStatusDTO = new FpT1UploadStatusDTO();
        fpT1UploadStatusDTO.setUuid(uuid);
        fpT1UploadStatusDTO.setCarStatus(1);
        fpT1UploadStatusDTO.setCarStatusResp(JSON.toJSONString(t1CommonResponseDTO));
        fpT1UploadStatusService.update(fpT1UploadStatusDTO);
        return Response.createSuccess();
    }

    /**
     * Description: 车辆信息上报
     * <br />
     * CreateDate 2022-05-16 10:22:07
     *
     * @author yuyi
     **/
    private T1CommonResponseDTO uploadT1CarInfo(T1CarInfoDTO carInfo) {
        long startTime = System.currentTimeMillis();
        String url = t1Config.getDateUrl() + "/user-rnr-data/data/vehicleInfo";
        log.info("uploadT1CarInfo url: {},request: {}", url, JSON.toJSONString(carInfo));
        String requestStr = JSON.toJSONString(carInfo);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr, headers()),
                        String.class);
        log.info("uploadT1CarInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        return result;
    }

    /**
     * Description: 文件信息上报
     * <br />
     * CreateDate 2022-06-08 09:50:30
     *
     * @author yuyi
     **/
    private boolean fileUpload(List<MgRnrFileDTO> list, T1FileReqDTO t1FileReqDTO, String userInfoT1Key,String uuid,String iccid) {
        //从文件系统下载文件到本地目录
        String folderName = "";
        if(com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(operatorService.get(iccid))) {
            folderName = "KH_" + t1FileReqDTO.getRequestID() + "_"+encryptionKeyDTO.getPlatFormId();
        }else {
            folderName = "KH_" + t1FileReqDTO.getRequestID() + "_" + t1FileReqDTO.getCode();
        }

        String folderPath = System.getProperty("java.io.tmpdir") + File.separator + folderName ;
        File rootFile = new File(folderPath );
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        FileDownloadDTO fileDownload;
        String fileName;
        boolean isDecryptFile;
        for (MgRnrFileDTO file : list) {
            isDecryptFile = true;
            fileName =  fileTypeConvertName(file);
            if (CuscStringUtils.isEmpty(fileName)) {
                continue;
            }

            //判断文件是否需要加密
            if (fileName.equals("027") || fileName.equals("047")) {
                isDecryptFile = false;
            }

//            //通过文件id查询文件格式
//            FileRecordDTO fileRecord = fileService.fileMetainfo(file.getFileSystemId());
//            if (fileRecord == null) {
//                log.error("文件【{}】未查询到文件信息", file.getFileSystemId());
//                continue;
//            }
            //增加文件类型后缀
            fileName = fileName + file.getFileSystemId().substring(file.getFileSystemId().lastIndexOf("."));
            fileDownload = new FileDownloadDTO();
            fileDownload.setFilePath(folderPath);
            fileDownload.setUuid(file.getFileSystemId());
            fileDownload.setFileName(folderName + "_" + fileName);

//            //根据类型判断是否需要解密
//            if (isDecryptFile) {
//                Response<ImageBytesDTO> bytesResp = cuscImageService.getBytes(file.getFileSystemId());
//                if (bytesResp.isSuccess()) {
//                    try {
//                        FileUtils.writeByteArrayToFile(
//                                new File(fileDownload.getFilePath() + File.separator + fileDownload.getFileName()),
//                                bytesResp.getData().getBytes());
//                    } catch (IOException e) {
//                        log.error("FileUtils.writeByteArrayToFile error  ", e);
//                    }
//                }
//            } else {
            String targetPath = fileDownload.getFilePath() + File.separator + fileDownload.getFileName();
            byte[] bytes = fileService.downLoadBytes(file.getFileSystemId());
            InputStream sbs = new ByteArrayInputStream(bytes);

            String font = "中国移动车联网卡实名登记,"+file.getCreateTime()+","+encryptionKeyDTO.getPlatFormId()+t1FileReqDTO.getRequestID();

            try {
                //移动需要增加水印
                if(MbCodeEnum.CMCC.getCode().equals(operatorService.get(iccid))) {
                    WatermarkUtil.waterPress(sbs, new FileOutputStream(targetPath), 14, 0.9f, 30, 30, font.split(","));
                }else {
                    Files.copy(sbs, Paths.get(targetPath));
                }
                new File(targetPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
//                fileService.downloadToLocal(fileDownload);

        }

//        }
        //压缩目录并加密，将压缩文件读取到EncryptFile中
        String zipFileName = folderPath + ".zip";
        try {

            if (com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(operatorService.get(iccid))) {
                ZipUtils.toZip(folderPath, new FileOutputStream(zipFileName), false);

                File file = encryptZipFile(new File(zipFileName),encryptionKeyDTO);
                t1FileReqDTO.setEncryptFile(file);
                log.info("file.getPath(){},",file.getPath());
//                AESUtil.decryptFile(fpT1VehicleCompanyDTO.getCmccTextOrPictureKey(),file.getPath(),"D:\\测试文件夹\\"+file.getName());
            }else {
                ZipUtils.toZip(folderPath, new FileOutputStream(zipFileName), false);
                log.info("zipFileName----------{}",JSON.toJSON(zipFileName));
                byte[] byteArr = ZipUtils.readByteFromFile(zipFileName);

                log.info("userInfoT1Key============={}",JSON.toJSON(encryptionKeyDTO.getT1UserInfoKey()));

                byte[] encodeByteArr = RnrDataSm4Util.encryptEcbPaddingBytes(encryptionKeyDTO.getT1UserInfoKey(), byteArr, true);

                t1FileReqDTO.setEncryptFile(CuscFileUtils.byte2File(encodeByteArr, folderPath + ".bin"));
            }

            t1FileReqDTO.setServiceProvider(iccid);
            if(MbCodeEnum.CMCC.getCode().equals(MbCodeEnum.get(iccid).getCode())){
                this.t1UploadFileInfoCMCC(t1FileReqDTO,uuid);
            }else if(MbCodeEnum.CTCC.getCode().equals(MbCodeEnum.get(iccid).getCode())){
                this.t1UploadFileInfoCTCC(t1FileReqDTO,uuid);
            }else {
                //执行文件上传
                uploadT1File(t1FileReqDTO,uuid);
            }
        } catch (Exception e) {
            log.error("ZipUtils toZip error ", e);
            return false;
        } finally {
            //删除文件夹
            CuscFileUtils.delFolder(folderPath);
            //删除zip文件
            File zipFile = new File(zipFileName);
            if (zipFile.exists()) {
                zipFile.delete();
            }
            //删除bin文件
            File binFile = new File(folderPath + ".bin");
            if (binFile.exists()) {
                binFile.delete();
            }
        }
        return true;
    }

    @Override
    public File encryptZipFile(File zip,EncryptionKeyDTO encryptionKeyDTO) throws Exception {
        String sourceFile = zip.getAbsolutePath();
        return AESUtil.encryptFile(encryptionKeyDTO.getCmccTextOrPictureKey(), sourceFile, -1 != sourceFile.indexOf(".zip") ? sourceFile.replace(".zip", ".bin") : sourceFile);
    }

    @Override
    public T1CommonResponseDTO t1CallbackResult(T1CallbackResultDTO t1CallbackResultDTO) {
        T1CommonResponseDTO t1CommonResponseDTO = new T1CommonResponseDTO();
        t1CommonResponseDTO.setRequestID(t1CallbackResultDTO.getRequestID());
        //查询上报信息
        FpT1UploadStatusDTO fpT1UploadStatusDTO = fpT1UploadStatusService.getByRequestId(t1CallbackResultDTO.getRequestID());
        if(null == fpT1UploadStatusDTO ){
            t1CommonResponseDTO.setOprRst("2");
            t1CommonResponseDTO.setFailureCause("根据requestId没有查询到上报信息");
            log.info("没有查询到T1上报信息requestId{}",t1CallbackResultDTO.getRequestID());
            return t1CommonResponseDTO;
        }
        FpT1UploadStatusDTO fpT1UploadStatus = new FpT1UploadStatusDTO();
        fpT1UploadStatus.setUuid(fpT1UploadStatusDTO.getUuid());
        fpT1UploadStatus.setReportCompletion(Integer.valueOf(t1CallbackResultDTO.getOprRst()));
        fpT1UploadStatus.setReportCompletionResp(JSON.toJSONString(t1CallbackResultDTO));
        fpT1UploadStatusService.update(fpT1UploadStatus);
        t1CommonResponseDTO.setOprRst("1");
        return t1CommonResponseDTO;
    }

    @Override
    public Response againUploadUserInfoAndFile(AgainUploadDTO againUploadDTO) {
        List<String> requestIdList = againUploadDTO.getRequestIdList();
        if(CollectionUtils.isEmpty(requestIdList)){
            return Response.createError("入参不可以为空");
        }
        List<FpT1UploadStatusDTO> list = fpT1UploadStatusService.queryByRequestIdList(requestIdList);
        if(CollectionUtils.isEmpty(list)){
            return Response.createError("没有查询到上报信息");
        }
        for(FpT1UploadStatusDTO fpT1UploadStatusDTO : list){
            MgCardNoticeDTO mgCardNoticeDTO = JSON.parseObject(fpT1UploadStatusDTO.getT1Request(),MgCardNoticeDTO.class);
            Response response = uploadUserInfoAndFile(mgCardNoticeDTO);
            if(!response.isSuccess()){
                log.warn("重试失败requestId{}",fpT1UploadStatusDTO.getRequestId());
            }
        }
        return Response.createSuccess();
    }

    public static void main(String[] args) {
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.add(SignConstants.APP_ID, "78F985EE0C6F4418B73013D2B5C48AB2");
//        httpHeaders.add(SignConstants.NONCE_STR, CuscStringUtils.generateUuid());
//        httpHeaders.add(SignConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis()));
//        httpHeaders.add(SignConstants.VERSION, "1.0.0");
//        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
//        StringBuilder sb = new StringBuilder();
//        sb.append(SignConstants.APP_ID + "78F985EE0C6F4418B73013D2B5C48AB2");
//        sb.append(SignConstants.NONCE_STR + httpHeaders.get(SignConstants.NONCE_STR).get(0));
//        sb.append(SignConstants.TIMESTAMP + httpHeaders.get(SignConstants.TIMESTAMP).get(0));
//        sb.append(SignConstants.VERSION + httpHeaders.get(SignConstants.VERSION).get(0));
//        log.info("SmsServiceImpl headers param : {}, appScret:{}", sb, "6C0768AA4CE64AC3893A0F0F280571A6");
//        String scret = HMAC.sign(sb.toString(), "6C0768AA4CE64AC3893A0F0F280571A6", HMAC.Type.HmacSHA256);
//        httpHeaders.add(SignConstants.SIGN, scret);
//
//        RestTemplate restTemplate = new RestTemplate();
//        long startTime = System.currentTimeMillis();
//
//        String url = "https://pre-fileservice.cu-sc.com:19098/open-api/unified-storage/file/api/upload";
//
//        File file = new File("C:\\Users\\PC\\Desktop\\T1上报.txt");
//
//        FileSystemResource fileSystemResource = new FileSystemResource(file);
//
//        // body体参数
//        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
//        // headers参数
//        HttpHeaders requestHeaders = new HttpHeaders();
//        requestBody.add("RequestID", "dsajsahsadfsdfsfahksa");
////        requestBody.add("Path", file.getEncryptFile().getPath());
//        try {
//            requestBody.add("Md5", DigestUtils.md5Hex(new FileInputStream(file)));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        requestBody.add("File", fileSystemResource);
//
////        ByteArrayResource resource = null;
////            //存储
////        resource = new ByteArrayResource(File2byte(file.getEncryptFile())) ;
////        requestBody.add("File", resource);
//
////        try {
////            InputStream inputStream = new FileInputStream(file.getEncryptFile());
////            MultipartFile multipartFile = new MockMultipartFile(file.getEncryptFile().getName(), inputStream);
////            requestBody.add("File", multipartFile.getResource());
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//
//        // 封装所有参数
//        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
//        ResponseEntity<String> entity =
//                restTemplate.exchange(url,HttpMethod.POST, requestEntity, String.class);
//        log.info("uploadT1File url: {},response: {},cost: {} ms", url, entity.getBody(),
//                System.currentTimeMillis() - startTime);
//        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
//


        RestTemplate restTemplateT1 = new RestTemplate();
        long startTimeT1 = System.currentTimeMillis();

        HttpHeaders httpHeaderT1 = new HttpHeaders();
        httpHeaderT1.add(SignConstants.APP_ID, "78F985EE0C6F4418B73013D2B5C48AB2");
        httpHeaderT1.add(SignConstants.NONCE_STR, CuscStringUtils.generateUuid());
        httpHeaderT1.add(SignConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis()));
        httpHeaderT1.add(SignConstants.VERSION, "1.0.0");
        httpHeaderT1.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        StringBuilder sbs = new StringBuilder();
        sbs.append(SignConstants.APP_ID + "78F985EE0C6F4418B73013D2B5C48AB2");
        sbs.append(SignConstants.NONCE_STR + httpHeaderT1.get(SignConstants.NONCE_STR).get(0));
        sbs.append(SignConstants.TIMESTAMP + httpHeaderT1.get(SignConstants.TIMESTAMP).get(0));
        sbs.append(SignConstants.VERSION + httpHeaderT1.get(SignConstants.VERSION).get(0));
        log.info("SmsServiceImpl headers param : {}, appScret:{}", sbs, "6C0768AA4CE64AC3893A0F0F280571A6");
        String screts = HMAC.sign(sbs.toString(), "6C0768AA4CE64AC3893A0F0F280571A6", HMAC.Type.HmacSHA256);
        httpHeaderT1.add(SignConstants.SIGN, screts);

        // body体参数
        Map<String, String> requestBodyT1 = new HashMap<>();
        // 设置header是文件上传
        // 参数设置文件
        requestBodyT1.put("RequestID", "dsajsahsadfsdfsfahksa");
        requestBodyT1.put("Code", "cuscplus");
//        requestBody.add("EncryptFile", fileSystemResource);
        requestBodyT1.put("EncryptFileId", "261a1000000000000285235");

        String urls = "https://pre-rnr-open-api.cu-sc.com:19098/open-api/user-rnr-data/file/rnr";

//        try {
//            requestBody.add("FileMd5",DigestUtils.md5Hex(new FileInputStream(file.getEncryptFile())));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        requestBodyT1.put("ServiceProvider", "89860098000000000036");
        // 封装所有参数
        HttpEntity<Map<String, String>> requestEntitys = new HttpEntity<>(requestBodyT1, httpHeaderT1);
        log.info("开户文件上报{}",JSON.toJSON(requestEntitys));
        ResponseEntity<String> entitys =
                restTemplateT1.exchange(urls, HttpMethod.POST, requestEntitys, String.class);
        log.info("开户文件上报回参 url: {},response: {},cost: {} ms", urls, entitys.getBody(),
                System.currentTimeMillis() - startTimeT1);
        T1CommonResponseDTO results = JSON.parseObject(entitys.getBody(), T1CommonResponseDTO.class);
        System.out.println(JSON.toJSON(results));


    }
    /**
     * Description: 根据文件类型转文件名称
     * <br />
     * CreateDate 2022-06-08 21:32:02
     *
     * @author yuyi
     **/
    private String fileTypeConvertName(MgRnrFileDTO file) {
        StringBuffer fileName = new StringBuffer();
        fileName.append("0");
        //第3 位指示照片类型，“1”表示“视频截图1”，“2”表示“视频截图2”，“4”表示“证件正面照片”，“5”表示“证件反面照片”，“6”表示“现场正面照片”，“7”表示“授权书”
        //判断个人还是企业
        if (file.getIsCompany() == 0) {
            //“1”表示个人用户照片，，“4”表示代/经办人照片
            //个人
            if (CuscStringUtils.isEmpty(file.getLiaisonId()) || file.getLiaisonId().equals("0")) {
                //本人
                //“1”表示“视频截图1”
                if (RnrFileType.LIVENESS_SCREEN_FIRST.getCode().equals(file.getFileType())) {
                    fileName.append("11");
                    return fileName.toString();
                }
                //“2”表示“视频截图2”
                if (RnrFileType.LIVENESS_SCREEN_TWO.getCode().equals(file.getFileType())) {
                    fileName.append("12");
                    return fileName.toString();
                }
                //“4”表示“证件正面照片”
                if (isCertPicFront(file.getFileType())) {
                    fileName.append("14");
                    return fileName.toString();
                }
                //“5”表示“证件反面照片”
                if (isCertPicBack(file.getFileType())) {
                    fileName.append("15");
                    return fileName.toString();
                }
            } else {
                //委托人
                //“1”表示“视频截图1”
                if (RnrFileType.LIVENESS_SCREEN_FIRST.getCode().equals(file.getFileType())) {
                    fileName.append("41");
                    return fileName.toString();
                }
                //“2”表示“视频截图2”
                if (RnrFileType.LIVENESS_SCREEN_TWO.getCode().equals(file.getFileType())) {
                    fileName.append("42");
                    return fileName.toString();
                }
                //“4”表示“证件正面照片”
                if (isCertPicFront(file.getFileType())) {
                    fileName.append("44");
                    return fileName.toString();
                }
                //“5”表示“证件反面照片”
                if (isCertPicBack(file.getFileType())) {
                    fileName.append("45");
                    return fileName.toString();
                }
                //个人 “7”表示“授权书”
                if (RnrFileType.LETTER_ATTORNEY.getCode().equals(file.getFileType())) {
                    fileName.append("47");
                    return fileName.toString();
                }
            }
        } else {
            //企业  “2”表示责任人照片，“3”表示单位照片
            //“1”表示“视频截图1”
            if (RnrFileType.LIVENESS_SCREEN_FIRST.getCode().equals(file.getFileType())) {
                fileName.append("21");
                return fileName.toString();
            }
            //“2”表示“视频截图2”
            if (RnrFileType.LIVENESS_SCREEN_TWO.getCode().equals(file.getFileType())) {
                fileName.append("22");
                return fileName.toString();
            }
            //“4”表示“证件正面照片”
            if (isCertPicFront(file.getFileType())) {
                fileName.append("24");
                return fileName.toString();
            }
            //“5”表示“证件反面照片”
            if (isCertPicBack(file.getFileType())) {
                fileName.append("25");
                return fileName.toString();
            }
            //企业 “7”表示“授权书”
            if (RnrFileType.ENTERPRISE_AUTH_FILE.getCode().equals(file.getFileType())) {
                fileName.append("27");
                return fileName.toString();
            }
            //企业 “4”表示“证件正面照片”
            if (RnrFileType.ENTERPRISE_PIC.getCode().equals(file.getFileType())) {
                fileName.append("34");
                return fileName.toString();
            }
        }
        return null;
    }

    /**
     * Description: 验证文件类型是否是证件正面
     * <br />
     * CreateDate 2022-06-09 10:12:56
     *
     * @author yuyi
     **/
    private boolean isCertPicFront(Integer fileType) {
        if (RnrFileType.IDENTITY_CARD_BACK.getCode().equals(fileType)
                || RnrFileType.OFFICIAL_CARD_FRONT.getCode().equals(fileType)
                || RnrFileType.POLICE_CARD_FRONT.getCode().equals(fileType)
                || RnrFileType.HK_MACAO_PASSPORT_FRONT.getCode().equals(fileType)
                || RnrFileType.TAIWAN_CARD_FRONT.getCode().equals(fileType)
                || RnrFileType.FOREIGN_NATIONAL_PASSPORT_FRONT.getCode().equals(fileType)
                || RnrFileType.HK_MACAO_RESIDENCE_PERMIT_FRONT.getCode().equals(fileType)
                || RnrFileType.TAIWAN_RESIDENCE_PERMIT_FRONT.getCode().equals(fileType)) {
            return true;
        }
        return false;
    }

    /**
     * Description: 验证文件类型是否是证件反面
     * <br />
     * CreateDate 2022-06-09 10:12:56
     *
     * @author yuyi
     **/
    private boolean isCertPicBack(Integer fileType) {
        if (RnrFileType.IDENTITY_CARD_FRONT.getCode().equals(fileType)
                || RnrFileType.OFFICIAL_CARD_BACK.getCode().equals(fileType)
                || RnrFileType.POLICE_CARD_BACK.getCode().equals(fileType)
                || RnrFileType.HK_MACAO_PASSPORT_BACK.getCode().equals(fileType)
                || RnrFileType.TAIWAN_CARD_BACK.getCode().equals(fileType)
                || RnrFileType.FOREIGN_NATIONAL_PASSPORT_BACK.getCode().equals(fileType)
                || RnrFileType.HK_MACAO_RESIDENCE_PERMIT_BACK.getCode().equals(fileType)
                || RnrFileType.TAIWAN_RESIDENCE_PERMIT_BACK.getCode().equals(fileType)) {
            return true;
        }
        return false;
    }


    /**
     * Description: 上传开户信息
     * <br />
     * CreateDate 2022-05-16 10:22:07
     *
     * @author yuyi
     **/
    private T1CommonResponseDTO uploadT1UserInfo(T1UserInfoReqDTO userInfo) {
        long startTime = System.currentTimeMillis();
        String url = t1Config.getDateUrl() + "/user-rnr-data/data/userInfo";
        log.info("uploadUserInfo url: {},request: {}", url, JSON.toJSONString(userInfo));
        String requestStr = JSON.toJSONString(userInfo);

        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr, headers()),
                        String.class);
        log.info("uploadUserInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        return result;
    }

    public HttpHeaders headers() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(SignConstants.APP_ID, t1Config.getAPPID());
        httpHeaders.add(SignConstants.NONCE_STR, CuscStringUtils.generateUuid());
        httpHeaders.add(SignConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis()));
        httpHeaders.add(SignConstants.VERSION, t1Config.getVERSION());
        httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        StringBuilder sb = new StringBuilder();
        sb.append(SignConstants.APP_ID + t1Config.getAPPID());
        sb.append(SignConstants.NONCE_STR + httpHeaders.get(SignConstants.NONCE_STR).get(0));
        sb.append(SignConstants.TIMESTAMP + httpHeaders.get(SignConstants.TIMESTAMP).get(0));
        sb.append(SignConstants.VERSION + httpHeaders.get(SignConstants.VERSION).get(0));
        log.info("SmsServiceImpl headers param : {}, appScret:{}", sb, t1Config.getAPPSCRET());
        String scret = HMAC.sign(sb.toString(), t1Config.getAPPSCRET(), HMAC.Type.HmacSHA256);
        httpHeaders.add(SignConstants.SIGN, scret);
        log.info("httpHeaders============{}",JSON.toJSON(httpHeaders));
        return httpHeaders;
    }

    public HttpHeaders fileHeader() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(SignConstants.APP_ID, t1Config.getAPPID());
        httpHeaders.add(SignConstants.NONCE_STR, CuscStringUtils.generateUuid());
        httpHeaders.add(SignConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis()));
        httpHeaders.add(SignConstants.VERSION, t1Config.getVERSION());
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        StringBuilder sb = new StringBuilder();
        sb.append(SignConstants.APP_ID + t1Config.getAPPID());
        sb.append(SignConstants.NONCE_STR + httpHeaders.get(SignConstants.NONCE_STR).get(0));
        sb.append(SignConstants.TIMESTAMP + httpHeaders.get(SignConstants.TIMESTAMP).get(0));
        sb.append(SignConstants.VERSION + httpHeaders.get(SignConstants.VERSION).get(0));
        log.info("SmsServiceImpl headers param : {}, appScret:{}", sb, t1Config.getAPPSCRET());
        String scret = HMAC.sign(sb.toString(), t1Config.getAPPSCRET(), HMAC.Type.HmacSHA256);
        httpHeaders.add(SignConstants.SIGN, scret);
        log.info("httpHeaders============{}",JSON.toJSON(httpHeaders));
        return httpHeaders;
    }
    /**
     * Description: 上传开户信息
     * <br />
     * CreateDate 2022-05-16 10:22:07
     *
     * @author yuyi
     **/
    private T1CommonResponseDTO uploadT1File(T1FileReqDTO file,String uuid) {
        T1CommonResponseDTO  t1= uploadFile(file);
        if(null !=t1.getOprRst() && !"1".equals(t1.getOprRst())){
            this.fpT1UpdateFiletatus(uuid,2,t1);
            return t1;
        }
        long startTime = System.currentTimeMillis();
        String url = t1Config.getDateUrl() + "/user-rnr-data/file/rnr";
        log.info("uploadT1File url: {},request: {}", url, JSON.toJSONString(file));
        FileSystemResource fileSystemResource = new FileSystemResource(file.getEncryptFile());
        // headers参数
            HttpHeaders requestHeaders = new HttpHeaders();
        // body体参数
        Map<String, String> requestBody = new HashMap<>();
        // 设置header是文件上传
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 参数设置文件
        requestBody.put("RequestID", file.getRequestID());
        requestBody.put("Code", file.getCode());
//        requestBody.add("EncryptFile", fileSystemResource);
        requestBody.put("EncryptFileId", t1.getFileId());


//        try {
//            requestBody.add("FileMd5",DigestUtils.md5Hex(new FileInputStream(file.getEncryptFile())));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        requestBody.put("ServiceProvider", file.getServiceProvider());
        // 封装所有参数
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers());
        log.info("开户文件上报{}",JSON.toJSON(requestEntity));
        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, requestEntity, String.class);
        log.info("uploadT1File url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);

        if(result.getOprRst().equals("1")){
            this.fpT1UpdateFiletatus(uuid,1,result);
        }else {
            this.fpT1UpdateFiletatus(uuid,2,result);
        }

        return result;
    }

    /**
     * 中国移动上传开户信息
     */
    private T1CommonResponseDTO t1UploadUserInfoCMCC(MgRnrCardInfoDTO card,T1UserInfoDTO ret,FpT1VehicleCompanyDTO t1VehicleCompanyDTO,T1UserInfoReqDTO t1UserInfoReq){
        //通过iccid查询msisdn
        T1CommonResponseDTO result = null;

        Response<VinIccidDTO> iccidResp = simVehicleRelService.getVinByIccid(card.getIccid());
        log.warn("t1UploadUserInfoCMCC方法iccidResp回参{}",JSON.toJSON(iccidResp));
        if (!iccidResp.isSuccess() || iccidResp.getData() == null) {
            log.warn("t1UploadUserInfoCMCC 通过卡获取msisdn失败，失败原因：{}", JSON.toJSONString(iccidResp));
        }
        VinIccidDTO iccidInfo = iccidResp.getData();
        ret.setMSISDN(iccidInfo.getMsisdn());
        //移动的开户信息用AES加密
        String encryptUserInfo = null;
        try {
            encryptUserInfo = AESUtil.encryptStr( JSON.toJSONString(ret),encryptionKeyDTO.getCmccTextOrPictureKey());
        } catch (Exception e) {

            result = new T1CommonResponseDTO();
            result.setOprRst("2");
            result.setFailureCause("加密失败");
            return result;
        }

        t1UserInfoReq.setEncryptUserInfo(encryptUserInfo);

        t1UserInfoReq.setAuth(getAuth(encryptionKeyDTO));
        t1UserInfoReq.setServiceProvider(null);


        long startTime = System.currentTimeMillis();
        String url = t1Config.getCmccUrl() + "/realname/interface/v1/account-info/sync";
        log.info("uploadUserInfo url: {},request: {}", url, JSON.toJSONString(t1UserInfoReq));
        String requestStr = JSON.toJSONString(t1UserInfoReq);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        try {
            ResponseEntity<String> entity =
                    noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr,requestHeaders),
                            String.class);
            log.info("uploadUserInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                    System.currentTimeMillis() - startTime);
            result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        } catch (RestClientException e) {
            result = new T1CommonResponseDTO();
            result.setOprRst("2");
            result.setFailureCause("调用报错");
        }
        return result;
    }

    /**
     * 中国移动上传车辆信息
     */
    private T1CommonResponseDTO t1UploadCarInfoCMCC(T1CarInfoDTO t1CarInfoDTO){

        T1CarInfoCMCCDTO t1CarInfoCMCCDTO = new T1CarInfoCMCCDTO();
        BeanUtils.copyProperties(t1CarInfoDTO,t1CarInfoCMCCDTO);
        t1CarInfoCMCCDTO.setAuth(getAuth(encryptionKeyDTO));
        t1CarInfoCMCCDTO.setRequestId(requestIdCmss);

        long startTime = System.currentTimeMillis();
        String url = t1Config.getCmccUrl() + "/realname/interface/v1/car-info/sync";
        log.info("uploadUserInfo url: {},request: {}", url, JSON.toJSONString(t1CarInfoCMCCDTO));
        String requestStr = JSON.toJSONString(t1CarInfoCMCCDTO);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr, requestHeaders),
                        String.class);
        log.info("uploadUserInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        return result;
    }

    /**
     * 中国移动上传图片信息
     */
    private Boolean t1UploadFileInfoCMCC(T1FileReqDTO t1FileReqDTO,String uuid) {
        Response response = cmccSftpUtil.upload(t1FileReqDTO);

        T1CommonResponseDTO t1CommonResponseDTO = new T1CommonResponseDTO();
        t1CommonResponseDTO.setFailureCause("上传移动文件服务器失败");
        t1CommonResponseDTO.setRequestID(response.getException());
        t1CommonResponseDTO.setFailureCause(response.getMsg());
        if(response.isSuccess()){
            t1CommonResponseDTO.setOprRst("1");
            this.fpT1UpdateFiletatus(uuid,1,t1CommonResponseDTO);
            return true;
        }else {
            t1CommonResponseDTO.setOprRst("2");
            this.fpT1UpdateFiletatus(uuid,2,t1CommonResponseDTO);
            return false;
        }
    }

    /**
     * 中国电信上传开户信息
     */
    private T1CommonResponseDTO t1UploadUserInfoCTCC(MgRnrCardInfoDTO card,T1UserInfoDTO ret,FpT1VehicleCompanyDTO t1VehicleCompanyDTO,T1UserInfoReqDTO t1UserInfoReq){
        //通过iccid查询msisdn
        Response<VinIccidDTO> iccidResp = simVehicleRelService.getVinByIccid(card.getIccid());
        log.warn("t1UploadUserInfoCMCC方法iccidResp回参{}",JSON.toJSON(iccidResp));
        if (!iccidResp.isSuccess() || iccidResp.getData() == null) {
            log.warn("t1UploadUserInfoCMCC 通过卡获取msisdn失败，失败原因：{}", JSON.toJSONString(iccidResp));
        }
        VinIccidDTO iccidInfo = iccidResp.getData();
        ret.setMSISDN(iccidInfo.getMsisdn());

        String encryptUserInfo = RnrDataSm4Util.encryptEcbPadding(t1VehicleCompanyDTO.getT1UserInfoKey(),
                JSON.toJSONString(ret),
                true, null);
        t1UserInfoReq.setEncryptUserInfo(encryptUserInfo);

        t1UserInfoReq.setAuth(getAuth(encryptionKeyDTO));

        long startTime = System.currentTimeMillis();
        String url = t1Config.getCtccUrl() + "/api/createAccount";
        log.info("uploadUserInfo url: {},request: {}", url, JSON.toJSONString(t1UserInfoReq));
        String requestStr = JSON.toJSONString(t1UserInfoReq);

        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr),
                        String.class);
        log.info("uploadUserInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        return result;
    }

    /**
     * 中国电信上传车辆信息
     */
    private T1CommonResponseDTO t1UploadCarInfoCTCC(T1CarInfoDTO t1CarInfoDTO){
        //通过iccid查询msisdn
//        Response<VinIccidDTO> iccidResp = simVehicleRelService.getVinByIccid(card.getIccid());
//        log.warn("t1UploadCarInfoCUCC方法iccidResp回参{}",JSON.toJSON(iccidResp));
//        if (!iccidResp.isSuccess() || iccidResp.getData() == null) {
//            log.warn("t1UploadCarInfoCUCC 通过卡获取msisdn失败，失败原因：{}", JSON.toJSONString(iccidResp));
//        }
//        VinIccidDTO iccidInfo = iccidResp.getData();
//        ret.setMSISDN(iccidInfo.getMsisdn());


        T1CarInfoCMCCDTO t1CarInfoCMCCDTO = new T1CarInfoCMCCDTO();
        BeanUtils.copyProperties(t1CarInfoDTO,t1CarInfoCMCCDTO);
        t1CarInfoCMCCDTO.setAuth(getAuth(encryptionKeyDTO));

        long startTime = System.currentTimeMillis();
        String url = t1Config.getCtccUrl() + "/api/vehicleInfo";
        log.info("uploadUserInfo url: {},request: {}", url, JSON.toJSONString(t1CarInfoCMCCDTO));
        String requestStr = JSON.toJSONString(t1CarInfoCMCCDTO);

        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url, HttpMethod.POST, new HttpEntity<>(requestStr),
                        String.class);
        log.info("uploadUserInfo url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);
        return result;
    }

    /**
     * 中国电信上传图片信息
     */
    private Boolean t1UploadFileInfoCTCC(T1FileReqDTO t1FileReqDTO,String uuid){
        Response response = ctccSftpUtil.upload(t1FileReqDTO);

        T1CommonResponseDTO t1CommonResponseDTO = new T1CommonResponseDTO();
        t1CommonResponseDTO.setFailureCause("上传移动文件服务器失败");
        t1CommonResponseDTO.setRequestID(response.getException());
        t1CommonResponseDTO.setFailureCause(response.getMsg());
        if (response.isSuccess()) {
            t1CommonResponseDTO.setOprRst("1");
            this.fpT1UpdateFiletatus(uuid, 1, t1CommonResponseDTO);
            return true;
        } else {
            t1CommonResponseDTO.setOprRst("2");
            this.fpT1UpdateFiletatus(uuid, 2, t1CommonResponseDTO);
            log.warn("t1UploadFileInfoCTCC---{}", response.getMsg());
            return false;
        }
    }
    /**
     * 上传文件信息
     * @param file
     * @return
     */
    private T1CommonResponseDTO uploadFile(T1FileReqDTO file) {
        long startTime = System.currentTimeMillis();
        String url = t1Config.getFileUrl() + "/unified-storage/file/api/upload";
        log.info("uploadFile url: {},request: {}", url, JSON.toJSONString(file));
        File f = file.getEncryptFile();
        FileSystemResource fileSystemResource = new FileSystemResource(f);

        // body体参数
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        // headers参数
        HttpHeaders requestHeaders = new HttpHeaders();
        requestBody.add("RequestID", file.getRequestID());
//        requestBody.add("Path", file.getEncryptFile().getPath());
        try {
            requestBody.add("Md5", DigestUtils.md5Hex(new FileInputStream(f)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        requestBody.add("File", fileSystemResource);

//        ByteArrayResource resource = null;
//            //存储
//        resource = new ByteArrayResource(File2byte(file.getEncryptFile())) ;
//        requestBody.add("File", resource);

//        try {
//            InputStream inputStream = new FileInputStream(file.getEncryptFile());
//            MultipartFile multipartFile = new MockMultipartFile(file.getEncryptFile().getName(), inputStream);
//            requestBody.add("File", multipartFile.getResource());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        // 封装所有参数
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, fileHeader());
        ResponseEntity<String> entity =
                noBalanceRestTemplateRnrFpT1.exchange(url,HttpMethod.POST, requestEntity, String.class);
        log.info("uploadT1File url: {},response: {},cost: {} ms", url, entity.getBody(),
                System.currentTimeMillis() - startTime);
        T1CommonResponseDTO result = JSON.parseObject(entity.getBody(), T1CommonResponseDTO.class);

        return result;
    }

    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }
        /**
         * Description: 证件类型转换
         * <br />
         * CreateDate 2022-06-08 17:20:28
         *
         * @author yuyi
         **/
    private String certTypeTransform(String certType) {
        //居民身份证
        if (CertTypeEnum.IDCARD.getCode().equals(certType)) {
            return "A";
        }
        //户口簿
        if (CertTypeEnum.RESIDENCE.getCode().equals(certType)) {
            return "B";
        }
        //军官证 -中国人民解放军军人身份证件
        if (CertTypeEnum.PLA.getCode().equals(certType)) {
            return "C";
        }
        //警官证
        if (CertTypeEnum.POLICEPAPER.getCode().equals(certType)) {
            return "D";
        }
        //港澳居民来往内地通行证
        if (CertTypeEnum.HKIDCARD.getCode().equals(certType)) {
            return "E";
        }
        //台湾居民来往大陆通行证
        if (CertTypeEnum.TAIBAOZHENG.getCode().equals(certType)) {
            return "F";
        }
        //外国公民护照
        if (CertTypeEnum.PASSPORT.getCode().equals(certType)) {
            return "G";
        }

        //营业执照
        if (CertTypeEnum.BUSINESS_LICENSE_NO.getCode().equals(certType)) {
            return "I";
        }
        //统一社会信用代码
        if (CertTypeEnum.UNITCREDITCODE.getCode().equals(certType)) {
            return "K";
        }
        //港澳居民居住证
        if (CertTypeEnum.HKRESIDENCECARD.getCode().equals(certType)) {
            return "S";
        }
        //港澳居民居住证
        if (CertTypeEnum.TWRESIDENCECARD.getCode().equals(certType)) {
            return "T";
        }
        if (CertTypeEnum.OTHER.getCode().equals(certType)) {
            return "O";
        }
        return "N";
    }

    @Override
    public  T1AuthDTO getAuth(EncryptionKeyDTO encryptionKeyDTO) {
        final T1AuthDTO t1AuthDTO = new T1AuthDTO();
        t1AuthDTO.setPlatformID(encryptionKeyDTO.getPlatFormId());

        //平台标识+密码的SM3值，密码由 OneLink车联卡实名平台分配
        String signNature = RnrDataSM3Utils.encode(encryptionKeyDTO.getPlatFormId() + encryptionKeyDTO.getCmccApiKey());

        t1AuthDTO.setSignNature(signNature);
        return t1AuthDTO;
    }
}
