package com.seeyon.apps.esign.node;

import com.seeyon.aicloud.common.JsonUtils;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.common.workflow.node.ACommonSuperNode;
import com.seeyon.apps.esign.config.EsignConfigProvider;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.po.param.FlowParamSource;
import com.seeyon.apps.esign.po.signer.OrgInfo;
import com.seeyon.apps.esign.po.signer.PersonInfo;
import com.seeyon.apps.esign.po.signer.SignParty;
import com.seeyon.apps.esign.po.signer.SignerType;
import com.seeyon.apps.esign.service.ContractCreateService;
import com.seeyon.apps.esign.service.SealService;
import com.seeyon.apps.esign.service.TokenCacheManager;
import com.seeyon.apps.ext.workflow.vo.FieldDataVo;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.ext.workflow.vo.SuperNodeContext;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.utils.form.*;
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 EsignAntiFakeSignNode extends ACommonSuperNode {

    private static final Log log = LogFactory.getLog(EsignAntiFakeSignNode.class);
    private EsignConfigProvider configProvider = EsignConfigProvider.getInstance();
    private TokenCacheManager tokenCacheManager = (TokenCacheManager) AppContext.getBean("tokenCacheManager");
    private ContractCreateService contractCreateService = (ContractCreateService) AppContext.getBean("contractCreateService");
    private SealService sealService = (SealService) AppContext.getBean("sealService");

    @Override
    public String getPluginId() {
        return EsignConfigConstants.getPluginId();
    }

    @Override
    public String getFormParse() {
        return "";
    }

    @Override
    public SuperNodeContext proceed(String s, FormDataVo formDataVo, FormDataMasterBean formDataMasterBean) throws Exception {
        SuperNodeContext context = new SuperNodeContext();
        context.setNeedSave(true);
        log.info("进入E签宝防伪签署签署集成超级节点");
        try {
            FlowParamSource source = new FlowParamSource();
            source.setConfigProvider(configProvider);
            source.setFormDataVo(formDataVo);
            source.setDoAutoSign(true);
            String unitName = configProvider.getBizConfigByKey(EsignConfigConstants.FIXAPPUNITNAME);
            String appId = tokenCacheManager.getAppIdByOrgName(unitName);
            source.setAppId(appId);
            source.setMasterBean(formDataMasterBean);
            source.setUseKeyWordPositing(false);
            source.setSignerParties(buildSigners(formDataVo,true,unitName));
            String esignFlowId = contractCreateService.startSign(source);
            if(esignFlowId == null) {
                return context.back("E签宝签署发起失败");
            }
            log.info("E签宝签署流程ID: " + esignFlowId + " , OA超级节点ID：" + formDataVo.getToken());
            log.info("E签宝多方签署合同已发送: " + esignFlowId);
            return context.wait("等待签署结束");
        } catch (Exception e) {
            log.error("E签宝签署失败", e);
            e.printStackTrace();
            context.setErrMsg("E签宝签署失败: " + e.getMessage());
            return context.back("E签宝签署失败: " + e.getMessage());
        }
    }

    private String getStringField(FormDataVo vo, String field) {
        try {
            FieldDataVo fieldData = vo.getFieldData(field);
            return fieldData.getStringValue();
        }catch (Exception e) {
            return null;
        }
    }

    private V3xOrgMember getPsn(Long memberId) throws NoSuchFieldException {
        OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
        if(memberId != null) {
            try {
                V3xOrgMember member = orgManager.getMemberById(memberId);
                return member;
            }catch (Exception e){

            }
        }
        return null;
    }

    private String getLastSenderId(Long caseId) {
        List<String> columns = new ArrayList<>();
        columns.add("SENDER_ID");
        SqlBuildParam param = new SqlBuildParam();
        List<FormWhereCondition> conditions = new ArrayList<>();
        conditions.add(FormWhereCondition.build().fieldName("CASE_ID").value(caseId));
        param.setSqlType(SqlType.SELECT);
        param.setTableName("ctp_affair");
        param.setQueryColumns(columns);
        param.setConditions(conditions);
        param.setPageNo(1);
        param.setPageSize(1);
        param.setOrderField("UPDATE_DATE");
        param.setSortType("DESC");
        Map<String, Object> sqlMap = FormTableExecutor.generateSql(param);
        JDBCAgent agent = new JDBCAgent();
        try {
            agent.execute((String)sqlMap.get("sql"), (List)sqlMap.get("params"));
            log.info("执行sql为: " + sqlMap.get("sql"));
            List<Map<String, Object>> rows = agent.resultSetToList();
            if(rows.size() <= 0) {
                return null;
            }
            Map<String, Object> map = rows.get(0);
            return map.get("sender_id") + "";
        } catch (Exception e) {
            log.error("执行sql为: " + sqlMap.get("sql"));
            log.error("执行sql参数为: " + JsonUtils.toJSONString(sqlMap.get("params")));
            log.error(e.getMessage(), e);
        } finally {
            agent.close();
        }

        return null;
    }

    private List<SignParty> buildSigners(FormDataVo formDataVo, Boolean doAutoSign, String unitName) throws NoSuchFieldException, BusinessException {
        List<SignParty> parties = new ArrayList<>();
        SignParty party = new SignParty();
        ColSummary colSummary = formDataVo.getColSummary();
        Long caseId = colSummary.getCaseId();
        String senderId = getLastSenderId(caseId);
        party.setPartyId("防伪章签署方");
        party.setSignOrder(2);
        party.setSignerType(SignerType.ORG);
        party.setSignAcrossPage(false);
        party.setAutoSign(doAutoSign);
        party.setSealId(sealService.getAntiFakeSealId(unitName));
        OrgInfo orgInfo = new OrgInfo();
        party.setOrgInfo(orgInfo);
        if(!doAutoSign){
            if(senderId == null) {
                return null;
            }
            V3xOrgMember psn = getPsn(Long.parseLong(senderId));
            String psnName = psn.getName();
            if(psnName == null) {
                throw new RuntimeException("防伪章签署经办人为空");
            }
            String psnMobile = psn.getTelNumber();
            String orgName = unitName;
            PersonInfo personInfo = new PersonInfo();
            orgInfo.setOrgName(orgName);
            personInfo.setName(psnName);
            personInfo.setPhone(psnMobile);
            orgInfo.setTransactor(personInfo);
        }else {
            orgInfo.setOrgId(tokenCacheManager.getOrgIdByOrgName(unitName));
        }
        parties.add(party);
        return parties;
    }

    @Override
    public String getNodeId() {
        return "nd_20260508";
    }

    @Override
    public String getNodeName() {
        return "E签宝防伪签署节点";
    }
}
