/*
 *
 * Copyright (c) 2001-2016 泛微软件.
 * 泛微协同商务系统,版权所有.
 *
 */
package com.engine.meeting.cmd.meetingmobilevideo;

import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.api.browser.util.MobileJsonConfigUtil;
import com.api.browser.util.MobileShowTypeAttr;
import com.api.meeting.util.FieldUtil;
import com.api.meeting.util.MeetingSearchConditionUtil;
import com.api.workplan.util.WorkPlanUtil;
import com.cloudstore.dev.api.bean.SplitMobileDataBean;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.PageIdConst;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.meeting.MeetingShareUtil;
import weaver.meeting.defined.MeetingFieldComInfo;
import weaver.meeting.search.SearchComInfo;
import weaver.meeting.video.util.VideoMeetingUtil;
import weaver.systeminfo.SystemEnv;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 获取视频会议未开始的数据
 *
 * @author yp
 */
public class GetMeetingInfoCmd extends AbstractCommonCommand<Map<String, Object>> {

    public GetMeetingInfoCmd(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;

    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map apidatas = new HashMap();
        VideoMeetingUtil vmt = new VideoMeetingUtil();
        String videomtname = "";
        String oaMtid = "";
        String mtpassword = "";
        String hrmids = "";
        String videoparties = "";//会议方数
        String videomtbegindate = "";
        String videomtenddate = "";
        String videomtcreater = "";
        String manufacturers = "";//视频会议记录厂商
        String manu = "";//当前使用厂商
        String videomtjoinurl = "";
        String videomtstarturl = "";
        String videomtid = "";
        String usePswd = "1";
        String frommould = "";
        String mouldkey = "";
        int viewattr = 3;
        int pwdViewAttr = 2;
        String type = Util.null2String(params.get("type"));
        String client = Util.null2String(params.get("client"));
        String _ec_os = Util.null2String(params.get("_ec_os"));//移动端os类型
        String ismobile = Util.null2String(params.get("ismobile"));//是否伟移动端请求
        String realMeetingId = Util.null2String(params.get("realMeetingId"));
        if("history".equals(type) || "view".equals(type)|| "invite".equals(type)){
            viewattr = 1;
            pwdViewAttr = 1;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String id = Util.null2String(params.get("id"));
        RecordSet recordSet = new RecordSet();
        //看下是不是从会议模块过来的，是的话，取一下会议模块的数据
        if("emobile_meeting".equals(client)){
            if(StringUtils.isNotBlank(realMeetingId)){
                recordSet.executeQuery("select * from meeting where id = ?",realMeetingId);
                if(recordSet.next()){
                    videomtname = Util.null2String(recordSet.getString("name"));
                    hrmids = Util.null2String(recordSet.getString("hrmmembers"));
                    videomtbegindate = Util.null2String(recordSet.getString("begindate"))+" "+Util.null2String(recordSet.getString("begintime"));
                    videomtenddate = Util.null2String(recordSet.getString("enddate"))+" "+Util.null2String(recordSet.getString("endtime"));
                }
            }
        }
        if(StringUtils.isNotBlank(realMeetingId)){
            recordSet.executeQuery("select * from meeting_videolist where videomtstatus in (0,1) and frommould = ? and mouldkey = ? ", "MEETING", realMeetingId);
            if (recordSet.next()) {
                id = Util.null2String(recordSet.getString("id"));
            }
        }
        recordSet.executeQuery("select * from meeting_videolist where id = ?", id);
        if (recordSet.next()) {
            videomtname = Util.null2String(recordSet.getString("videomtname"));
            oaMtid = Util.null2String(recordSet.getString("oaMtid"));
            mtpassword = Util.null2String(recordSet.getString("mtpassword"));
            hrmids = Util.null2String(recordSet.getString("hrmids"));
            videoparties = Util.null2String(recordSet.getString("videoparties"));
            videomtbegindate = Util.null2String(recordSet.getString("videomtbegindate"));
            videomtenddate = Util.null2String(recordSet.getString("videomtenddate"));
            videomtcreater = Util.null2String(recordSet.getString("videomtcreater"));
            manufacturers = Util.null2String(recordSet.getString("manufacturers"));
            videomtjoinurl = Util.null2String(recordSet.getString("videomtjoinurl"));
            videomtstarturl = Util.null2String(recordSet.getString("videomtstarturl"));
            usePswd = Util.null2String(recordSet.getString("usePswd"),"1");
            frommould = Util.null2String(recordSet.getString("frommould"));
            mouldkey = Util.null2String(recordSet.getString("mouldkey"));
            videomtid = Util.null2String(recordSet.getString("videomtid"));
            if(isJson(mtpassword)){
                JSONObject jsonObject = JSONObject.fromObject(mtpassword);
                if(user.getUID() == Util.getIntValue(videomtcreater)){
                    mtpassword = jsonObject.getString("chair_pwd");
                }else{
                    mtpassword = jsonObject.getString("general_pwd");
                }
            }
        }

        if("InfowareLab".equals(manufacturers) && "1".equals(ismobile)){//特殊处理红杉树会议链接
            videomtstarturl = vmt.getHSSLinkUrl(user.getUID()+"",_ec_os,videomtid,mtpassword,true);
            videomtjoinurl = vmt.getHSSLinkUrl(user.getUID()+"",_ec_os,videomtid,mtpassword,false);
        }


        boolean isCreater =false;
        boolean isHrm = false;
        boolean isInvite = type.equals("invite");
        if(user.getUID() == Util.getIntValue(videomtcreater)){
            isCreater = true;
        }else if((","+hrmids+",").contains(","+user.getUID()+",")){
            isHrm = true;
        }
        ResourceComInfo resourceComInfo = null;
        try {
            resourceComInfo = new ResourceComInfo();
        }catch (Exception e){
            e.printStackTrace();
        }

        if("quick".equals(type)){
            videomtname = SystemEnv.getHtmlLabelName(525787,user.getLanguage()).replace("${lastname}",resourceComInfo.getResourcename(user.getUID()+""));
        }

        List<Map<String, Object>> grouplist = new ArrayList<Map<String, Object>>();
        Map<String, Object> groupitem = new HashMap<String, Object>();
        List itemlist = new ArrayList();

        Map nameMap = FieldUtil.getFormItemForInput("videomtname", SystemEnv.getHtmlLabelName(2151, user.getLanguage()), videomtname, viewattr);
        nameMap.put("fieldcol", 14);
        nameMap.put("rules", "required");
        itemlist.add(nameMap);

        Map videomtbegindateMap = FieldUtil.getFormItemForDate("videomtbegindate", SystemEnv.getHtmlLabelName(742, user.getLanguage()), videomtbegindate, viewattr, true);
        videomtbegindateMap.put("rules", "required");
        itemlist.add(videomtbegindateMap);

        Map videomtenddateMap = FieldUtil.getFormItemForDate("videomtenddate", SystemEnv.getHtmlLabelName(743, user.getLanguage()), videomtenddate, viewattr, true);
        videomtenddateMap.put("rules", "required");
        itemlist.add(videomtenddateMap);

        if(!"order".equals(type)){
            Map videomtidMap = FieldUtil.getFormItemForInput("oaMtid", SystemEnv.getHtmlLabelName(525536, user.getLanguage()), oaMtid, viewattr);
            videomtidMap.put("fieldcol", 14);
            videomtidMap.put("rules", "required");
            itemlist.add(videomtidMap);
        }

        RecordSet rs = new RecordSet();
        rs.executeQuery("SELECT * FROM meeting_videoset WHERE keyname = 'manufacturers'");
        if(rs.next()){
            manu = Util.null2String(rs.getString("keyvalue"));
        }
//
//        if("order".equals(type) || "edit".equals(type)){
//            Map mtMap = FieldUtil.getFormItemForSwitch("usePswd", SystemEnv.getHtmlLabelName(	24522, user.getLanguage()), "1", 2);
//            mtMap.put("fieldcol", 14);
//            itemlist.add(mtMap);
//        }
        Map mtpasswordMap = FieldUtil.getFormItemForInput("mtpassword", SystemEnv.getHtmlLabelName(	409, user.getLanguage()), mtpassword, pwdViewAttr);
        mtpasswordMap.put("fieldcol", 14);
//        mtpasswordMap.put("rules", "required");
        if(!"".equals(manu) && manu != null){
            rs.executeQuery("select * from meeting_videolineset where linename = ? and linevalue = ?",manu,manu);
            if(rs.next()){
                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(Util.null2String(rs.getString("pwdparams")));
                com.alibaba.fastjson.JSONObject controlparams = com.alibaba.fastjson.JSONObject.parseObject(Util.null2String(rs.getString("controlparams")));
                String needPwd = json.getString("needPwd");
                apidatas.put("needPwd",needPwd);
                apidatas.put("maxLength",json.getString("maxLength"));
                apidatas.put("isNumber",json.getString("isNumber"));
                String showRefresh = Util.null2String(controlparams.getString("showRefresh"));
                if("1".equals(showRefresh)){
                    apidatas.put("showRefresh",true);
                }else{
                    apidatas.put("showRefresh",false);
                }
                if("1".equals(needPwd)){
                    itemlist.add(mtpasswordMap);
                }else if(!"".equals(mtpassword)){
                    itemlist.add(mtpasswordMap);
                }
            }
            //针对方数单独处理
            rs.executeQuery("SELECT keyvalue FROM meeting_videoset where keyname = ? ",manu+"_parties");
            if (rs.next()) {
                String parties = Util.null2String(rs.getString(1));
                if(!"".equals(parties)){
                    List<SearchConditionOption> options = getVideoMeetingPartiesOption(parties);
                    itemlist.add(FieldUtil.getFormItemForSelect("videoparties", SystemEnv.getHtmlLabelName(533826, user.getLanguage()), videoparties, viewattr, options));
                }
            }
        }else{
            rs.executeQuery("select * from meeting_videolineset where linename = ? and linevalue = ?",manufacturers,manufacturers);
            if(rs.next()){
                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(Util.null2String(rs.getString("pwdparams")));
                com.alibaba.fastjson.JSONObject controlparams = com.alibaba.fastjson.JSONObject.parseObject(Util.null2String(rs.getString("controlparams")));
                String needPwd = json.getString("needPwd");
                apidatas.put("needPwd",needPwd);
                apidatas.put("maxLength",json.getString("maxLength"));
                apidatas.put("isNumber",json.getString("isNumber"));
                String showRefresh = Util.null2String(controlparams.getString("showRefresh"));
                if("1".equals(showRefresh)){
                    apidatas.put("showRefresh",true);
                }else{
                    apidatas.put("showRefresh",false);
                }
                if("1".equals(needPwd)){
                    itemlist.add(mtpasswordMap);
                }
            }
            //针对方数单独处理
            rs.executeQuery("SELECT keyvalue FROM meeting_videoset where keyname = ? ",manufacturers+"_parties");
            if (rs.next()) {
                String parties = Util.null2String(rs.getString(1));
                if(!"".equals(parties)){
                    List<SearchConditionOption> options = getVideoMeetingPartiesOption(parties);
                    itemlist.add(FieldUtil.getFormItemForSelect("videoparties", SystemEnv.getHtmlLabelName(533826, user.getLanguage()), videoparties, viewattr, options));
                }
            }
        }

        ConditionFactory conditionFactory = new ConditionFactory(user);
        SearchConditionItem sci = conditionFactory.createCondition(ConditionType.BROWSER, "2106", "hrmids", "17");
        WorkPlanUtil wpu = new WorkPlanUtil();
        List hrmReplaceData = new ArrayList();
        try {
            hrmReplaceData = wpu.convertResourceToList(hrmids,"hrm");
        } catch (Exception e) {
            e.printStackTrace();
        }
        sci.getBrowserConditionParam().setReplaceDatas(hrmReplaceData);
        sci.getBrowserConditionParam().setViewAttr(viewattr==3?2:viewattr);
        Map hrmidsMap = FieldUtil.getFormItemForBrowser(sci, "hrmids", SystemEnv.getHtmlLabelName(	2106,user.getLanguage()), "17", hrmids);
        hrmidsMap.put("fieldcol", 14);
        itemlist.add(hrmidsMap);

        Map manufaceMap = FieldUtil.getFormItemForInput("manufacturers", SystemEnv.getHtmlLabelName(24522, user.getLanguage()), manufacturers, 1);
        manufaceMap.put("fieldcol", 14);
        itemlist.add(manufaceMap);

        //主持人
        if(user.getUID() == Util.getIntValue(videomtcreater)){
            Map startMap = FieldUtil.getFormItemForInput("videomtstarturl", SystemEnv.getHtmlLabelName(519302, user.getLanguage()), videomtstarturl, 1);
            startMap.put("fieldcol", 14);
            itemlist.add(startMap);
        }else{
            Map joinMap = FieldUtil.getFormItemForInput("videomtjoinurl", SystemEnv.getHtmlLabelName(519303, user.getLanguage()), videomtjoinurl, 1);
            joinMap.put("fieldcol", 14);
            itemlist.add(joinMap);
        }
    //相关链接控件。

        String browsertype = "";
        //从模块表拿一下browsertype
        recordSet.executeQuery("select * from meeting_videomould where mouldvalue = ?",frommould);
        if(recordSet.next()){
            browsertype = Util.null2String(recordSet.getString("browsertype"));
        }

        if(StringUtils.isNotBlank(mouldkey)){
            SearchConditionItem browsertypebrowser = conditionFactory.createCondition(ConditionType.BROWSER, 24969, "browsertype", "28");
            itemlist.add(FieldUtil.getFormItemForBrowser(browsertypebrowser, "browsertype", SystemEnv.getHtmlLabelName(24969, user.getLanguage()), browsertype,mouldkey,1));
        }


        groupitem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
        groupitem.put("defaultshow", true);
        groupitem.put("items", itemlist);
        grouplist.add(groupitem);

        apidatas.put("fields", grouplist);

        //这里取一下是否支持邀请的功能。
        String personType = "";
        if (isCreater){
            personType = "view";
        }else if(isInvite){
            personType = "invite";
        }else if(isHrm){
            personType = "hrm";
        }else{
            personType = "history";
        }
        VideoMeetingUtil videoMeetingUtil = new VideoMeetingUtil();
        apidatas.put("isOpenInvite",videoMeetingUtil.isOpenInvite());
        apidatas.put("personType",personType);
        apidatas.put("userId",user.getUID());
        //放一下是否开始的参数。
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date begindate = simpleDateFormat.parse(videomtbegindate);
            apidatas.put("isBegin",begindate.getTime()<new Date().getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //如果是从会议模块发起，那么需要取一下视频会议id
        if("emobile_meeting".equals(client)){
            apidatas.put("videoMtid",id);
        }
        return apidatas;
    }


    public static boolean isJson(String content) {
        try {
            JSONObject.fromObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    /**
     * 会议方数选择框
     * @param parties 会议方数
     * @return
     */
    public static List getVideoMeetingPartiesOption(String parties) {
        List<SearchConditionOption> options = new ArrayList<SearchConditionOption>();
        String[] partiesArr = parties.split(",");
        for (int i=0;i<partiesArr.length;i++){
            options.add(new SearchConditionOption(partiesArr[i], partiesArr[i]));
        }
        return options;
    }
}
