package com.bcxin.signature.api.controller;

import cn.hutool.core.date.DateUtil;
import com.bcxin.signature.config.exception.BusinessException;
import com.bcxin.signature.config.yesign.YesignUtil;
import com.bcxin.signature.util.StringUtils;
import com.bcxin.signature.util.common.cipher.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * <b> 负责对外接口 </b>
 * @author ZXF
 * @create 2021/01/28 0028 13:20
 * @version
 * @注意事项 </b>
 */
@RestController
@RequestMapping("/signature/api/file")
@Slf4j
public class FileController {

    @Autowired
    private YesignUtil yesignUtil;
    @Value("${signature.api}")
    String api;

    @PostMapping(value = "/yesign")
    public void yesign(MultipartHttpServletRequest request, HttpServletResponse response) throws BusinessException {
        String token = request.getParameter("token");
        MultipartFile signpdf = request.getFile("signpdf");
        String fileName = request.getParameter("fileName");
        if(StringUtils.isEmpty(fileName)||signpdf == null){
            log.error("====> 电子签章中转开始.yesign.BusinessException：参数异常");
            throw new BusinessException("300","参数异常！");
        }
        String cretoken = MD5Util.string2MD5("BCXIN" + fileName + DateUtil.today());
        if(StringUtils.isEmpty(token)||!token.equals(cretoken)){
            log.error("====> 电子签章中转开始.yesign.BusinessException：非法请求，来源不受信任！");
            throw new BusinessException("403","非法请求，来源不受信任！");
        }

        try {
            yesignUtil.signPdf(signpdf,api,fileName,response);
        } catch (Exception e) {
            log.error("====> 电子签章中转开始.yesign.BusinessException：签章失败："+e.getMessage());
            throw new BusinessException("500","签章失败："+e.getMessage());
        }
    }
}
