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

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

import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.interfaces.easoa.CallEasServices;
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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * 报账单付款冻结申请  提交OA流程requestId：1362923
 */
@org.springframework.stereotype.Service("workflow_action_EasQuerySourceBoeNumAction")
public class EasQuerySourceBoeNumAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private CallEasServices services;

    private static final Logger logger_3c7e784f = LoggerFactory.getLogger(EasQuerySourceBoeNumAction.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 {
            logger_3c7e784f.error(String.valueOf("do EasQuerySourceBoeNumAction on request:" + request.getRequestid()));
            logger_3c7e784f.error("requestIdTemp == " +requestIdTemp);
            logger_3c7e784f.error("userIdTemp == " +userIdTemp);
            try {
                // 获取主表数据
                // 申请类型 	1供应商、2报账单
                String type1 = "";
                // 操作类型  	Y冻结、N解冻
                String type2 = "";
                Property[] aproperty = request.getMainTableInfo().getProperty();
                for (int i = 0; i < aproperty.length; i++) {
                    String name = aproperty[i].getName().toUpperCase();
                    String value = Util.null2String(aproperty[i].getValue());
                    if (name.equals("TYPE1")) {
                        // 申请类型
                        type1 = value;
                        logger_3c7e784f.error(String.valueOf("得到申请类型" + type1));
                    }
                    if (name.equals("TYPE2")) {
                        // 申请类型
                        type2 = value;
                        logger_3c7e784f.error(String.valueOf("得到操作类型" + type2));
                    }
                }
                // 获取明细表
                logger_3c7e784f.error(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                // 指定明细表
                DetailTable dtq = detailtable[0];
                // 当前明细表的所有数据,按行存储
                Row[] sq = dtq.getRow();
                String[] bzdhArray = new String[sq.length];
                String[] lxArray = new String[sq.length];
                String[] djjeArray = new String[sq.length];
                String[] gysidArray = new String[sq.length];
                String[] gsidArray = new String[sq.length];
                String[] sfhmdArray = new String[sq.length];
                logger_3c7e784f.error(String.valueOf("For循环开始校验"));
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        // 明细字段的值
                        String valueq = Util.null2String(cq1.getValue());
                        if (nameq.equals("BZDH")) {
                            // 报账单号
                            String bzdh = valueq.trim();
                            bzdhArray[j] = bzdh;
                            logger_3c7e784f.error(String.valueOf("报账单号：" + bzdh));
                        }
                        if (nameq.equals("LX")) {
                            // 类型
                            String lx = valueq.trim();
                            lxArray[j] = lx;
                            logger_3c7e784f.error(String.valueOf("类型：" + lx));
                        }
                        if (nameq.equals("DJJE")) {
                            // 冻结金额
                            String djje = valueq.trim();
                            djjeArray[j] = djje;
                            logger_3c7e784f.error(String.valueOf("冻结金额：" + djje));
                        }
                        if (nameq.equals("GSDM")) {
                            // 公司代码
                            String gsdm = valueq.trim();
                            logger_3c7e784f.error(String.valueOf("公司代码：" + gsdm));
                        }
                        if (nameq.equals("GSMC")) {
                            // 公司名称
                            String gsmc = valueq.trim();
                            logger_3c7e784f.error(String.valueOf("公司名称：" + gsmc));
                        }
                        if (nameq.equals("GSID")) {
                            // 公司名称
                            String gsid = valueq.trim();
                            gsidArray[j] = gsid;
                            logger_3c7e784f.error(String.valueOf("公司ID：" + gsid));
                        }
                        if (nameq.equals("GYSDM")) {
                            // 供应商代码
                            String gysdm = valueq.trim();
                            logger_3c7e784f.error(String.valueOf("供应商代码：" + gysdm));
                        }
                        if (nameq.equals("GYSMC")) {
                            // 供应商名称
                            String gysmc = valueq.trim();
                            logger_3c7e784f.error(String.valueOf("供应商名称：" + gysmc));
                        }
                        if (nameq.equals("GYSID")) {
                            // 供应商id
                            String gysid = valueq.trim();
                            gysidArray[j] = gysid;
                            logger_3c7e784f.error(String.valueOf("供应商id：" + gysid));
                        }
                        if (nameq.equals("SFHMD")) {
                            // 是否黑名单
                            String check = valueq.trim();
                            sfhmdArray[j] = check;
                            logger_3c7e784f.error(String.valueOf("是否黑名单：" + check));
                        }
                    }
                }
                String status = "";
                String msg = "";
                // 检验单据或者供应商的有效性
//                CallEasServices services = new CallEasServices();
                String[] result = null;
                logger_3c7e784f.error(String.valueOf("type1：" + type1));
                logger_3c7e784f.error(String.valueOf("type2：" + type2));
                if ("2".equals(type1) && "Y".equals(type2)) {
                    // 报账单 冻结
                    for (int i = 0; i < bzdhArray.length; i++) {
                        if (("0".equals(lxArray[i]) && !"0.00".equals(djjeArray[i])) || ("1".equals(lxArray[i]) && "0.00".equals(djjeArray[i]))) {
                            status = "F";
                            msg = "部分冻结金额需大于0，整单冻结金额为0！";
                            break;
                        }
                    }
                    if (!"F".equals(status)) {
                        result = services.querySourceBoeNum(bzdhArray, lxArray, djjeArray);
                        status = result[0];
                        msg = result[1];
                    }
                } else {
                    if ("2".equals(type1)) {
                        List<String> bzdhList = new ArrayList<String>();
                        List<String> gsidList = new ArrayList<String>();
                        for (int i = 0; i < sfhmdArray.length; i++) {
                            if ("1".equals(sfhmdArray[i])) {
                                if ("".equals(djjeArray[i])) {
                                    bzdhList.add(bzdhArray[i]);
                                    gsidList.add(gsidArray[i]);
                                } else {
                                    status = "F";
                                    msg = "不是黑名单时，可支付金额为空";
                                    break;
                                }
                            }
                        }
                        String[] bzdhArr = new String[bzdhList.size()];
                        bzdhArr = bzdhList.toArray(bzdhArr);
                        String[] gsidArr = new String[gsidList.size()];
                        gsidArr = gsidList.toArray(gsidArr);
                        logger_3c7e784f.error(String.valueOf("bzdhArr:" + bzdhArr.length + "--gsidArr:" + gsidArr.length));
                        if (!"F".equals(status) && (bzdhArr.length > 0)) {
                            result = services.queryPayControlStatus(type1, bzdhArr, type2, gsidArr);
                            status = result[0];
                            msg = result[1];
                        }
                    } else {
                        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                        for (int n = 0; n < gysidArray.length; n++) {
                            String sql = "select v.id,oid from e10_common.dbo.uf_eas_vendor v INNER JOIN e10_common.dbo.uf_eas_company c on v.companyId=c.oid where v.vendorId='" + gysidArray[n] + "'";
                            logger_3c7e784f.error("EasQuerySourceBoeNumAction sql"+sql);
                            String poolname = CONN_TYPE.workflow.getType();
                            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                            boolean b = rs.executeSql(sql, poolname);
                            logger_3c7e784f.error(String.valueOf("b:" + b));
                            String oid = "";
                            while (rs.next()) {
                                oid = rs.getString("oid");
                            }
                            if (!oid.equals(gsidArray[n])) {
                                status = "F";
                                msg = "公司和供应商不对应，请修改！";
                                break;
                            }
                        }
                        if (!"F".equals(status)) {
                            result = services.queryPayControlStatus(type1, gysidArray, type2, gsidArray);
                            status = result[0];
                            msg = result[1];
                        }
                    }
                }
                logger_3c7e784f.error(String.valueOf("EasQuerySourceBoeNumAction result status：" + status + " , msg:" + msg));
                if ("F".equals(status)) {
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("报账系统返回信息：" + msg);
                    return  WeaResult.fail(500, "报账系统返回信息：" + msg, getResultMapForAction(weaverResultMap, "result", "报账系统返回信息：" + msg, request.getRequestManager()));

                }
            } catch (Exception e) {
                logger_3c7e784f.error(String.valueOf("error : " + e.getMessage()));
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent("报账系统返回信息：" + e.toString());
                return  WeaResult.fail(500, "报账系统返回信息："+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_3c7e784f.error("EasQuerySourceBoeNumAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "EasQuerySourceBoeNumAction 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;
    }
}
