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

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.Date;
import com.weaver.seconddev.interfaces.htjt.util.LogUtil;
import  com.weaver.seconddev.interfaces.srmoa.*;
import  com.weaver.seconddev.interfaces.swfa.*;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
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.conn.RecordSetDataSource;
import com.weaver.verupgrade.general.TimeUtil;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.interfaces.workflow.action.Action;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;

/**
 * SRM--比价单审批接口--qingf20170313
 * @author Administrator
 */
@org.springframework.stereotype.Service("workflow_action_OaSrmCheckPriceRefuseAction")
public class OaSrmCheckPriceRefuseAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_80563c68 = LoggerFactory.getLogger(OaSrmCheckPriceRefuseAction.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_80563c68.error("OaSrmCheckPriceRefuseAction start");
        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 {
            LogUtil logUtil = new LogUtil();
            String requestId = "";
            try {
                int reqid = 0;
                // 流程编号
                String lcbh = "";
                // 询价单ID
                String enquiryid = "";
                // 审核人
                String shr = "";
                // 审核意见
                String shyj = "";
                // 审核日期
                String shrq = "2016-11-13";
                // 审核时间
                String shsj = "12:00:00";
                // 1批准、-1驳回
                int shzt = -1;
                // String zt = "1"; //1批准、-1驳回
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                Date now = new Date();
                SimpleDateFormat datetype = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat timetype = new SimpleDateFormat("HH:mm:ss");
                shrq = datetype.format(now);
                shsj = timetype.format(now);
                // 流程请求ID
                requestId = request.getRequestid();
                lcbh = requestId;
                shyj = request.getRequestManager().getRemark();
                shr = hr.getResourcename(String.valueOf(userIdTemp));
                String requestName = request.getRequestManager().getRequestname();
                // 获取工作流程Workflowid的值
                String workflowID = request.getWorkflowid();
                logUtil.setJklm("OaSrmCheckPriceRefuseAction");
                logUtil.setLx("1");
                logUtil.setBt(requestName);
                logUtil.setLcid(requestId);
                logUtil.setLclxid(workflowID);
                logger_80563c68.error(String.valueOf("OaSrmCheckPriceRefuseAction-Request: " + requestId + "开始"));
                RfqCheckPriceHandlerServiceServiceStub.CheckPriceResultIn resultin = new RfqCheckPriceHandlerServiceServiceStub.CheckPriceResultIn();
                // 封装单据主信息
                // 封装表单信息
                // 获取表单主字段信息
                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("lcbh")) {
                        if (!value.equals("")) {
                            // 流程编号
                            lcbh = value;
                        }
                    }
                    if (name.equals("enquiryid")) {
                        // 询价单ID
                        enquiryid = value;
                    }
                }
                try {
                    reqid = Integer.parseInt(requestId);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                if (shyj.length() > 100) {
                    shyj = shyj.trim().substring(0, 100);
                }
                resultin.setRequestId(reqid);
                resultin.setEnquiryId(enquiryid);
                resultin.setCheckUserName(shr);
                resultin.setCheckStatus(shzt);
                resultin.setCheckRearks(shyj);
                // writeLog("调用接口开始0 ");
                logger_80563c68.error(String.valueOf("调用接口完成RequestId--" + requestId + "--enquiryid--" + enquiryid + "--shr--" + shr + "--shzt--" + shzt + "--shyj--" + shyj + "--shrq--" + shrq + shsj));
                logUtil.setTscs("RequestId--" + requestId + "--enquiryid--" + enquiryid + "--shr--" + shr + "--shzt--" + shzt + "--shyj--" + shyj + "--shrq--" + shrq + shsj);
                String sta = "";
                String meg = "";
//                CallSrmCheckPriceServices srm = new CallSrmCheckPriceServices();
                srm.setOainput(resultin);
                String[] rtInfo = srm.call();
                logger_80563c68.error(String.valueOf("调用接口完成RequestId--" + rtInfo[0] + "--Istat--" + rtInfo[1] + "--Srmsage--" + rtInfo[2]));
                logUtil.setFhxx("RequestId--" + rtInfo[0] + "--Istat--" + rtInfo[1] + "--Srmsage--" + rtInfo[2]);
                sta = rtInfo[1];
                meg = rtInfo[2].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_80563c68.error(String.valueOf("logsql:" + logsql));
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(logsql, poolname);
                logger_80563c68.error(String.valueOf("b:" + b));
                logger_80563c68.error(String.valueOf("OaSrmCheckPriceRefuseAction-Request: " + requestId + "完成"));
                if (!sta.equals("S")) {
                    logUtil.setJkzt("1");
                    logUtil.insertLog();
                    request.getRequestManager().setMessageid("ERROR:");
                    request.getRequestManager().setMessagecontent("回写srm失败：" + meg);
                    return  WeaResult.fail(500, "OaSrmCheckPriceRefuseAction err"+ meg, getResultMapForAction(weaverResultMap, "result",meg, request.getRequestManager()));
                }
            } catch (Exception e) {
                logUtil.setJkzt("2");
                logUtil.setFhxx(logUtil.getFhxx() + e.getMessage());
                logUtil.insertLog();
                logger_80563c68.error(requestId + " error:" , e);
                logger_80563c68.error(String.valueOf(e));
                request.getRequestManager().setMessagecontent("回写srm失败，接口异常请联系管理员");
                request.getRequestManager().setMessageid("ERROR:");
                return  WeaResult.fail(500, "OaSrmCheckPriceRefuseAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_80563c68.error("OaSrmCheckPriceRefuseAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaSrmCheckPriceRefuseAction 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;
    }
}
