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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.util.HashMap;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
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 com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import com.weaver.verupgrade.soa.workflow.request.*;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * 投资类合同登记提交同步
 */
@org.springframework.stereotype.Service("workflow_action_EasTzlhtSyncAction")
public class EasTzlhtSyncAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private EasTzlhtApplyResult mGetResult;
    private static final Logger logger_197dffab = LoggerFactory.getLogger(EasTzlhtSyncAction.class);

    @Override
    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 requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            /**
             * 请求ID*
             */
            String requestID = "";
            /**
             * 报账总金额*
             */
            float totalMoney = 0;
            /**
             * 系统标识*
             */
            String systemFlag = "OA";
            /**
             * 接口ID*
             */
            String ITFID = "ITFID";
            try {
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_197dffab.info(String.valueOf("EasTzlhtSyncAction--start--" + requestID));
                logger_197dffab.info("requestIdTemp == " +requestIdTemp);
                logger_197dffab.info("userIdTemp == " +userIdTemp);
                Map<String, String> mMap = new HashMap<String, String>();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    mMap.put(name, value);
                }
                String money = mMap.get("BZZJE");
                logger_197dffab.info(String.valueOf("报账总金额:" + money));
                if (money != null && !money.equals("")) {
                    totalMoney = Float.parseFloat(money);
                }
                // 申请人
                String sqr = mMap.get("SQR");
                String sqrcode = "";
                String sqrname = "";
                if (!sqr.equals("")) {
                    // 申请人工号
                    sqrcode = unit.getWorkcode(sqr);
                    // 申请人姓名
                    sqrname = hr.getResourcename(sqr);
                }
                String id_hsdw = mMap.get("HSDW");
                String companyId = "";
                String companyCode = "";
                String companyName = "";
                if (!id_hsdw.equals("")) {
                    companyId = gethsdwid(id_hsdw);
                    // 公司名称
                    companyName = gethsdwname(id_hsdw);
                    // 公司编码
                    companyCode = gethsdwcode(id_hsdw);
                }
                String deptId = mMap.get("SQBM");
                String deptCode = "";
                if (!"".equals(deptId)) {
                    deptCode = getDepartmentcode(deptId);
                }
                // String bz = mMap.get("BZ");
                // String currency = "";
                // if ("0".equals(bz)) {
                // currency = "CNY";
                // } else {
                // currency = "USD";
                // }
                String htlx = mMap.get("HTLX");
                String htlxname = "";
                if ("0".equals(htlx)) {
                    // 产业投资类
                    htlxname = "BOE_TYPE_IND";
                } else {
                    // 财务投资类
                    htlxname = "BOE_TYPE_FIN";
                }
                JSONObject mJson = new JSONObject();
                // 系统标识
                mJson.put("systemFlag", systemFlag);
                mJson.put("requestID", requestID);
                // oa合同号
                mJson.put("OANum", mMap.get("LCBH"));
                mJson.put("ITFID", ITFID);
                // 验证1就是提交，2就是归档
                mJson.put("operationFlag", "2");
                // 合同信息
                // 报账人工号
                mJson.put("employeeNumber", sqrcode);
                // 报账人姓名
                mJson.put("employeeName", sqrname);
                // 核算公司ID
                mJson.put("companyId", companyId);
                // 核算公司编码
                mJson.put("companyCode", companyCode);
                // 核算公司名称
                mJson.put("companyName", companyName);
                // 合同名称
                mJson.put("contractName", mMap.get("HTMC"));
                // 提报部门 deptCode
                mJson.put("dept", deptCode);
                // 业务类型
                mJson.put("businessType", "");
                // mJson.put("currency", currency);//币种
                // mJson.put("contractNumber", mMap.get("HTBH"));//合同编号
                // 合同签订日期
                mJson.put("contractDate", mMap.get("HTQDRQ"));
                // 合同类型
                mJson.put("contractType", htlxname);
                // 金额
                mJson.put("amount", money);
                // 相关说明
                mJson.put("remarks", mMap.get("FYSM"));
                // 往来单位id mMap.get("WLDW") vendorid "123684"
                mJson.put("vendorName", mMap.get("VENDORID"));
                // 项目编号  mMap.get("XM")  projectCode "0000"
                mJson.put("project", mMap.get("PROJECTCODE"));
                // 项目预算 预算的relationProjectId
                mJson.put("budget", mMap.get("RELATIONPROJECTID"));
                // vendorNumber
                mJson.put("vendorNumber", mMap.get("VENDORNUMBER"));
                // 
                mJson.put("projectId", mMap.get("PROJECTID"));
                // 币种
                mJson.put("currency", mMap.get("CURRENCYCODE"));
                // select top 100 imagefilename from ImageFile where imagefileid = 158795
                String fileIds = mMap.get("XGFJ");
                String fileNames = "";
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                if (fileIds != null && fileIds.contains(",")) {
                    String[] idArr = fileIds.split(",");
                    for (int i = 0; i < idArr.length; i++) {
                        String sql = "select imagefilename from document_main_access as  docimagefile where docid = " + idArr[i];
                        String poolname_s7 = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        rs.executeSql(sql, poolname_s7);
                        if (rs.next()) {
                            fileNames = fileNames + Util.null2String(rs.getString("imagefilename")) + ",";
                        }
                    }
                    if (fileNames.endsWith(",")) {
                        fileNames = fileNames.substring(0, fileNames.lastIndexOf(","));
                    }
                } else if (fileIds != null && !fileIds.equals("")) {
                    String sql = "select imagefilename from document_main_access as  docimagefile where docid = " + fileIds;
                    String poolname = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    rs.executeSql(sql, poolname);
                    if (rs.next()) {
                        fileNames = Util.null2String(rs.getString("imagefilename"));
                    }
                }
                // 附件id
                mJson.put("fileIds", fileIds);
                // 附件名字
                mJson.put("fileNames", fileNames);
                String errorMsg = "";
                logger_197dffab.info(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                // ===========付款条件明细==============//
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                JSONArray mJSONArray = new JSONArray();
                JSONArray mJSONArray1 = new JSONArray();
                float totalScale = 0;
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    JSONObject item = new JSONObject();
                    Map<String, String> mDetailMap = new HashMap<String, String>();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        String valueq = Util.null2String(cq1.getValue());
                        mDetailMap.put(nameq, valueq);
                    }
                    // 付款阶段数
                    item.put("paymentNum", (Integer.parseInt(mDetailMap.get("FKJDS")) + 1) + "");
                    // 付款阶段
                    item.put("paymentStage", (Integer.parseInt(mDetailMap.get("FKJD")) + 1) + "");
                    // String type = mDetailMap.get("FKFS");
                    // String typename = getFKFname(type);
                    // 付款方式  typename
                    item.put("paymentType", mDetailMap.get("PAYMENTNAME"));
                    // 付款行
                    item.put("paymentid", j);
                    // 付款比例
                    item.put("paymentPercent", mDetailMap.get("FKBL"));
                    // 付款日期
                    item.put("paymentDate", mDetailMap.get("FKRQ"));
                    // 付款金额
                    item.put("paymentAmount", mDetailMap.get("FKJE"));
                    // 期初已付金额
                    item.put("amountPaid", mDetailMap.get("QCYFKJE"));
                    mJSONArray1.add(item);
                }
                if (totalScale != 100) {
                    logger_197dffab.info(String.valueOf("所有付款行比例相加后不等于100%，请重新填写！"));
                    errorMsg = errorMsg + "所有付款行比例相加后不等于100%，请重新填写！</br>";
                    // requestInfo.getRequestManager().setMessagecontent("所有付款行比例相加后不等于100%，请重新填写！");
                    // return  FAILURE_AND_CONTINUE;
                }
                // 约束条件明细
                DetailTable dtq_ystj = detailtable[1];
                Row[] sq_ystj = dtq_ystj.getRow();
                Map<String, JSONArray> map = new HashMap<String, JSONArray>();
                for (int j = 0; j < sq_ystj.length; j++) {
                    // 指定行
                    Row rq = sq_ystj[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    JSONObject item = new JSONObject();
                    Map<String, String> mDetailMap = new HashMap<String, String>();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        String valueq = Util.null2String(cq1.getValue());
                        mDetailMap.put(nameq, valueq);
                    }
                    String ystj_fkjd = (Integer.parseInt(mDetailMap.get("FKJD")) + 1) + "";
                    for (int m = 0; m < mJSONArray1.size(); m++) {
                        if (ystj_fkjd.equals(mJSONArray1.getJSONObject(m).getString("paymentStage"))) {
                            // 付款行id
                            item.put("paymentid", mJSONArray1.getJSONObject(m).getString("paymentid"));
                            break;
                        }
                    }
                    // item.put("paymentid",j);//付款行id
                    // 约束条件id
                    item.put("condition_id", j);
                    // 约束条件
                    item.put("condition", mDetailMap.get("YSTJ").replaceAll("&nbsp;", "").replaceAll("<br>", ""));
                    logger_197dffab.info(String.valueOf("阶段数======" + ystj_fkjd));
                    if (map.containsKey(ystj_fkjd)) {
                        map.get(ystj_fkjd).add(item);
                    } else {
                        JSONArray arr_new = new JSONArray();
                        arr_new.add(item);
                        map.put(ystj_fkjd, arr_new);
                    }
                }
                logger_197dffab.info(String.valueOf("获取明细表数据结束"));
                for (int i = 0; i < mJSONArray1.size(); i++) {
                    JSONObject obj = mJSONArray1.getJSONObject(i);
                    String fkjd = obj.getString("paymentStage");
                    obj.put("conditions", map.get(fkjd));
                }
                mJson.put("contractLines", mJSONArray1);
                logger_197dffab.info("调用投资类合同新增同步接口请求数据1：=====" + mJson.toString());
                // 调用接口
