package com.friday.custody.service.tenantService.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.friday.custody.api.dto.gjdf.GjdfAppSecretDto;
import com.friday.custody.common.CustodyContants;
import com.friday.custody.dto.*;
import com.friday.custody.entity.TenantEmailAuthorizationInfoEntity;
import com.friday.custody.entity.TenantEscrowAuthorizationInfoEntity;
import com.friday.custody.enums.DaasTrustNoEnum;
import com.friday.custody.enums.EmailConfigPurposeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.service.basicService.TenantEmailAuthorizationInfoService;
import com.friday.custody.service.basicService.impl.TenantEscrowAuthorizationInfoServiceImpl;
import com.friday.custody.service.basicService.impl.TenantInfoServiceImpl;
import com.friday.base.common.response.DubboResult;
import com.friday.custody.service.logicService.LogicInternalService;
import com.friday.operation.api.custody.dto.*;
import com.friday.operation.api.custody.vo.*;
import com.friday.operation.api.custody.service.ITrustAuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

import static com.friday.custody.common.CustodyContants.AUTHORIZATION_API;
import static com.friday.base.common.response.DubboResult.CLIENT_EXCEPTION;
import static com.friday.base.common.response.DubboResult.SERVER_EXCEPTION;
import static java.time.LocalDateTime.now;

@Slf4j
@Service("trustAuthorization")
public class TrustAuthorizationServiceImpl implements ITrustAuthorizationService {

    @Autowired
    private TenantInfoServiceImpl tenantInfoService;
    @Autowired
    private TenantEscrowAuthorizationInfoServiceImpl tenantEscrowAuthorizationInfoService;
    @Autowired
    private TenantEmailAuthorizationInfoService tenantEmailAuthorizationInfoService;
    @Autowired
    private LogicInternalService logicInternalService;

    @Resource(name = "initTenantDataThreadPool")
    private ExecutorService initTenantDataThreadPool;


