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

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import weaver.interfaces.eipoa.PortalPlanService;
//import weaver.interfaces.eipoa.SI_HTPortalPlan_OUTServiceStub.InsertPlan;
//import weaver.interfaces.swfa.BillFieldUtil;
//import weaver.interfaces.workflow.entity.Meeting;
//import weaver.meeting.Maint.MeetingRoomComInfo;
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 weaver.wxinterface.InterfaceUtil;
@org.springframework.stereotype.Service("workflow_action_PushMeetingAction")
public class PushMeetingAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    /*public String getWorkcode(String ids){
		String[] arr = ids.split(",");
		Set<String> list = new HashSet<String>();
		for(int i=0;i<arr.length;i++){
			if(!"".equals(arr[i])){
				list.add(util.getWorkcode(arr[i]));
			}
		}
		return StringUtils.join(list.toArray(),";");
	}*/
    public static final org.slf4j.Logger logger_88956bf8 = LoggerFactory.getLogger(PushMeetingAction.class);

//    private static ExecutorService pool = Executors.newFixedThreadPool(3);

    public PushMeetingAction() {
        logger_88956bf8.error(String.valueOf("PushMeetingAction---"));
    }

    /*	private static BillFieldUtil util = new BillFieldUtil();
	private static String systemId = "SYS006";
	private static String password = "123456";
	private static String type = "22";*/
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_88956bf8.error("PushMeetingAction 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 {

            //TODO custom 会议
//            Meeting m = new Meeting(request.getRequestid());
//            pool.execute(m);
            /*String requestid = request.getRequestid();
		writeLog("requestid:"+requestid);
		RecordSet rs = new RecordSet();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String url = Util.null2String(getPropValue("htportaloaUrl", "pc_url")).trim();
		String address = "";
		String contacter = "";
		List<String> sendList = new ArrayList<String>();
		try{
			String sql = "select top 1 m.ApproveID,t.name AS meetingtype,m.Contacter,m.MeetingName,m.address,m.customizeAddress,m.resources,m.BeginDate," +
					"m.BeginTime,m.EndDate,m.EndTime,m.description,L.operateuserid,L.operatedate,L.operatetime from bill_meeting m INNER JOIN Meeting_Type t " +
					"ON m.meetingtype = t.id inner join MeetingLog L on m.ApproveID = L.relatedid " +
					"where m.requestid="+requestid;
			rs.execute(sql);
			Map<String,String> map = new HashMap<String,String>();
			if(rs.next()){
				String id = Util.null2String(rs.getString("ApproveID"));
				String meetingtype = Util.null2String(rs.getString("meetingtype"));
				String name = Util.null2String(rs.getString("MeetingName"));
				contacter = Util.null2String(rs.getString("Contacter"));
				address = Util.null2String(rs.getString("address"));
				String customizeAddress = Util.null2String(rs.getString("customizeAddress"));
				String hrmmembers = Util.null2String(rs.getString("resources"));
				String begindate = Util.null2String(rs.getString("BeginDate"));
				String begintime = Util.null2String(rs.getString("BeginTime"));
				String enddate = Util.null2String(rs.getString("EndDate"));
				String endtime = Util.null2String(rs.getString("EndTime"));
				String creater = Util.null2String(rs.getString("operateuserid"));
				String createdate = Util.null2String(rs.getString("operatedate"));
				String createtime = Util.null2String(rs.getString("operatetime"));
				String description = Util.null2String(rs.getString("description"));
				String userId = getWorkcode(hrmmembers);
				String fromName = util.getName(creater);
				String fromWorkcode = util.getWorkcode(creater);
				String itemId = systemId+fromWorkcode+sdf.parse(createdate+" "+createtime.substring(0,5)+":00").getTime()+id;
				String location = "";
				sendList.add(contacter);
				if(!"".equals(address)){
					MeetingRoomComInfo info = new MeetingRoomComInfo();
					location = info.getMeetingRoomInfoname(address);
					writeLog("会议地点："+location);
				}else{
					location = customizeAddress;
				}
				map.put("id",id);
				map.put("userId",userId);
		        map.put("systemId",systemId);
		        map.put("password",password);
		        map.put("itemId",itemId);
		        map.put("title",name);
		        map.put("url",url+URLEncoder.encode(Util.null2String(getPropValue("htportaloaUrl", "meeting_url")).trim()+id ));
		        map.put("type",type);
		        map.put("startDate",begindate+" "+begintime+":00");
		        map.put("endDate",enddate+" "+endtime+":00");
		        map.put("status","0");
		        map.put("priority","0");
		        map.put("formName",fromName);
		        map.put("mobileUrl",url+URLEncoder.encode(Util.null2String(getPropValue("htportaloaUrl", "meeting_mobileUrl")).trim() +id));
		        map.put("category",meetingtype);
		        map.put("source","1");
		        map.put("content","会议地点："+location+"\r\n会议内容："+description);
			}

			if(!"".equals(address)){
				String[] str = address.split(",");
				for(int a=0;a<str.length;a++){
					int adr = Integer.parseInt(str[a]);
					if(adr<=9||(adr>=93&&adr<=97)||adr==166||adr==167){
						writeLog("开始微信提醒预约人："+getPropValue("remindforweixin","MeetingReminderStart"));
						InterfaceUtil.sendMsg(sendList, ",2a202436404f44368a0a7b50295d6273,", "", getPropValue("remindforweixin","MeetingReminderStart"), 3);
					}
				}
			}

			PortalPlanService service = new PortalPlanService();
			InsertPlan insertData= JSONObject.parseObject(JSON.toJSONString(map),InsertPlan.class);
			String[] str = service.insertPlan(insertData);
			writeLog("推送会议到门户结束--"+map.get("id")+"--"+str[1]);
		}catch(Exception e){
			writeLog("推送会议到门户失败--"+requestid+"--"+e.toString());
		}*/
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_88956bf8.error("PushMeetingAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "PushMeetingAction 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;
    }
}
