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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.easoa.EAS_YszxfpApplyResult;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
// import weaver.webservice.pojo.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.interfaces.workflow.action.Action;
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;

/**
 * oa->报账系统
 */
@org.springframework.stereotype.Service("workflow_action_EasYszxfpApplyResultAction")
public class EasYszxfpApplyResultAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private  EAS_YszxfpApplyResult mGetResult;
    private static final Logger logger_59285be7 = LoggerFactory.getLogger(EasYszxfpApplyResultAction.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 {
            String systemFlag = "OA";
            String requestID = "";
            String boeNum = "";
            String boeHeaderId = "";
            String tablename = "";
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            BillFieldUtil unit = new  com.weaver.seconddev.interfaces.swfa.BillFieldUtil();
            try {
                logger_59285be7.error(String.valueOf("EasYszxfpApplyResultAction--start--" + requestID));
                logger_59285be7.error("requestIdTemp == " +requestIdTemp);
                logger_59285be7.error("userIdTemp == " +userIdTemp);
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                String wfid = requestInfo.getWorkflowid();
//                tablename = unit.getTablename(wfid);
                tablename = requestInfo.getRequestManager().getBillTableName();
                String sql = "select id,sfdy from e10_core_business.dbo." + tablename + " where id =" + requestID;
                logger_59285be7.error("sql == " +sql);
                String poolname_l4 = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                rs.executeSql(sql, poolname_l4);
                if (rs.next()) {
                    int sfdy = rs.getInt("sfdy");
                    logger_59285be7.error("sfdy == " +sfdy);
                    if (sfdy == 0) {
                        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
                    } else {
                        String poolname_r6 = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        String sql2 = "update e10_core_business.dbo." + tablename + " set sfdy = 0 where id = " + requestID;
                        logger_59285be7.error("sql2 == " +sql2);
                        boolean b = rs.executeSql(sql2, poolname_r6);
                        logger_59285be7.error("b == " +b);
                    }
                }
                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);
                }
                boeNum = mMap.get("BOENUM");
                logger_59285be7.error(String.valueOf(requestID + "报账单号:" + boeNum));
                boeHeaderId = mMap.get("BOEHEADERID");
                logger_59285be7.error(String.valueOf(requestID + "报账单Id:" + boeHeaderId));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                JSONArray mJSONArray = new JSONArray();
                BillFieldUtil util = new BillFieldUtil();
                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);
                    }
                    logger_59285be7.error(String.valueOf(requestID + "TAXRATE:" + mDetailMap.get("TAXRATE")));
                    // 测试环境-63588,正式环境-68112
                    String selectitem = util.getselectName(mDetailMap.get("TAXRATE"), "100003720000068112");
                    logger_59285be7.error(String.valueOf(requestID + "selectitem:" + selectitem));
                    String taxrate = selectitem.substring(0, selectitem.indexOf("%"));
                    if ("0".equals(taxrate)) {
                        taxrate = "0";
                    } else {
                        taxrate = new Float(taxrate) / 100 + "";
                    }
                    // 发票代码
                    item.put("invoiceCode", mDetailMap.get("INVOICECODE"));
                    // 发票号
                    item.put("invoiceNum", mDetailMap.get("INVOICENUM"));
                    // 发票票面含税金额
                    item.put("invoiceAmount", mDetailMap.get("INVOICEAMOUNT"));
                    // 税额
                    item.put("taxAmount", mDetailMap.get("TAXAMOUNT"));
                    // 未税金额
                    item.put("noTaxAmount", mDetailMap.get("NOTAXAMOUNT"));
                    logger_59285be7.error(String.valueOf(requestID + "noTaxAmount:" + mDetailMap.get("NOTAXAMOUNT")));
                    String typeStr = mDetailMap.get("INVOICETYPE");
                    String invoiceType = "";
                    if ("0".equals(typeStr)) {
                        // 增值税专用发票
                        invoiceType = "01";
                    } else if ("1".equals(typeStr)) {
                        // 机动车销售统一发票
                        invoiceType = "03";
                    } else if ("2".equals(typeStr)) {
                        // 增值税普通发票
                        invoiceType = "04";
                    } else if ("3".equals(typeStr)) {
                        // 增值税普通发票(电子)
                        invoiceType = "10";
                    } else if ("4".equals(typeStr)) {
                        // 增值税普通发票(卷式)
                        invoiceType = "11";
                    } else if ("5".equals(typeStr)) {
                        // 增值税电子普通发票[通行费]
                        invoiceType = "14";
                    } else if ("6".equals(typeStr)) {
                        // 增值税普通发票（全电）
                        invoiceType = "08xdpp";
                    } else if ("7".equals(typeStr)) {
                        // 增值税普通专票（全电）
                        invoiceType = "08xdp";
                    }
                    // 发票类型
                    item.put("invoiceType", invoiceType);
                    // 税率
                    item.put("taxRate", taxrate);
                    // 开票日期
                    item.put("invoiceDate", mDetailMap.get("INVOICEDATE"));
                    mJSONArray.add(item);
                }
                logger_59285be7.error(String.valueOf(requestID + "获取明细表数据结束"));
                JSONObject mJson = new JSONObject();
                mJson.put("systemFlag", systemFlag);
                mJson.put("boeNum", boeNum);
                mJson.put("requestId", requestID);
                mJson.put("boeHeaderId", boeHeaderId);
                mJson.put("ITFID", "HT01BZ032");
                mJson.put("items", mJSONArray);
//                EAS_YszxfpApplyResult mGetResult = new EAS_YszxfpApplyResult();
                logger_59285be7.error(requestID + " " + mJson.toString());
                String result = mGetResult.getApproveResult(mJson, "EasYszxfpApplyResult");
                logger_59285be7.error(String.valueOf(requestID + "调用报账系统应收折现发票申请接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，E-失败
                    String isTat = jsonObject.getString("istat");
                    // 处理消息
                    String srMessage = jsonObject.getString("srmsage");
                    if (!"S".equals(isTat)) {
                        String poolname_so = CONN_TYPE.workflow.getType();
                        // 失败
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        String sql3 = "update e10_core_business.dbo." + tablename + " set sfdy = 1 where id = " + requestID;
                        logger_59285be7.error("sql3"+sql3);
                        boolean b = rs.executeSql(sql3, poolname_so);
                        logger_59285be7.error("b2"+b);
                        logger_59285be7.error(String.valueOf(requestID + "报账系统返回错误信息：" + srMessage));
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                        return  WeaResult.fail(500, "报账系统返回错误信息：" + srMessage, getResultMapForAction(weaverResultMap, "result", "报账系统返回错误信息：" + srMessage, requestInfo.getRequestManager()));
                    }
                } else {
                    String poolname_b5 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    String sql4 = "update e10_core_business.dbo." + tablename + " set sfdy = 1 where id = " + requestID;
                    logger_59285be7.error("sql4"+sql4);
                    boolean b = rs.executeSql(sql4, poolname_b5);
                    logger_59285be7.error("b3"+b);
                }
            } catch (Exception e) {
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                String sql5 = "update e10_core_business.dbo." + tablename + " set sfdy = 1 where id = " + requestID;
                logger_59285be7.error("sql5"+sql5);
                boolean b = rs.executeSql(sql5, poolname);
                logger_59285be7.error("b4"+b);
                logger_59285be7.error(String.valueOf(requestID + "调用报账系统应收折现发票申请接口出错：" + e.toString()));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("调用报账系统应收折现发票申请接口返回失败，请联系报账系统管理员！");
                return  WeaResult.fail(500, requestID + "调用报账系统应收折现发票申请接口出错：" + e.toString(), getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));

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