package com.trade.service.contract.util;

import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.service.contract.dto.ContractSignInfo;
import com.trade.service.contract.dto.ContractSigner;
import com.trade.service.contract.service.SignAccountCreator;
import com.trade.service.contract.util.esign.ESignConstant;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SignPubUtil {

    /**
     * 根据签署入参，获取签署账号信息
     * 
     * @param signInfoList 签署信息列表
     * @param accountCreator 账号创建器
     * @return 签署账号信息Map
     */
    public static Map<String, String> getAccountMapFromSignInfo(List<ContractSignInfo> signInfoList,
            SignAccountCreator accountCreator) {
        Map<String, String> resultMap = new HashMap<>();
        signInfoList.forEach(signInfo -> {
            // 单方签署
            ContractSigner signer = signInfo.getSingleSigner();
            if (null != signer) {
                resultMap.put(signer.getSignerIdNo(), accountCreator.creatPersonalAccount(signer));
            }
            signInfo.getSealInfoList().forEach(sealInfo -> {
                if (null == sealInfo.getSigner()) {
                    if (null == signer) {
                        throw new ServiceException("签署信息中的签署人和签章信息中的签署人不能同时为空", HttpStatus.BAD_REQUEST);
                    }
                    sealInfo.setSigner(signer);
                } else {
                    resultMap.getOrDefault(sealInfo.getSigner().getSignerIdNo(),
                            accountCreator.creatPersonalAccount(sealInfo.getSigner()));
                }
                // 若存在企业签章，则需创建企业账号
                if (ESignConstant.CRED_ORG_USCC.equals(sealInfo.getSealIdType())
                        || ESignConstant.CRED_ORG_UNKNOWN.equals(sealInfo.getSealIdType())) {
                    resultMap.getOrDefault(sealInfo.getSealIdNo(), accountCreator.createOrgAccount(sealInfo));
                }
            });
        });
        return resultMap;
    }

    /**
     * 删除pdf（若采用本地存储方式则无需此步操作）
     *
     * @param file file
     */
    public static void deleteFile(File file) {
        try {
            file.delete();// 删除本地文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
