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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import org.springframework.core.env.Environment;
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.docs.webservices.DocAttachment;
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;

/**
 * 电子档案借阅审批流程--借阅审批回调接口
 * 接口账号密码：测试环境--hengtong/abc,,,123   正式环境--htefs/efs2@2@@9!@HT
 */
@org.springframework.stereotype.Service("workflow_action_EAS_DZDAApproveAction")
public class EAS_DZDAApproveAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_3f787449 = LoggerFactory.getLogger(EAS_DZDAApproveAction.class);

    @Autowired
    BillFieldUtil unit;
    @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 = "";
            /**
             * 系统标识*
             */
            String SYSID = "OA";
            /**
             * 接口ID*
             */
            String ITFID = "HTEFS002";
            // 接口账号
            String USERNAME = configProp.getEfsaccount();
            // 接口密码
            String PASSWORD = configProp.getEfspassword();
            // 审批者工号
            String approvalBy = "";
            // 审批时间
            String approvalDate = "";
            // 审批状态
            String approvalStatus = "";
            // 计划归还日期
            String revisedPlanReturnDate = "";
            try {
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_3f787449.error(String.valueOf("EAS_DZDAApproveAction--start--" + requestID));
                String lastopertorid = requestInfo.getLastoperator();
                approvalBy = unit.getWorkcode(lastopertorid);
                logger_3f787449.error(String.valueOf("--lastoperatorid--" + lastopertorid + "||approvalBy=" + approvalBy));
                approvalDate = getCurrentDate();
                logger_3f787449.error(String.valueOf("--approvalDate--" + approvalDate));
                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);
                }
                approvalStatus = mMap.get("STATUS");
                logger_3f787449.error(String.valueOf("审批状态：" + approvalStatus));
                if (approvalStatus == null || approvalStatus.equals("")) {
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
                }
                revisedPlanReturnDate = mMap.get("YJGHRQ");
                logger_3f787449.error(String.valueOf("计划归还日期：" + revisedPlanReturnDate));
                if (revisedPlanReturnDate != null && !revisedPlanReturnDate.equals("")) {
                    revisedPlanReturnDate = revisedPlanReturnDate.replaceAll("-", "");
                }
                if (approvalDate != null && !approvalDate.equals("")) {
                    approvalDate = approvalDate.replaceAll("-", "");
                }
                JSONObject mJson = new JSONObject();
                mJson.put("USERNAME", USERNAME);
                mJson.put("PASSWORD", PASSWORD);
                // 系统标识
                mJson.put("ITFID", ITFID);
                mJson.put("requestId", requestID);
                mJson.put("SYSID", SYSID);
                mJson.put("approvalStatus", approvalStatus);
                // revisedPlanReturnDate
                mJson.put("revisedPlanReturnDate", revisedPlanReturnDate);
                mJson.put("approvalBy", approvalBy);
                mJson.put("approvalDate", approvalDate);
                String errorMsg = "";
                if ("Y".equals(approvalStatus)) {
                    logger_3f787449.error(String.valueOf("明细表开始取值"));
                    DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                    // ===========凭证明细==============//
                    DetailTable dtq = detailtable[0];
                    Row[] sq = dtq.getRow();
                    JSONArray receiptVOListArr = 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);
                        }
                        String jynr = mDetailMap.get("JYNR");
                        String zt = mDetailMap.get("ZT");
                        if ("0".equals(zt)) {
                            // 状态
                            item.put("status", "Y");
                        } else {
                            // 状态
                            item.put("status", "N");
                        }
                        // 1：一份文件 2：一册文件
                        item.put("borrowType", (Integer.parseInt(jynr) + 1) + "");
                        // 借阅单据号
                        item.put("receiptNO", mDetailMap.get("JYDJH"));
                        receiptVOListArr.add(item);
                    }
                    mJson.put("receiptVOList", receiptVOListArr);
                    logger_3f787449.error(String.valueOf("获取明细表数据结束"));
                }
                logger_3f787449.error("调用借阅审批回调接口请求数据：=====" + mJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.uploadDZDAApprovelUrl")).trim();
                String url = configProp.getUploadDZDAApprovelUrl();
                ZZ_SendPostRequest mGetResult = new ZZ_SendPostRequest();
                String result = mGetResult.getResult(mJson, url);
                logger_3f787449.error(String.valueOf("调用借阅审批回调接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，F-失败
                    String isTat = jsonObject.getString("status");
                    // 处理消息
                    String srMessage = jsonObject.getString("message");
                    logger_3f787449.error("报账系统返回数据：" + jsonObject.toString());
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_3f787449.error(String.valueOf("报账系统返回错误信息：" + srMessage));
                        // requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                        return WeaResult.fail(500, "执行失败:"+srMessage, getResultMapForAction(weaverResultMap, "result", FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                    }
                } else {
                    logger_3f787449.error(String.valueOf("调用借阅审批回调接口返回失败，请联系报账系统管理员！"));
                    // requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用借阅审批回调接口返回失败，请联系报账系统管理员！");
                    return WeaResult.fail(500, "调用借阅审批回调接口返回失败，请联系报账系统管理员！", getResultMapForAction(weaverResultMap, "result", FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                }
            } catch (Exception e) {
                logger_3f787449.error(String.valueOf("提交失败！"));
                logger_3f787449.error(String.valueOf("Error======" ), e);
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, "提交失败！"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_3f787449.error("EAS_DZDAApproveAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "EAS_DZDAApproveAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    public String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public long getCurrentDate_long() {
        Date currentTime = new Date();
        return currentTime.getTime();
    }

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