package com.jwipc.contract.logic.impl;

import cn.hutool.core.lang.Pair;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.constant.SignFlowStatus;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.interceptor.SignBackLogic;
import com.jwipc.constant.SignProcessType;
import com.jwipc.contract.entity.Contract;
import com.jwipc.contract.service.IContractService;
import com.jwipc.api.esign.SignUtils;
import com.jwipc.exception.DaoException;
import com.jwipc.log.annotation.ApiOperateLog;
import com.jwipc.log.constant.ApiDirection;
import com.jwipc.log.constant.ThirdSysType;
import com.jwipc.sys.client.FileClient;
import com.jwipc.sys.client.dto.FileResposeCDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/3/21 0021 16:18
 */
@RequiredArgsConstructor
@Service("signContractCallBack")
@Slf4j
public class SignContractCallBackImpl implements SignBackLogic {

    @Autowired
    IContractService contractService;
    @Autowired
    FileClient fileClient;

    @Value("${sys.esign.projectid}")
    private String projectid;

    @Value("${sys.esign.serverip}")
    private String serverip;

    @Value("${sys.esign.projectsecret}")
    private String projectsecret;

    @Override
    @ApiOperateLog(code = "signContractCallBack", name = "E签宝回传数据", direction = ApiDirection.OTHER_TO_SRM,
            thirdSysType = ThirdSysType.SIGN)
    public ApiResult processor(String processId, SignFlowStatus status, String businessNo, String signDownloadOuterUrl)
    {

        //0草稿，1签署中，2完成，3已过期，4已拒签，5已作废，6作废中
        Contract contract = contractService.getOne(
                new LambdaQueryWrapper<Contract>().eq(Contract::getSignFlowId, processId));
        if (Objects.isNull(contract)) {
            throw new DaoException("未找到匹配流程!");
        }
        contract.setSignFlowStatus(String.valueOf(status.getStatus()));
        // 已完成 下载文件
        if (status.getStatus() == SignFlowStatus.Completed.getStatus()) {
            final Pair<String, String> defaultFileAbsolutePath = fileClient.getDefaultFileAbsolutePath();
            String path = SignUtils.getFile(signDownloadOuterUrl, defaultFileAbsolutePath, serverip, "/file/v1/getDownloadUrl",
                    projectsecret, projectid);
            if (StringUtils.isNotEmpty(path)) {
                // 读取文件内容
                Path pathFile = Paths.get(path);
                final File file = pathFile.toFile();
                FileResposeCDTO fileResposeCDTO = fileClient.saveSignFile(file);
                if (!Objects.isNull(fileResposeCDTO)) {
                    contract.setSignFile(fileResposeCDTO.getId().toString());
                }
            }
        }
        contractService.updateById(contract);
        log.info("{}", "signContractCallBack");
        log.info("{}", processId);
        return ApiResult.builder().code(RestCode.SIGN_SUCCESS.getCode()).build();
    }

    @Override
    public SignProcessType getProcessType() {
        return SignProcessType.CONTRACT;
    }

}
