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.ext.workflow.vo.FormDataVo;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.utils.http.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import www.seeyon.com.utils.UUIDUtil;

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


public class SignLinkService {

    private static final Log log = LogFactory.getLog(SignLinkService.class);
    private EsignConfigProvider esignConfigProvider = (EsignConfigProvider) AppContext.getBean("esignConfigProvider");
    private TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");

    public void saveGetLinkParam(FormDataVo formDataVo,String eFlowId,String appId) {
        try {
            String bSignerType = formDataVo.getFieldData("乙方签署类型").getStringValue();
            String psnAccount = null;
            if(!"组织".equals(bSignerType) ) {
                psnAccount = formDataVo.getFieldData("乙方电话").getStringValue();
            }else {
                psnAccount = formDataVo.getFieldData("乙方经办人手机号").getStringValue();
            }
            String contractNo = formDataVo.getFieldData("合同编号").getStringValue();
            Map<String,Object> param = new HashMap<>();
            Map<String,Object> operator = new HashMap<>();
            operator.put("psnAccount",psnAccount);
            param.put("signFlowId",eFlowId);
            param.put("operator",operator);
            String paramStr = JsonUtils.toJSONString(param);
            saveDb(paramStr,eFlowId,contractNo,appId);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }

    }

    public void del(String eFlowId) {
        String sqlDel = "delete FROM SIGN_LINK_PARAM where eFlowId = ?";
        JDBCAgent jdbcAgent = new JDBCAgent();
        try {
            List<Object> param = new ArrayList<>();
            param.add(eFlowId);
            jdbcAgent.execute(sqlDel,param);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }finally {
            jdbcAgent.close();
        }
    }

    private void saveDb(String jsonStr,String eFlowId,String contractNo,String appId) {
        String sqlInsert = "insert into SIGN_LINK_PARAM (id,param,eFlowId,contractNo,appId) values (?,?,?,?,?)";
        String sqlQuery = "select * FROM SIGN_LINK_PARAM where contractNo = ?";
        String sqlUpdate = "update SIGN_LINK_PARAM set param = ?,eFlowId = ? where id = ?";
        JDBCAgent jdbcAgent = new JDBCAgent();
        try {
            List<Object> param = new ArrayList<>();
            param.add(contractNo);
            jdbcAgent.execute(sqlQuery,param);
            List list = jdbcAgent.resultSetToList();
            long id = UUIDUtil.getUUIDLong();
            if(list.size() == 0) {
                param.clear();
                param.add(id);
                param.add(jsonStr);
                param.add(eFlowId);
                param.add(contractNo);
                param.add(appId);
                jdbcAgent.execute(sqlInsert,param);
            }else {
                param.clear();
                Map<String,Object> tempMap  = (Map<String, Object>) list.get(0);
                param.add(jsonStr);
                param.add(eFlowId);
                param.add(tempMap.get("id"));
                jdbcAgent.execute(sqlUpdate,param);
            }
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }finally {
            jdbcAgent.close();
        }
    }

    public String getSignLink(String eFlowId) {
        String sqlQuery = "select * from SIGN_LINK_PARAM where eFlowId = ?";
        JDBCAgent jdbcAgent = new JDBCAgent();
        try {
            List<Object> param = new ArrayList<>();
            param.add(eFlowId);
            jdbcAgent.execute(sqlQuery,param);
            List list = jdbcAgent.resultSetToList();
            if(list.size() > 0) {
                Map<String,Object> tempMap  = (Map<String, Object>) list.get(0);
                String paramStr = (String)tempMap.get("param");
                String appId = (String)tempMap.get("appid");
                if(!checkContractVaild(appId,eFlowId)) {
                    throw new RuntimeException("当前合同无效");
                }
                String url = esignConfigProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.SIGN_LINK_GET_URL.replace("{signFlowId}",eFlowId);
                EsignApiHeader esignApiHeader = EsignApiHeader.build();
                esignApiHeader.token(tokenCacheManager.getToken(appId)).appId(appId);
                String respStr = HttpClient.httpPostRaw(url, paramStr,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() + "")) {
                    log.error("合同链接获取失败," + esignBaseResp.getMessage());
                }else {
                    return (String) dataMap.get("url");
                }
            }

        }catch (Exception e) {
            log.error("合同链接获取失败:"+e.getMessage(),e);
        }finally {
            jdbcAgent.close();
        }
        return null;
    }

    private boolean checkContractVaild(String appId,String eFlowId) {
        EsignApiHeader esignApiHeader = EsignApiHeader.build();
        esignApiHeader.token(tokenCacheManager.getToken(appId)).appId(appId);
        String url = esignConfigProvider.getBizConfigByKey(EsignConfigConstants.ESIGN_HOST) + EsignApiUrl.SIGN_FLOW_QUERY.replace("{signFlowId}",eFlowId);
        String respStr = HttpClient.httpGet(url, 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() + "")) {
            log.error("合同信息查询失败," + esignBaseResp.getMessage());
            return false;
        }
        Integer flowStatus  = (Integer) dataMap.get("signFlowStatus");
        return flowStatus == 1;
    }

}
