package com.seeyon.apps.esign.service;

import com.seeyon.aicloud.common.JsonUtils;
import com.seeyon.apps.esign.config.EsignConfigProvider;
import com.seeyon.apps.esign.constants.EsignApiUrl;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.po.esignapi.EsignApiHeader;
import com.seeyon.apps.esign.po.esignapi.EsignBaseResp;
import com.seeyon.apps.esign.utils.HttpClient;
import com.seeyon.apps.esign.utils.JsonCleaner;
import com.seeyon.ctp.common.AppContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import java.util.Map;


public class EsignByTemplateService {
    
    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();
    private TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");
    private static final Log log = LogFactory.getLog(EsignByTemplateService.class);

    public void signByTemplate(Map<String,Object> params) {

    }

    public void startSignFlow(String flowId) throws Exception {
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.SIGN_START_URL;
        url.replace("{signFlowId}", flowId);
        String respStr = HttpClient.httpPostRaw(url, "", null, null);
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
        if (esignBaseResp.getCode() != 0) {
            throw new Exception("签署发起失败");
        }
    }

    public String createBySignTemplate(String appId,Map<String,Object> params) throws Exception {
        EsignApiHeader esignApiHeader = EsignApiHeader.build();
        String jsonBody = JsonCleaner.removeEmptyObjects(JsonUtils.toJSONString(params));
        esignApiHeader.token(tokenCacheManager.getToken(appId)).appId(appId);
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.SIGN_BY_FILE_URL;
        log.info("合同发起入参： " + jsonBody);
        String respStr = HttpClient.httpPostRaw(url, jsonBody, esignApiHeader.convert2Headers(), "UTF-8");
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
        Map<String,Object> dataMap = (Map<String, Object>) esignBaseResp.getData();
        if(!"0".equals(esignBaseResp.getCode() + "")) {
            throw new RuntimeException("签署发起失败," + esignBaseResp.getMessage());
        }
        String flowId = (String) dataMap.get("signFlowId");
        return flowId;
    }
}
