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

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import com.weaver.seconddev.interfaces.prop.ConfigProp;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.eipoa.PortalPlanService;
import  com.weaver.seconddev.interfaces.eipoa.SI_HTPortalPlan_OUTServiceStub.InsertPlan;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
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.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.company.SubCompanyComInfo;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

@org.springframework.stereotype.Service("workflow_action_CarApplyInfoAction")
public class CarApplyInfoAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private  PortalPlanService service;
    private static final Logger logger_4411f79d = LoggerFactory.getLogger(CarApplyInfoAction.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 requestid = requestinfo.getRequestid();
            String workflowid = requestinfo.getWorkflowid();
            try {
                logger_4411f79d.error(String.valueOf(requestid + "-CarApplyInfoAction-start"));
                Map<String, String> map = new HashMap<String, String>();
                Property[] properties = requestinfo.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    map.put(name, value);
                }
                BillFieldUtil util = new BillFieldUtil();
                SubCompanyComInfo com = I18nContextUtil.getBean(SubCompanyComInfo.class);
                ResourceComInfo res = I18nContextUtil.getBean(ResourceComInfo.class);
                String startDate = map.get("CFRQ") + " " + map.get("CFSJ") + ":00";
                String endDate = map.get("DDRQ") + " " + map.get("YJFHSJ") + ":59";
                String sqr = map.get("SQR");
//                String title = com.getSubCompanyname(map.get("SQDW")) + "，" + res.getLastnames(map.get("CCRY")) + "，" + util.getselectName(map.get("PCFS"), Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htportaloaUrl.YC_pcfsid")).trim());
                String title = com.getSubCompanyname(map.get("SQDW")) + "，" + res.getLastnames(map.get("CCRY")) + "，" + util.getselectName(map.get("PCFS"), configProp.getYC_pcfsid());
                // 测试环境-"61279"，正式环境-Util.null2String(this.getPropValue("htportaloaUrl", "YC_pcfsid")).trim()
                title = title + "，" + map.get("CFDD") + " 至 " + map.get("MDDD");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String itemId = "SYS006" + util.getWorkcode(sqr) + sdf.parse(map.get("SQRQ") + " 08:00:00").getTime() + requestid;
                String fromName = util.getName(sqr);
                String ccry = map.get("CCRY");
                // 测试环境-102，正式环境-42
                String type = "42";
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htportaloaUrl.pc_url")).trim();
                String url = configProp.getPc_url();
                StringBuilder content = new StringBuilder();
                content.append("行程：" + map.get("CFDD") + " 至 " + map.get("MDDD") + "；\r\n");
                String pc_url = "/workflow/request/ViewRequest.jsp?requestid=" + requestid + "&_workflowid=" + workflowid + "&_workflowtype=&isovertime=0";
                String mobile_url = "/mobile/plugin/1/view.jsp?requestid=" + requestid + "&_workflowid=" + workflowid + "&_workflowtype=&isovertime=0";
                String otherids = "";
                if ("0".equals(map.get("YCYQ"))) {
//                    otherids = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htportaloaUrl.YC_WJYQTZR")).trim();
                    otherids = configProp.getYC_WJYQTZR();
                } else if ("1".equals(map.get("YCYQ"))) {
//                    otherids = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htportaloaUrl.YC_QDYQTZR")).trim();
                    otherids = configProp.getYC_QDYQTZR();
                } else if ("2".equals(map.get("YCYQ"))) {
//                    otherids = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htportaloaUrl.YC_CSYQTZR")).trim();
                    otherids = configProp.getYC_CSYQTZR();
                }
                String userid = "";
                if (!"".equals(otherids)) {
                    userid = getWorkcode(sqr + "," + ccry + "," + otherids, util);
                } else {
                    userid = getWorkcode(sqr + "," + ccry, util);
                }
                Map<String, String> info = new HashMap<String, String>();
                info.put("systemId", "SYS006");
                info.put("password", "123456");
                info.put("itemId", itemId);
                info.put("userId", userid);
                info.put("title", title);
                info.put("url", url + URLEncoder.encode(pc_url));
                info.put("type", type);
                info.put("startDate", startDate);
                info.put("endDate", endDate);
                info.put("status", "0");
                info.put("priority", "0");
                info.put("formName", fromName);
                info.put("mobileUrl", url + URLEncoder.encode(mobile_url));
                info.put("category", "用车");
                info.put("source", "1");
                info.put("content", content.toString());
//                PortalPlanService service = new PortalPlanService();
                InsertPlan insertData = JSONObject.parseObject(JSON.toJSONString(info), InsertPlan.class);
                String[] str = service.insertPlan(insertData);
                logger_4411f79d.error(requestid + "-CarApplyInfoAction-传值[" + JSON.toJSONString(info) + "]");
                logger_4411f79d.error(String.valueOf(requestid + "-CarApplyInfoAction-end-返回值：[" + str[0] + "-" + str[1] + "]"));
            } catch (Exception e) {
                logger_4411f79d.error(String.valueOf(requestid + "-CarApplyInfoAction-error:" + e.toString()));
                return  WeaResult.fail(500, requestid + "-CarApplyInfoAction-error:" + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestinfo.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestinfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_4411f79d.error("CarApplyInfoAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "CarApplyInfoAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestinfo.getRequestManager()));
        }
    }

    public String getWorkcode(String ids, BillFieldUtil util) {
        String[] arr = ids.split(",");
        HashSet<String> set = new HashSet<String>();
        for (int i = 0; i < arr.length; i++) {
            if (!"".equals(arr[i])) {
                set.add(util.getWorkcode(arr[i]));
            }
        }
        return StringUtils.join(set.toArray(), ";");
    }

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