package com.seeyon.apps.esign.service;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.esign.config.EsignConfigProvider;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.utils.FileUtil;
import com.seeyon.apps.esign.utils.ProtUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.utils.form.EnumMapUtils;
import com.seeyon.utils.form.FormTableExecutor;
import com.seeyon.utils.form.FormUpdateField;
import com.seeyon.utils.form.FormWhereCondition;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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


public class EsignCallbackFlowBizService implements EsignCallbackBizService{

    private static final Log log = LogFactory.getLog(EsignCallbackFlowBizService.class);
    private ProtUtil protUtil = (ProtUtil) AppContext.getBean("protUtil");
    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();

    public void handleSuccessSignCallbackBiz(String tablename,String updatefield,String statusField,String formId,Object[] fileInfos) throws Exception {
        String[] strings = formId.split("_");
        String oaFlowId = strings[0];
        String tempFormId = strings[1];
        String[] statusParams = statusField.split("_");
        String status = statusParams[0];
        String enumId = statusParams[1];
        String enumItemId = EnumMapUtils.getEnumItemValueByEnumId("已签署",Long.parseLong(enumId));
        //下载文件到本地
        List<FormWhereCondition> conditions = new ArrayList<>();
        String refId = FileUtil.uploadContractToOA(fileInfos, getModuleId(tempFormId),
                configProvider.getBizConfigByKey(EsignConfigConstants.FORMEDITLOGINNAME),
                configProvider.getBizConfigByKey(EsignConfigConstants.updateAccountName));
        List<FormUpdateField> updateFields = new ArrayList<>();
        updateFields.add(FormUpdateField.build().fieldName(updatefield).value(refId));
        updateFields.add(FormUpdateField.build().fieldName(status).value(enumItemId));
        conditions.add(FormWhereCondition.build().value(tempFormId).fieldName("ID"));
        JSONObject params = new JSONObject();
        params.put("message", "签署完成！！！");
        params.put("returnCode", 1);
        protUtil.sendPostNotification(params.toString(), configProvider.getBizConfigByKey(EsignConfigConstants.nodeTokenUrl), oaFlowId);
        FormTableExecutor.update(tablename,updateFields,conditions);
    }

    public void handleFailSignCallbackBiz(String tableName,String statusField,String formId,String failMsg) throws Exception {
        String[] strings = formId.split("_");
        String oaFlowId = strings[0];
        String tempFormId = strings[1];
        String[] statusParams = statusField.split("_");
        String status = statusParams[0];
        String enumId = statusParams[1];
        String enumItemId = EnumMapUtils.getEnumItemValueByEnumId("签署失败",Long.parseLong(enumId));
        List<FormWhereCondition> conditions = new ArrayList<>();
        List<FormUpdateField> updateFields = new ArrayList<>();
        updateFields.add(FormUpdateField.build().fieldName(status).value(enumItemId));
        conditions.add(FormWhereCondition.build().value(tempFormId).fieldName("ID"));
        JSONObject params = new JSONObject();
        params.put("message", "签署失败: " + failMsg);
        params.put("returnCode", 2);
        protUtil.sendPostNotification(params.toString(), configProvider.getBizConfigByKey(EsignConfigConstants.nodeTokenUrl), oaFlowId);
        FormTableExecutor.update(tableName,updateFields,conditions);
    }

    private String getModuleId(String formId) {
        JDBCAgent jdbcAgent = new JDBCAgent();
        try {
            String sql = "SELECT MODULE_ID FROM ctp_content_all where CONTENT_DATA_ID = ?";
            List<Object> params = new ArrayList<>();
            params.add(formId);
            jdbcAgent.execute(sql,params);
            List list = jdbcAgent.resultSetToList();
            if(list == null || !(list.size() > 0)) {
                throw new RuntimeException("MODULE_ID获取失败");
            }
            Map<String,Object> map = (Map<String, Object>) list.get(0);
            return map.get("module_id") +"";
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