//                EasTzlhtApplyResult mGetResult = new EasTzlhtApplyResult();
                String result = mGetResult.getApproveResult(mJson);
                logger_197dffab.info(String.valueOf("调用投资类合同新增同步接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，E-失败
                    String isTat = jsonObject.getString("iSTAT");
                    // 处理消息
                    String srMessage = jsonObject.getString("sRMSAGE");
                    logger_197dffab.info("报账系统返回数据：" + jsonObject.toString());
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_197dffab.info(String.valueOf("报账系统返回错误信息：" + srMessage));
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                    }
                } else {
                    logger_197dffab.info(String.valueOf("调用报账系统投资类合同新增同步接口返回失败，请联系报账系统管理员！"));
                    requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用报账系统投资类合同新增同步接口返回失败，请联系报账系统管理员！");
                }
            } catch (Exception e) {
                logger_197dffab.info(String.valueOf("提交失败！"));
                logger_197dffab.info(String.valueOf("Error======" + e.getMessage()));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_197dffab.error("EasTzlhtSyncAction e: {}", e.getMessage());
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", WeaResult.fail(500, "执行异常", getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager())), requestInfo.getRequestManager()));
        }
    }

    public String gethsdwcode(String var1) {
        String var2 = "";
        RecordSet var3 = I18nContextUtil.getBean(RecordSet.class);
        String poolname_kp = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        var3.executeSql("select companycode from e10_common.dbo.uf_eas_company where id = " + var1, poolname_kp);
        if (var3.next()) {
            var2 = Util.null2String(var3.getString("companycode"));
        }
        return var2;
    }

    public String gethsdwid(String var1) {
        String var2 = "";
        RecordSet var3 = I18nContextUtil.getBean(RecordSet.class);
        String poolname_vt = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        var3.executeSql("select oid from e10_common.dbo.uf_eas_company where id = " + var1, poolname_vt);
        if (var3.next()) {
            var2 = Util.null2String(var3.getString("oid"));
        }
        return var2;
    }

    public String gethsdwname(String var1) {
        String var2 = "";
        RecordSet var3 = I18nContextUtil.getBean(RecordSet.class);
        String poolname_jy = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        var3.executeSql("select companyname from e10_common.dbo.uf_eas_company where id = " + var1, poolname_jy);
        if (var3.next()) {
            var2 = Util.null2String(var3.getString("companyname"));
        }
        return var2;
    }

    public String getDepartmentcode(String var1) {
        String var2 = "";
        RecordSet var3 = I18nContextUtil.getBean(RecordSet.class);
        String poolname_bg = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        var3.executeSql("select code from eteams.dbo.department as  HrmDepartment where id = " + var1, poolname_bg);
        if (var3.next()) {
            var2 = Util.null2String(var3.getString("departmentcode"));
        }
        return var2;
    }

    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;
    }
}