    @Value(value = "${file.parentPath.realPath}")
    private String realPath;
    @Value(value = "${file.parentPath.AuthorizationFile}")
    private String AuthorizationFile;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public DubboResult editAuthorizationInfo(AuthorizationDTO authorizationDTO) {
        String admin = authorizationDTO.getAdmin();
        String trustNo = authorizationDTO.getTrustNo();
        Map<String, String> authorizationMap = authorizationDTO.getAuthorizationMap();
        List<AuthorizationEmailDTO> authorizationEmailList = authorizationDTO.getAuthorizationEmailList();
        if (StringUtils.isBlank(admin)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "管理人不能为空！");
        }
        if (StringUtils.isBlank(trustNo)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "托管编码不能为空！");
        }
        // 邮件和api都为空
        if (ObjectUtil.isEmpty(authorizationMap) && CollectionUtils.isEmpty(authorizationEmailList)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "账密信息不能为空！");
        }
        // 校验邮件参数
        if (CollectionUtils.isNotEmpty(authorizationEmailList)) {
            String checkResult = this.checkMailConfig(authorizationEmailList);
            if (StringUtils.isNotBlank(checkResult)) {
                return DubboResult.newFailure(CLIENT_EXCEPTION, checkResult);
            }
        }
        //判断当前租户是否已添加, 如没有则新加租户
        boolean existsTenant = tenantInfoService.isExistsTenant(authorizationDTO.getAdmin());
        //如果不存在 则新增租户
        if (!existsTenant){
            int i = tenantInfoService.addTenantInfo(authorizationDTO.getAdmin());
            if (i == 0){
                return DubboResult.newFailure(SERVER_EXCEPTION, "编辑托管配置信息失败！请联系系统管理人");
            }
        }
        TenantEscrowAuthorizationInfoEntity authorizationInfo;
        boolean isApi = ObjectUtil.isNotEmpty(authorizationMap);
        try {
            authorizationInfo = handleAuthorizationByTrustNo(authorizationDTO, isApi);
        }catch (RRException e){
            log.error("Processing data failed!", e);
            return DubboResult.newFailure(e.getCode(), e.getMessage());
        } catch (IOException e) {
            log.error("Save File failed!", e);
            return DubboResult.newFailure(SERVER_EXCEPTION, "上传授权文件失败!");
        }
        boolean flag;
        boolean isCreate = tenantEscrowAuthorizationInfoService.isExistAuthorization(authorizationDTO.getTrustNo(), authorizationDTO.getAdmin());
        if(isCreate){
            authorizationInfo.setCreateTime(new Date());
            authorizationInfo.setUpdateTime(new Date());
            flag = tenantEscrowAuthorizationInfoService.save(authorizationInfo);
        } else {
            authorizationInfo.setUpdateTime(new Date());
            flag = tenantEscrowAuthorizationInfoService.updateByTenant(authorizationInfo);
        }
        if (!flag) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "编辑托管授权信息失败！");
        }
        //如果成功 则调用初始化数据接口
        if (isApi) {
            CompletableFuture.supplyAsync(() -> {
                System.out.println("开始初始化数据!");
                tenantEscrowAuthorizationInfoService.initData(Arrays.asList(authorizationInfo));
                return null;
            }, initTenantDataThreadPool);
        }
        // 邮件配置
        if (CollectionUtils.isEmpty(authorizationEmailList)) {
            return DubboResult.newSuccess();
        }
        // 查询当前托管人是否配置过相对应的，这里顶多两条，不做批量添加或更新了
        for (AuthorizationEmailDTO emailDTO : authorizationEmailList) {
            TenantEmailAuthorizationInfoEntity emailInfoEntity = tenantEmailAuthorizationInfoService.getOne(Wrappers.lambdaQuery(TenantEmailAuthorizationInfoEntity.class)
                    .eq(TenantEmailAuthorizationInfoEntity::getTenantName, authorizationInfo.getTenantName())
                    .eq(TenantEmailAuthorizationInfoEntity::getTrustNo, authorizationInfo.getTrustNo())
                    .eq(TenantEmailAuthorizationInfoEntity::getPurpose, emailDTO.getPurpose())
                    .eq(TenantEmailAuthorizationInfoEntity::getIsDeleted, 0)
                    .last("limit 1")
            );
            if (emailInfoEntity != null) {
                emailInfoEntity.setEmailAgreement(emailDTO.getEmailAgreement());
                emailInfoEntity.setEmailHost(emailDTO.getEmailHost());
                emailInfoEntity.setEmailServerPort(emailDTO.getEmailServerPort());
                emailInfoEntity.setEmailAddress(emailDTO.getEmailAddress());
                emailInfoEntity.setEmailSecret(emailDTO.getEmailSecret());
                emailInfoEntity.setFromEmail(emailDTO.getFromEmail());
                emailInfoEntity.setEmailSubject(emailDTO.getEmailSubject());
                emailInfoEntity.setDirFilePath(emailDTO.getDirFilePath());
                emailInfoEntity.setAttachKey(emailDTO.getAttachKey());
                emailInfoEntity.setUpdateTime(new Date());
                tenantEmailAuthorizationInfoService.updateById(emailInfoEntity);
            } else {
                tenantEmailAuthorizationInfoService.save(TenantEmailAuthorizationInfoEntity.builder()
                        .tenantName(authorizationInfo.getTenantName())
                        .contactPerson(authorizationInfo.getContactPerson())
                        .emailAgreement(emailDTO.getEmailAgreement())
                        .emailHost(emailDTO.getEmailHost())
                        .emailServerPort(emailDTO.getEmailServerPort())
                        .emailAddress(emailDTO.getEmailAddress())
                        .emailSecret(emailDTO.getEmailSecret())
                        .fromEmail(emailDTO.getFromEmail())
                        .emailSubject(emailDTO.getEmailSubject())
                        .dirFilePath(emailDTO.getDirFilePath())
                        .purpose(emailDTO.getPurpose())
                        .trustNo(authorizationInfo.getTrustNo())
                        .attachKey(emailDTO.getAttachKey())
                        .creatTime(new Date())
                        .updateTime(new Date())
                        .build());
            }
        }
        CompletableFuture.supplyAsync(() -> {
            log.info("开始初始化解析邮箱操作!");
            // 调起邮件解析
            logicInternalService.initByMail("", authorizationInfo.getTenantName(), authorizationInfo.getTrustNo(), authorizationInfo.getAppKey(), "init");
            return null;
        }, initTenantDataThreadPool);
        return DubboResult.newSuccess();
    }

    /**
     * 校验邮件配置必传参数
     * @param authorizationEmailList
     * @return
     */
    private String checkMailConfig(List<AuthorizationEmailDTO> authorizationEmailList) {
        for (AuthorizationEmailDTO emailDTO : authorizationEmailList) {
            if (StringUtils.isBlank(emailDTO.getEmailAgreement())) {
                return "邮件接受协议为空！";
            }
            if (StringUtils.isBlank(emailDTO.getEmailHost())) {
                return "邮件服务器为空！";
            }
            if (StringUtils.isBlank(emailDTO.getEmailServerPort())) {
                return "邮件服务器端口为空！";
            }
            if (StringUtils.isBlank(emailDTO.getEmailAddress())) {
                return "邮件账号为空！";
            }
            if (StringUtils.isBlank(emailDTO.getEmailSecret())) {
                return "邮件密码为空！";
            }
            if (StringUtils.isBlank(emailDTO.getFromEmail())) {
                return "邮件发件人为空！";
            }
            if (StringUtils.isBlank(emailDTO.getEmailSubject())) {
                return "邮件主题为空！";
            }
            if (StringUtils.isBlank(emailDTO.getPurpose()) || Arrays.stream((EmailConfigPurposeEnum.values())).noneMatch(purposeEnum -> purposeEnum.getPurpose().equals(emailDTO.getPurpose()))) {
                return "邮件配置解析类型为空或有误！";
            }
            if (StringUtils.isBlank(emailDTO.getAttachKey())) {
                return "附件关键字为空！";
            }
        }
        return "";
    }


    /**
     * @param bytes byte数组
     * @param fileRoute 文件路径
     * @param fileName 文件名
     */
    public void saveFile(byte[] bytes,String fileRoute,String fileName) throws IOException {
        BufferedOutputStream bos = null;
        try {
            File directory=new File(fileRoute);
            if (!directory.exists()){
                if(!directory.mkdirs()){
                    log.error("创建授权文件目标文件夹失败：{}",fileRoute);
                    throw new RRException(SERVER_EXCEPTION,"保存授权文件失败！");
                }
            }
            //删除当前文件下已存在的文件
            List<String> fileNameList = FileUtil.listFileNames(fileRoute);
            if (ObjectUtil.isNotEmpty(fileNameList)) {
                for (String name : fileNameList) {
                    File existsFile = new File(directory, name);
                    existsFile.delete();
                }
            }
            File file = new File(directory, fileName);
            //如果文件已存在，则删除
            if (file.exists()) {
                file.delete();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(bytes);

        } catch (IOException e) {
            log.error("上传授权文件失败！", e);
        } finally {
            if (bos != null) bos.close();
        }
    }

    /**
     * 转换entity
     * @param authorizationDTO
     * @param isApi 当前配置是否为api配置
     * @return
     * @throws IOException
     */
    private TenantEscrowAuthorizationInfoEntity handleAuthorizationByTrustNo(AuthorizationDTO authorizationDTO, boolean isApi) throws IOException {
        TenantEscrowAuthorizationInfoEntity entity = new TenantEscrowAuthorizationInfoEntity();
        String trustNo = authorizationDTO.getTrustNo();
        String admin = authorizationDTO.getAdmin();
        String filePath = realPath + AuthorizationFile + "/" + authorizationDTO.getAdmin() + "/" + authorizationDTO.getTrustNo() + "/" + authorizationDTO.getAdmin() + "/";
//        String filePath = "D:\\Soft\\custody\\AuthorizationFile" + "/" + authorizationDTO.getAdmin() + "/" + authorizationDTO.getTrustNo() + "/" + authorizationDTO.getAdmin() + "/";
        entity.setTrustNo(trustNo);
        entity.setTenantName(admin);
        entity.setContactPerson(admin);
        if (!isApi) {
            log.info("当前配置是邮件配置");
            entity.setAppKey(admin);
            entity.setVersion(CustodyContants.AUTHORIZATION_EMAIL);
            return entity;
        }
        Map<String, String> authorizationMap = authorizationDTO.getAuthorizationMap();
        AuthorizationFileDTO fileDTO = authorizationDTO.getAuthorizationFileDTO();
        DaasTrustNoEnum trustNoEnum = DaasTrustNoEnum.fromCode(trustNo);
        switch (trustNoEnum){
            case HTSC : //华泰证券
                HtscAppSecretDTO htscAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, HtscAppSecretDTO.class, false);
                if (ObjectUtil.isEmpty(htscAppSecretDTO.getAppId()) ){
                    throw new RRException(CLIENT_EXCEPTION, "管理人编号不能为空！");
                }
                if(ObjectUtil.isEmpty(htscAppSecretDTO.getAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "密钥不能为空！");
                }
                entity.setAppKey(htscAppSecretDTO.getAppId());
                entity.setAppSecret(JSONUtil.toJsonStr(htscAppSecretDTO));
                break;
            case CMSC: //招商证券
                CmscAppSecretDTO cmscDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, CmscAppSecretDTO.class, false);
                if (StringUtils.isBlank(cmscDTO.getUapUserNo())){
                    throw new RRException(CLIENT_EXCEPTION, "用户编号不能为空！");
                }
                if(StringUtils.isBlank(cmscDTO.getCompanyId())){
                    throw new RRException(CLIENT_EXCEPTION, "管理人ID编号不能为空！");
                }
                if(StringUtils.isBlank(cmscDTO.getUapServerType())){
                    throw new RRException(CLIENT_EXCEPTION, "服务类型不能为空！");
                }
                if(StringUtils.isBlank(cmscDTO.getUapLicenceKey())){
                    throw new RRException(CLIENT_EXCEPTION, "接口许可号不能为空！");
                }
                if(StringUtils.isBlank(cmscDTO.getUnzipCode())){
                    throw new RRException(CLIENT_EXCEPTION, "解压密码不能为空！");
                }
                if(ObjectUtil.isEmpty(fileDTO)){
                    throw new RRException(CLIENT_EXCEPTION, "请上传文件及相关信息！");
                }
                if(StringUtils.isBlank(fileDTO.getFileName())){
                    throw new RRException(CLIENT_EXCEPTION, "授权文件名不能为空！");
                }
                if(ObjectUtil.isEmpty(fileDTO.getFile())){
                    throw new RRException(CLIENT_EXCEPTION, "请上传授权文件！");
                }
                entity.setAppKey(cmscDTO.getUapUserNo());
                cmscDTO.setPxfFilePath(fileDTO.getFileName());
                //20181212000001
                String date = DateUtil.format(now(), "yyyyMMddHHmmss");
                String random = String.valueOf(RandomUtil.randomInt(10, 99));
                String uapRequestId = date + random;
                cmscDTO.setUapRequestId(uapRequestId);
                entity.setAppSecret(JSONUtil.toJsonStr(cmscDTO));
                entity.setFilePath(filePath);
                entity.setCompanyId(cmscDTO.getCompanyId());//招商必须设置companyId
                break;
            case HAI_TONG:// 海通证券
                HaitongAppSecretDTO haitongDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, HaitongAppSecretDTO.class, false);
                if(StringUtils.isBlank(haitongDTO.getClientId())){
                    throw new RRException(CLIENT_EXCEPTION, "管理人ID编号不能为空！");
                }
                if(StringUtils.isBlank(haitongDTO.getLicense())){
                    throw new RRException(CLIENT_EXCEPTION, "营业执照不能为空！");
                }
                if(StringUtils.isBlank(haitongDTO.getAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "密钥不能为空！");
                }
                if(StringUtils.isBlank(haitongDTO.getPrivateKey())){
                    throw new RRException(CLIENT_EXCEPTION, "私钥不能为空！");
                }
                if(StringUtils.isBlank(haitongDTO.getPublicKey())){
                throw new RRException(CLIENT_EXCEPTION, "公钥不能为空！");
               }
                entity.setAppKey(haitongDTO.getClientId());
                entity.setAppSecret(JSONUtil.toJsonStr(haitongDTO));
                break;
            case ZHONG_XIN://中信证券
                ZhongxinAppSecretDTO zhongxinDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, ZhongxinAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(zhongxinDTO.getConsumerAuth()) ){
                    throw new RRException(CLIENT_EXCEPTION, "生产口令不能为空！");
                }
                entity.setAppKey(admin);
                entity.setAppSecret(JSONUtil.toJsonStr(zhongxinDTO));
                break;
            case GUO_TAI_JUN_AN://国泰君安
                GtjaAppSecretDTO gtjaDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, GtjaAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(gtjaDTO.getAppKey())){
                    throw new RRException(CLIENT_EXCEPTION, "账号不能为空！");
                }
                if(ObjectUtil.isEmpty(gtjaDTO.getAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "密码不能为空！");
                }
                if(ObjectUtil.isEmpty(gtjaDTO.getManagerId())){
                    throw new RRException(CLIENT_EXCEPTION, "管理人代码不能为空！");
                }

                entity.setAppKey(gtjaDTO.getAppKey());
                entity.setAppSecret(JSONUtil.toJsonStr(gtjaDTO));
                break;
            case XING_YE_SECURITIES://兴业证券
                XyAppSecretDTO xyDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, XyAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(xyDTO.getClientId())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端编号不能为空！");
                }
                if(ObjectUtil.isEmpty(xyDTO.getClientSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端密码不能为空！");
                }
                if(ObjectUtil.isEmpty(xyDTO.getUsername())){
                    throw new RRException(CLIENT_EXCEPTION, "用户名不能为空！");
                }
                if(ObjectUtil.isEmpty(xyDTO.getPassword())){
                    throw new RRException(CLIENT_EXCEPTION, "用户名密码不能为空！");
                }
                if(ObjectUtil.isEmpty(xyDTO.getResponseType())){
                    throw new RRException(CLIENT_EXCEPTION, "授权类型不能为空！");
                }
                entity.setAppKey(xyDTO.getClientId());
                entity.setAppSecret(JSONUtil.toJsonStr(xyDTO));
                break;
            case CSCS://中信建投
                CscAppSecretDTO cscAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, CscAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(cscAppSecretDTO.getApiKey())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端账号不能为空！");
                }
                if(ObjectUtil.isEmpty(cscAppSecretDTO.getApiSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端密码不能为空！");
                }
                if(ObjectUtil.isEmpty(cscAppSecretDTO.getEncryptKey())){
                    throw new RRException(CLIENT_EXCEPTION, "密钥不能为空！");
                }
                entity.setAppKey(cscAppSecretDTO.getApiKey());
                entity.setAppSecret(JSONUtil.toJsonStr(cscAppSecretDTO));
                break;
            case GUOSEN://国信
                GuosenAppSecretDTO guosenAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, GuosenAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(guosenAppSecretDTO.getAppId())) {
                    throw new RRException(CLIENT_EXCEPTION, "接口开通的appId不能为空！");
                }
                if(ObjectUtil.isEmpty(guosenAppSecretDTO.getAppSecret())) {
                    throw new RRException(CLIENT_EXCEPTION, "密钥不能为空！");
                }
                if(ObjectUtil.isEmpty(guosenAppSecretDTO.getManagerCode())) {
                    throw new RRException(CLIENT_EXCEPTION, "管理人编码不能为空！");
                }
                entity.setAppKey(guosenAppSecretDTO.getAppId());
                entity.setAppSecret(JSONUtil.toJsonStr(guosenAppSecretDTO));
                entity.setCompanyId(guosenAppSecretDTO.getManagerCode());
                break;
            case GUANG_FA_SECURITIES:
                GFAppSecretDTO gfAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, GFAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(gfAppSecretDTO.getAppKey())){
                    throw new RRException(CLIENT_EXCEPTION, "验证密钥不能为空！");
                }
                if(ObjectUtil.isEmpty(gfAppSecretDTO.getUserId())){
                    throw new RRException(CLIENT_EXCEPTION, "用户id不能为空！");
                }
                entity.setAppKey(gfAppSecretDTO.getAppKey());
                entity.setAppSecret(JSONUtil.toJsonStr(gfAppSecretDTO));
                break;
            case SW: //申万宏源
                SWAppSecretDTO swAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, SWAppSecretDTO.class, false);
                if (ObjectUtil.isEmpty(swAppSecretDTO.getManagerId())){
                    throw new RRException(CLIENT_EXCEPTION, "管理人编码不能为空！");
                }
                if (ObjectUtil.isEmpty(swAppSecretDTO.getAesAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "密钥不能为空！");
                }
                if (ObjectUtil.isEmpty(swAppSecretDTO.getHmacAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "数字签名不能为空！");
                }
                entity.setAppKey(swAppSecretDTO.getManagerId());
                entity.setAppSecret(JSONUtil.toJsonStr(swAppSecretDTO));
                break;
            case EBSCN :
                EbscnAppSecretDTO ebscnAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, EbscnAppSecretDTO.class, false);
                if (ObjectUtil.isEmpty(ebscnAppSecretDTO.getAppKey())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端id不能为空！");
                }
                if (ObjectUtil.isEmpty(ebscnAppSecretDTO.getAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端密钥不能为空！");
                }
                if (ObjectUtil.isEmpty(ebscnAppSecretDTO.getUsername())){
                    throw new RRException(CLIENT_EXCEPTION, "用户名不能为空！");
                }
                if (ObjectUtil.isEmpty(ebscnAppSecretDTO.getPassword())){
                    throw new RRException(CLIENT_EXCEPTION, "密码不能为空！");
                }
                if(ObjectUtil.isEmpty(fileDTO)){
                    throw new RRException(CLIENT_EXCEPTION, "请上传文件及相关信息！");
                }
                if(StringUtils.isBlank(fileDTO.getFileName())){
                    throw new RRException(CLIENT_EXCEPTION, "授权文件名不能为空！");
                }
                if(ObjectUtil.isEmpty(fileDTO.getFile())){
                    throw new RRException(CLIENT_EXCEPTION, "请上传授权文件！");
                }
                entity.setAppKey(ebscnAppSecretDTO.getAppKey());
                ebscnAppSecretDTO.setCerFilePath(fileDTO.getFileName());
                entity.setAppSecret(JSONUtil.toJsonStr(ebscnAppSecretDTO));
                entity.setFilePath(filePath);
                break;
            case YINHE:
                YinheAppSecretDTO yinheAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, YinheAppSecretDTO.class, false);
                if (ObjectUtil.isEmpty(yinheAppSecretDTO.getAppId())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端id不能为空！");
                }
                if (ObjectUtil.isEmpty(yinheAppSecretDTO.getAppKey())){
                    throw new RRException(CLIENT_EXCEPTION, "客户端密钥不能为空！");
                }
                if (ObjectUtil.isEmpty(yinheAppSecretDTO.getServiceName())){
                    throw new RRException(CLIENT_EXCEPTION, "服务名不能为空！");
                }
                if (ObjectUtil.isEmpty(yinheAppSecretDTO.getSecKey())){
                    throw new RRException(CLIENT_EXCEPTION, " 加密的密钥不能为空！");
                }
                entity.setAppKey(yinheAppSecretDTO.getAppKey());
                entity.setAppSecret(JSONUtil.toJsonStr(yinheAppSecretDTO));
                break;
            case ANXIN: //安信
                AnxinAppSecretDTO anxinAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, AnxinAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(anxinAppSecretDTO.getAppKey())){
                    throw new RRException(CLIENT_EXCEPTION, "用户id不能为空!");
                }
                if(ObjectUtil.isEmpty(anxinAppSecretDTO.getAppSecret())){
                    throw new RRException(CLIENT_EXCEPTION, "应用加密密钥不能为空!");
                }
                entity.setAppKey(anxinAppSecretDTO.getAppKey());
                entity.setAppSecret(JSONUtil.toJsonStr(anxinAppSecretDTO));
                break;
            case ZHONGTAI:
                ZhongtaiAppSecretDTO zhongtaiAppSecretDTO = BeanUtil.toBeanIgnoreCase(authorizationMap, ZhongtaiAppSecretDTO.class, false);
                if(ObjectUtil.isEmpty(zhongtaiAppSecretDTO.getAppId()) ){
                    throw new RRException(CLIENT_EXCEPTION, "用户唯一标识不能为空！");
                }
                if(ObjectUtil.isEmpty(zhongtaiAppSecretDTO.getAppKey()) ){
                    throw new RRException(CLIENT_EXCEPTION, "用户密钥appKey不能为空！");
                }
                if(ObjectUtil.isEmpty(zhongtaiAppSecretDTO.getAppSecret()) ){
                    throw new RRException(CLIENT_EXCEPTION, "用户密钥appSecret不能为空！");
                }
                entity.setAppKey(zhongtaiAppSecretDTO.getAppKey());
                entity.setAppSecret(JSONUtil.toJsonStr(zhongtaiAppSecretDTO));
                break;
            case GUOJIN: //国金道富
                GjdfAppSecretDto gjdfAppSecreDto = BeanUtil.toBeanIgnoreCase(authorizationMap, GjdfAppSecretDto.class, false);
                if (ObjectUtil.isEmpty(gjdfAppSecreDto.getOperateCode()) ){
                    throw new RRException(CLIENT_EXCEPTION, "账号不能为空！");
                }
                if(ObjectUtil.isEmpty(gjdfAppSecreDto.getPassword())){
                    throw new RRException(CLIENT_EXCEPTION, "密码不能为空！");
                }
                entity.setAppKey(gjdfAppSecreDto.getOperateCode());
                entity.setAppSecret(JSONUtil.toJsonStr(gjdfAppSecreDto));
                break;
            default:
                throw new IllegalStateException("Unexpected trustNo value: " + trustNo);
        }
        if (ObjectUtil.isNotEmpty(fileDTO)){
            if(ObjectUtil.isNotEmpty(fileDTO.getFile()) && ObjectUtil.isNotEmpty(fileDTO.getFileName())) {
                saveFile(fileDTO.getFile(), entity.getFilePath(), fileDTO.getFileName());
            }
        }
        return entity;
    }


    @Override
    public DubboResult deleteAuthorizationInfo(AuthorizationDeleteDTO deleteDTO) {
        String admin = deleteDTO.getAdmin();
        String trustNo = deleteDTO.getTrustNo();
        if (StringUtils.isBlank(admin)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "管理人不能为空！");
        }
        if (StringUtils.isBlank(trustNo)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "托管编码不能为空！");
        }
        int delete = tenantEscrowAuthorizationInfoService.deleteByTrust(admin, trustNo);
        if (delete != 0) {
            return DubboResult.newSuccess();
        }
        return DubboResult.newFailure(CLIENT_EXCEPTION, "删除托管配置信息失败！");
    }

    @Override
    public DubboResult<ArrayList<TrustAuthorizationVO>> queryAuthorizationInfo(AuthorizationQueryDTO queryDTO) {
        String admin = queryDTO.getAdmin();
        String trustNo = queryDTO.getTrustNo();
        if (StringUtils.isBlank(admin)) {
            return DubboResult.newFailure(CLIENT_EXCEPTION, "管理人不能为空！");
        }
        List<TenantEscrowAuthorizationInfoEntity> entityList = tenantEscrowAuthorizationInfoService.queryData(trustNo, admin, AUTHORIZATION_API);
        ArrayList<TrustAuthorizationVO> vos = convertData(entityList);
        return DubboResult.newSuccess(vos);
    }

    private ArrayList<TrustAuthorizationVO> convertData(List<TenantEscrowAuthorizationInfoEntity> entityList) {
        ArrayList<TrustAuthorizationVO> vos = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(entityList)) {
            // 查询所有邮件配置
            List<AuthorizationEmailVO> emailDTOList = tenantEmailAuthorizationInfoService.selectAllEmailConfigList();
            for (TenantEscrowAuthorizationInfoEntity entity : entityList) {
                String trustNo = entity.getTrustNo();
                TrustAuthorizationVO vo = new TrustAuthorizationVO();
                String appSecret = entity.getAppSecret();
                vo.setAdmin(entity.getTenantName());
                vo.setTrustNo(trustNo);
                vo.setAuthorizationInfo(JSONObject.parse(appSecret));
                // 筛选当前托管符合的邮件配置
                if (CollectionUtils.isNotEmpty(emailDTOList)) {
                    List<AuthorizationEmailVO> emailVOList = emailDTOList.stream().filter(email -> vo.getTrustNo().equals(email.getTrustNo()) && vo.getAdmin().equals(email.getTenantName())).collect(Collectors.toList());
                    vo.setAuthorizationEmailList(emailVOList);
                }
                vos.add(vo);
            }
        }
        return vos;
    }
}
