package com.seeyon.apps.esign.controller;

import cn.hutool.log.Log;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seeyon.apps.esign.po.esignapi.EsignCallbackParams;
import com.seeyon.apps.esign.service.EsignUploadFileService;
import com.seeyon.apps.esign.service.EsignCallbackFlowBizService;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.util.annotation.NeedlessCheckLogin;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class DefaultEsignCallBackController extends BaseController {

    private static final Log log = Log.get(DefaultEsignCallBackController.class);

    private EsignUploadFileService esignUploadFileService = (EsignUploadFileService) AppContext.getBean("esignUploadFileService");
    private EsignCallbackFlowBizService esignCallbackFlowBizService = (EsignCallbackFlowBizService) AppContext.getBean("esignCallbackFlowBizService");

    @NeedlessCheckLogin
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("签署回调触发");
            // 签署回调处理，改变超级节点状态
            String formId = request.getParameter("formId");
            String tableName = request.getParameter("tablename");
            String updatefield = request.getParameter("updatefield");
            String statusfield = request.getParameter("statusfield");;
            String appId = request.getParameter("xId");
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String body = sb.toString();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            EsignCallbackParams callbackParams = mapper.readValue(body, new TypeReference<EsignCallbackParams>() {
            });
            String flowId = callbackParams.getSignFlowId();
            String action = callbackParams.getAction();
            log.info("签署回调当前流程: " + flowId);
            if(action.equals("SIGN_FLOW_COMPLETE")) {
                if(callbackParams.getSignFlowStatus() == 2) {
                    Object[] fileInfos = esignUploadFileService.getDownloadFileInfo(appId,flowId);
                    esignCallbackFlowBizService.handleSuccessSignCallbackBiz(tableName,updatefield,statusfield,formId,fileInfos);
                }else if(callbackParams.getSignFlowStatus() == 5){
                    //合同过期
                    //esignCallbackBizService.handleExpiredSignCallbackBiz(tableName,statusfield,formId);
                }else {
                    esignCallbackFlowBizService.handleFailSignCallbackBiz(tableName,statusfield,formId,callbackParams.getResultDescription());
                }
                //signLinkService.del(flowId);
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }else if(action.equals("SIGN_MISSON_COMPLETE") && callbackParams.getSignResult() == 2 && callbackParams.getSignOrder() == 2){
                //发送消息
//                MessageVo messageVo = new MessageVo();
//                messageVo.setBizId(flowId);
//                messageVo.setMessageType("SIGN");

//                thirdMessageService.sendMessage();
            }
            //下载合同
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            try (OutputStream out = response.getOutputStream()) {
                out.write("{\"code\":\"200\",\"msg\":\"success\"}".getBytes(StandardCharsets.UTF_8));
                out.flush();
            }
            log.info("回调处理完成: " + flowId);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("回调处理失败", e);
        }
//        response.setStatus(HttpServletResponse.SC_OK);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}
