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.po.file.SignFile;
import com.seeyon.apps.esign.po.file.TemplateComponent;
import com.seeyon.apps.esign.utils.HttpClient;
import com.seeyon.ctp.common.AppContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class EsignFileTemplateService {

    private static final String ORI_TEMPLATE = "原始合同模板文件";
    private static final Log log = LogFactory.getLog(EsignFileTemplateService.class);
    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();
    private TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");
    private EsignUploadFileService uploadFileService = (EsignUploadFileService) AppContext.getBean("esignUploadFileService");

    private String getOrgId(String appId) {
        EsignApiHeader esignApiHeader = EsignApiHeader.build();
        try {
            esignApiHeader.token(tokenCacheManager.getToken(appId)).appId(appId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取orgId
        String queryStr = EsignApiUrl.QUERY_ORGINFO + "?orgName=" + tokenCacheManager.getOrgNameByAppId(appId);
        String reqUrl = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + queryStr;
        String orgInfoRespStr = HttpClient.httpGet(reqUrl, esignApiHeader.convert2Headers(), "UTF-8");
        EsignBaseResp orgInfoResp = JsonUtils.parseObject(orgInfoRespStr, EsignBaseResp.class);
        Map<String, Object> orgData = (Map<String, Object>) orgInfoResp.getData();
        return  (String) orgData.get("orgId");
    }

    //填充模板
    public SignFile fillTemplate(String templateId, String fileName, Map<String,Object> params) {
         //请求示例
        Map<String,Object> reqParams =  new HashMap<>();
        reqParams.put("docTemplateId",templateId);
        reqParams.put("fileName",fileName);
        List<TemplateComponent> components = new ArrayList<>();
        Set<String> keySets = params.keySet();
        for (String key : keySets) {
            TemplateComponent component = new  TemplateComponent();
            component.setComponentKey(key);
            component.setComponentValue((String) params.get(key));
            components.add(component);
        }
        reqParams.put("components",components);
        String url = "";
        String resp = HttpClient.httpPostRaw(url, JsonUtils.toJSONString(reqParams), null, null);
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(resp, EsignBaseResp.class);
        if(esignBaseResp.getCode() != 0) {}
        Map<String,Object> dataMap = (Map<String, Object>) esignBaseResp.getData();
        SignFile signFile = new SignFile();
        signFile.setFileId((String) dataMap.get("fileId"));
        signFile.setFileName(fileName);
        return signFile;
    }

    //获取模板详细信息
    public Map<String,Object> getTemplateDetail(String signTemplateId,String orgId,Boolean queryComponents) {
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + "?" + "signTemplateId=" + signTemplateId + "&orgId=" + orgId + (queryComponents != null ? "&queryComponents=" + queryComponents : "");
        String resp = HttpClient.httpGet(url, null, "UTF-8");
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(resp, EsignBaseResp.class);
        Map<String,Object> data = (Map<String, Object>) esignBaseResp.getData();
        return data;
    }

    //获取模板详细信息
    public Map<String,Object> getTemplateDetail(String appId,String signTemplateId,String orgId) {
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.QUERY_TEMPLATE_DETAIL_URL + "?" +"orgId=" + orgId + "&signTemplateId=" + signTemplateId;
        EsignApiHeader apiHeader = EsignApiHeader.build().token(tokenCacheManager.getToken(appId)).appId(appId);
        String resp = HttpClient.httpGet(url, apiHeader.convert2Headers(), "UTF-8");
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(resp, EsignBaseResp.class);
        Map<String,Object> data = (Map<String, Object>) esignBaseResp.getData();
        return data;
    }

    public Map<String,Object> queryTemplates(String appId,Integer pageNo) throws Exception {
        EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId);
        String queryStr =  EsignApiUrl.QUERY_TEMPLATES_URL + "?" + "orgId=" + obtainOrgId(appId) + "&pageNum=" + pageNo + "&pageSize=" + 20 + "&status=" + 1;
        esignApiHeader.token(tokenCacheManager.getToken(appId));
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) +  queryStr;
        String templateListRespStr = HttpClient.httpGet(url, esignApiHeader.convert2Headers(), "UTF-8");
        EsignBaseResp templateListResp = JsonUtils.parseObject(templateListRespStr, EsignBaseResp.class);
        Map<String,Object> listData = (Map<String,Object>)templateListResp.getData();
        Integer total = (Integer) listData.get("total");
        Object[] templateArray = (Object[]) listData.get("signTemplates");
        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("total",total);
        pageMap.put("templateList",templateArray);
        return pageMap;
    }

    public String getCompareDetailUrl(String appId,String templateRefId,String contractRefId) throws Exception {
        String templateFileId = uploadFileService.uploadFileToEsign(appId,templateRefId).get(0);
        String contractFileId = uploadFileService.uploadFileToEsign(appId,contractRefId).get(0);
        String url = configProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.CONTRACT_COMPARE_GETURL;
        Map<String,String> params = new HashMap<>();
        params.put("standardFileId",templateFileId);
        params.put("comparativeFileId",contractFileId);
        String jsonString = JsonUtils.toJSONString(params);
        EsignApiHeader esignApiHeader = EsignApiHeader.build().appId(appId);
        esignApiHeader.token(tokenCacheManager.getToken(appId));
        String respStr = HttpClient.httpPostRaw(url, jsonString, esignApiHeader.convert2Headers(), null);
        EsignBaseResp esignBaseResp = JsonUtils.parseObject(respStr, EsignBaseResp.class);
        log.info("调用获取合同比对链接接口返回值: "  + JsonUtils.toJSONString(esignBaseResp));
        Map<String,String> data = (Map<String, String>) esignBaseResp.getData();
        String contractCompareUrl = data.get("contractCompareUrl");
        return contractCompareUrl;
    }

    private String obtainOrgId(String appId) {
        return getOrgId(appId);
    }
}
