package com.mmc.iuav.user.service.fdd.impl;

import com.alibaba.fastjson.JSONObject;
import com.fadada.sdk.base.client.FddBaseClient;
import com.fadada.sdk.base.model.req.DownloadPdfParams;
import com.fadada.sdk.base.model.req.ExtSignParams;
import com.fadada.sdk.base.model.req.UploadDocsParams;
import com.fadada.sdk.base.model.req.ViewPdfURLParams;
import com.fadada.sdk.utils.crypt.FddEncryptTool;
import com.mmc.iuav.general.CodeUtil;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.constant.fdd.FddConnectConstant;
import com.mmc.iuav.user.constant.fdd.FddConstant;
import com.mmc.iuav.user.dao.fdd.ContractDao;
import com.mmc.iuav.user.entity.fdd.ContractInfoDO;
import com.mmc.iuav.user.entity.fdd.UserFddDO;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import com.mmc.iuav.user.model.fdd.vo.ContractVO;
import com.mmc.iuav.user.service.fdd.ContractService;
import com.mmc.iuav.user.service.fdd.SealManageService;
import com.mmc.iuav.user.util.TDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

/**
 * @Author LW
 * @date 2022/9/5 14:38
 * 概要：
 */
@Service
@Slf4j
public class ContractServiceImpl implements ContractService {
    @Resource
    ContractDao contractDao;
    @Resource
    SealManageService sealManageService;

    /**
     * 上传合同
     *
     * @param param
     * @return
     */
    @Override
    public ResultBody uploadContract(ContractVO param, LoginSuccessDTO loginSuccessDTO) {
        ResultBody resultBody = sealManageService.checkAuthStatus(param.getPort(), loginSuccessDTO);
        UserFddDO userFddDO = (UserFddDO) resultBody.getResult();
        FddBaseClient baseClient = new FddBaseClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        // 查询这个订单号之前有没有上传过合同有的话就删除
        ContractInfoDO contractInfoDO = contractDao.contractInfoByOrderNo(param.getOrderNo(), null);
        if (contractInfoDO != null) {
            // 把合同删除
            contractDao.deleteContractInfo(param.getOrderNo());
        }
        //自定义合同id 合同编号设置规则：YXF + 年份 + 8位随机数
        String contractId = FddConstant.YXF + TDateUtil.getCurrentYear() + CodeUtil.getRandomNum(8);
        // 调用法大大接口
        UploadDocsParams params = new UploadDocsParams();
        // 合同编号
        params.setContractId(contractId);
        //合同标题
        params.setDocTitle(param.getTitle());
        //PDF文档和下载地址二选一
        //合同公网下载地址
        params.setDocUrl(param.getDocUrl());
        //合同类型 目前仅支持pdf格式
        params.setDocType(".pdf");
        String result = baseClient.invokeUploadDocs(params);
        String code = JSONObject.parseObject(result).getString(FddConstant.CODE);
        String msg = JSONObject.parseObject(result).getString(FddConstant.MSG);
        if (FddConstant.SUCCESS_CODE.equals(code)) {
            // 保存合同信息到数据库
            ContractInfoDO contractInfo = new ContractInfoDO();
            contractInfo.setContractTitle(param.getTitle());
            contractInfo.setOrderNo(param.getOrderNo());
            contractInfo.setContractNo(contractId);
            contractInfo.setUnionId(userFddDO.getUnionId());
            contractDao.insertUavContractInfo(contractInfo);
            return ResultBody.success(contractInfo);
        } else {
            return ResultBody.error(msg);
        }
    }

    @Override
    public ResultBody viewContract(String contractId) {
        FddBaseClient baseClient = new FddBaseClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        ViewPdfURLParams params = new ViewPdfURLParams();
        //此处传入调用上传或填充合同接口成功时定义的合同编号
        params.setContractId(contractId);
        String result = baseClient.invokeViewPdfURL(params);
        String base64 = new String(FddEncryptTool.Base64Encode(result.getBytes())).trim();
        return ResultBody.success(base64);
    }

    @Override
    public ResultBody downloadContract(String contractId) {
        FddBaseClient baseClient = new FddBaseClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        DownloadPdfParams params = new DownloadPdfParams();
        // 合同编号
        params.setContractId(contractId);
        //如下，传setPath参数可以直接保存文件到本地，不传则返回url
//        params.setPath(""); // 指定路径，如：D:\\pdf\\uuidNew.pdf
        String result = baseClient.invokeDownloadPdf(params);
        String base64 = new String(FddEncryptTool.Base64Encode(result.getBytes())).trim();
        return ResultBody.success(base64);
    }


    @Override
    public ResultBody stamp(String contractId, LoginSuccessDTO loginSuccessDTO, String pages, Integer port) {
        ResultBody resultBody = sealManageService.checkAuthStatus(port, loginSuccessDTO);
        UserFddDO userFddDO = (UserFddDO) resultBody.getResult();
        // 获取合同信息
        ContractInfoDO contractInfo = contractDao.contractInfoByOrderNo(null, contractId);
        FddBaseClient baseClient = new FddBaseClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        ExtSignParams params = new ExtSignParams();
        String transactionId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        //平台自定义唯一交易号
        params.setTransactionId(transactionId);
        //此处传入调用上传或填充合同接口成功时定义的合同编号
        params.setContractId(contractId);
        params.setCustomerId(userFddDO.getCustomerId());
        params.setDocTitle(contractInfo.getContractTitle());
        if (pages != null) {
            params.setOpenEnvironment("1");
            params.setReturnUrl(pages);
        } else {
            params.setOpenEnvironment("0");
        }
        params.setNotifyUrl(FddConnectConstant.MMC_URL + FddConstant.NOTIFY_STAMP);
        if (port.equals(0) && userFddDO.getAccountType().equals(1)) {
            params.setMobileSignType("2");
        }
        String result = baseClient.invokeExtSign(params);
        // 将链接转成base64返回
        String base64 = new String(FddEncryptTool.Base64Encode(result.getBytes())).trim();
        ContractInfoDO updateContract = new ContractInfoDO();
        updateContract.setContractNo(contractId);
        if (contractInfo.getUnionId().equals(userFddDO.getUnionId())) {
            updateContract.setATransactionId(transactionId);
        } else {
            updateContract.setBTransactionId(transactionId);
        }
        contractDao.updateContractInfo(updateContract);
        return ResultBody.success(base64);
    }

    @Override
    public ResultBody notifyStamp(Map<String, String> map) {
        log.info("合同签署异步回调返回数据，{}", map.toString());
        String transactionId = map.get("transaction_id");// 交易号
        String contractId = map.get("contract_id");// 合同编号
        String resultCode = map.get("result_code");// 返回的code码
        String resultDesc = map.get("result_desc");// 签章结果描述信息
        String timestamp = map.get("timestamp");// 时间戳
        String msgDigest = map.get("msg_digest");// 摘要
        String sha1 = FddEncryptTool.sha1(FddConnectConstant.APP_KEY + transactionId);
        try {
            String md5 = FddEncryptTool.md5Digest(timestamp);
            String outSha1 = FddEncryptTool.sha1(FddConnectConstant.APP_ID + md5 + sha1);
            String base64 = new String(FddEncryptTool.Base64Encode(outSha1.getBytes())).trim();
            if (!base64.equals(msgDigest)) {
                return ResultBody.error(ResultEnum.NOT_FOUND);
            }
        } catch (Exception e) {
            return ResultBody.error(ResultEnum.NOT_FOUND);
        }
        return ResultBody.success();
    }
}
