package com.weaver.seconddev.interfaces.workflow.action;

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.ebuilder.form.client.ebform.data.EbFormDataDubboService;
import com.weaver.framework.rpc.annotation.RpcReference;
import  com.weaver.seconddev.interfaces.crmoa.CRM_SyncUnFreezeTimesStub;
import  com.weaver.seconddev.interfaces.crmoa.CRM_syncUnFreezeTimes;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.interfaces.workflow.util.CommonDevUtil;
import com.weaver.teams.domain.user.SimpleEmployee;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * SAP--信贷解锁接口--qingf20170327
 * @author Administrator
 */
@org.springframework.stereotype.Service("workflow_action_ZOA_SD_CREDIT_HANDLE_APPROVALAction")
public class ZOA_SD_CREDIT_HANDLE_APPROVALAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    @Autowired
    private CommonDevUtil commonDevUtil;

    @RpcReference(group = "ebuilderform")
    private EbFormDataDubboService ebFormDataDubboService;


    @Autowired
    private CRM_syncUnFreezeTimes freezeTimes ;
    private static final Logger logger_d591fda6 = LoggerFactory.getLogger(ZOA_SD_CREDIT_HANDLE_APPROVALAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            try {
                String requestId = "";
                // 销售组织
                String xszz = "";
                // 单号类别0交货单、1销售单
                String spdhlb = "";
                // 对应单号
                String dydh = "";
                // 客户编码
                String khbm = "";
                // 申请人
                String sqrgh = "";
                // 申请日期
                String sqrq = "";
                // 操作类型APPROVAL批准
                String czlx = "APPROVAL";
                String[] prdetail = null;
                prdetail = new String[7];
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                BillFieldUtil unit = new BillFieldUtil();
                // 流程请求ID
                requestId = request.getRequestid();
                logger_d591fda6.error(String.valueOf("ZOA_SD_CREDIT_HANDLE_APPROVALAction-Request: " + requestId + "开始"));
                // 获取表单主字段信息
                Property[] properties = request.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    // 主表数据
                    // 字段名
                    String name = properties[i].getName().toLowerCase();
                    // 值
                    String value = Util.null2String(properties[i].getValue());
                    // 单据主信息使用
                    if (name.equals("xszz")) {
                        // 销售组织
                        xszz = value.trim();
                    }
                    if (name.equals("spdhlb")) {
                        // 单号类别0交货单、1销售单
                        spdhlb = value;
                    }
                    if (name.equals("dydh1")) {
                        // 对应单号
                        dydh = value.trim();
                    }
                    if (name.equals("khbm")) {
                        // 客户编码
                        khbm = value.trim();
                    }
                    if (name.equals("sqr")) {
                        // 申请人
                        sqrgh = unit.getWorkcode(value.trim());
                    }
                    if (name.equals("sqrq")) {
                        // 申请日期
                        sqrq = value.trim();
                    }
                }
                if (spdhlb.equals("0")) {
                    prdetail[1] = dydh;
                }
                if (spdhlb.equals("1")) {
                    prdetail[0] = dydh;
                }
                prdetail[2] = xszz;
                prdetail[6] = khbm;
                ZOA_SD_CREDIT_APPROVAL_HANDLE po = new ZOA_SD_CREDIT_APPROVAL_HANDLE();
                String[] fhz = po.Getexecute(czlx, prdetail);
                // APPROVAL返回值
                String sta = fhz[4];
                String meg = fhz[5].replace("'", "’");
                String tablename = "";
                String wfid = request.getWorkflowid();
//                tablename = unit.getTablename(wfid);
                tablename = request.getRequestManager().getBillTableName();
                String logsql = "update e10_core_business.dbo." + tablename + " set sta ='" + sta + "', meg = '" + meg + "' where id = " + requestId;
                logger_d591fda6.error(String.valueOf("logsql:" + logsql));
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(logsql, poolname);
                logger_d591fda6.error(String.valueOf("b--" + b));
                logger_d591fda6.error(String.valueOf("ZOA_SD_CREDIT_HANDLE_APPROVALAction-Request: " + requestId + "完成"));
                if (!sta.equals("S")) {
                    request.getRequestManager().setMessageid("100001");
                    request.getRequestManager().setMessagecontent(meg);
                } else {
                    try {
                        CRM_SyncUnFreezeTimesStub.CRM_OA_SyncUnFreezeTimes times = new CRM_SyncUnFreezeTimesStub.CRM_OA_SyncUnFreezeTimes();
                        CRM_SyncUnFreezeTimesStub.ArrayOfCRM_UNFREEZETIMES_HEAD headArray = new CRM_SyncUnFreezeTimesStub.ArrayOfCRM_UNFREEZETIMES_HEAD();
                        CRM_SyncUnFreezeTimesStub.CRM_UNFREEZETIMES_HEAD head = new CRM_SyncUnFreezeTimesStub.CRM_UNFREEZETIMES_HEAD();
//                        CRM_syncUnFreezeTimes freezeTimes = new CRM_syncUnFreezeTimes();
                        head.setREQUESTID(requestId);
                        head.setKHBM(khbm);
                        head.setSQRGH(sqrgh);
                        head.setSQRQ(sqrq);
                        head.setXSZZ(xszz);
                        logger_d591fda6.error(String.valueOf("------------do webservice [requestId:" + requestId + "][khbm:" + khbm + "][sqrgh:" + sqrgh + "][sqrq:" + sqrq + "][xszz:" + xszz + "]------------"));
                        headArray.addCRM_UNFREEZETIMES_HEAD(head);
                        times.setUnfreezetimes(headArray);
                        freezeTimes.setOainputvendor(times);
                        String[] result = freezeTimes.call();
                        if (result != null) {
                            if (!result[0].equals("S")) {
                                // 不成功 打印日志 把数据写入中间表
                                logger_d591fda6.error(String.valueOf("------------[state : " + result[0] + "][message : " + result[1] + "] ----------"));
                                logger_d591fda6.error(String.valueOf("------------do webservice CRM_syncUnFreezeTimes fail ----------"));
                                // 把数据写入中间表
//                                String sql = "insert into HT_CRM_JDCS (REQUESTID,KHBM,XSZZ,SQRGH,SQRQ,CREATEDATE ) VALUES ('" + requestId + "','" + khbm + "','" + xszz + "','" + sqrgh + "','" + sqrq + "',GETDATE())";
//                                logger_d591fda6.error(String.valueOf("写入中间表sql : " + sql));
//                                String poolname_jj = CONN_TYPE.workflow.getType();
//                                /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//                                long generate = IdGenerator.generate();
//                                rs.executeSql(sql, poolname_jj,generate);

                                Long uf_CustomFlow_formId = commonDevUtil.getObjId("HT_CRM_JDCS");
                                logger_d591fda6.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
                                SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                                Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);// 获取插入的空的建模id
                                String sql3 = "update e10_common.dbo.HT_CRM_JDCS set REQUESTID = '" + requestId + "',KHBM='" + khbm + "',XSZZ='" + xszz + "',SQRGH='" + sqrgh + "',SQRQ='" + sqrq + "',CREATEDATE=GETDATE() where id  =  " + recodId + " and delete_type = 0 ";

                                logger_d591fda6.error("sql3 = " + sql3);
                                boolean b1 = rs.executeSql(sql3, poolname);

                                logger_d591fda6.error("添加 = " + b1);
                                logger_d591fda6.error(String.valueOf("------------写入中间表 success ----------"));

                            } else {
                                // 成功
                                logger_d591fda6.error(String.valueOf("------------[state : " + result[0] + "][message : " + result[1] + "] ----------"));
                                logger_d591fda6.error(String.valueOf("------------do webservice CRM_syncUnFreezeTimes success ----------"));
                            }
                        }
                    } catch (Exception e) {
                        System.err.println(e.toString());
                        logger_d591fda6.error(String.valueOf("调用接口报错 " + e.toString()));
                        return  WeaResult.fail(500, "调用接口报错 "+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

                    }
                }
                System.out.println(meg);
            } catch (Exception e) {
                System.err.println(e.toString());
                logger_d591fda6.error(String.valueOf("调用接口报错 " + e.toString()));
                return  WeaResult.fail(500, "调用接口报错 e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_d591fda6.error("ZOA_SD_CREDIT_HANDLE_APPROVALAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZOA_SD_CREDIT_HANDLE_APPROVALAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
        }
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
