package com.engine.meeting.cmd.meetingvideo;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogType;
import com.engine.common.constant.ParamConstant;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.meeting.video.consumer.MeetingVideoFactory;
import weaver.meeting.video.consumer.VideoMeetingClient;
import weaver.meeting.video.util.BizLogSmallType4VideoMeeting;
import weaver.meeting.video.util.VideoMeetingUtil;
import weaver.systeminfo.SystemEnv;

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

/*
 * 新建+编辑视频会议
 * @author yp
 * @date 2020/4/28
 * @param
 * @return
 */
public class DoAddVideoMeetingCmd extends AbstractCommonCommand<Map<String, Object>> {

    private SimpleBizLogger logger;
    private BizLogContext bizLogContext;
    public static VideoMeetingClient videoMeetingClient;

    public DoAddVideoMeetingCmd(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;
        this.logger = new SimpleBizLogger();
        this.bizLogContext = new BizLogContext();
    }


    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map ret = new HashMap();
        RecordSet recordSet = new RecordSet();
        String manufacturers = "";
        String host_id = "";
        String controlLine = "";
        String id = Util.null2String(params.get("id"));
        recordSet.executeQuery("select * from meeting_videoset");
        while (recordSet.next()) {
            if ("manufacturers".equals(recordSet.getString("keyname"))) {
                manufacturers = Util.null2String(recordSet.getString("keyvalue"));
            }
            if ("controlLine".equals(recordSet.getString("keyname"))) {
                controlLine = Util.null2String(recordSet.getString("keyvalue"));
            }
        }
        params.put("manufacturers", manufacturers);
        params.put("controlLine", controlLine);
        params.put("userid", user.getUID());
        videoMeetingClient = MeetingVideoFactory.getInstance(manufacturers);
        String pwd = Util.null2String(params.get("mtpassword"));
        if(!"".equals(pwd) && (pwd.length() > 6 || pwd.length() < 4) && "tencent".equals(manufacturers)){
            if(pwd.length() > 6){
                ret.put("msg",SystemEnv.getHtmlLabelName(31865, user.getLanguage())+"6");
            }
            if(pwd.length() < 4){
                ret.put("msg",SystemEnv.getHtmlLabelName(20172, user.getLanguage())+"4");
            }
            ret.put("ret", "false");
            return ret;
        }
        //会议名称，开始时间，结束时间，从前台点击按钮传参。
        Map map = VideoMeetingUtil.getFreeLine(params);
        String uniquetype = Util.null2String(map.get("uniquetype"));
        if ("email".equals(uniquetype) && !"gnet".equals(manufacturers)) {
            params.put("email", Util.null2String(map.get("line")));
            host_id = Util.null2String(videoMeetingClient.getUserInfo(params).get("id"));
        } else {
            host_id = Util.null2String(map.get("line"));
        }
        //如果hostid为空，说明没有配置线路，或者当前线路全忙，请重新选择时间
        if(!"huaweicloud".equals(manufacturers) && !"xylink".equals(manufacturers) && !"yealink".equals(manufacturers) && !"tencent".equals(manufacturers) && !"InfowareLab".equals(manufacturers) && !"BizConf".equals(manufacturers)){
            if (StringUtils.isBlank(host_id)) {
                ret.put("msg", SystemEnv.getHtmlLabelName(519495, user.getLanguage()));
                ret.put("ret", "false");
                return ret;
            }
        }
        //hostid在这里处理。用检测冲突那一套逻辑，去检测出来不冲突的线路，并取出hostid。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        int minute = 0;
        try {
            minute = (int) ((sdf.parse(Util.null2String(params.get("videomtenddate"))).getTime() - sdf.parse(Util.null2String(params.get("videomtbegindate"))).getTime()) / (1000 * 60));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(Util.null2String(params.get("videomtbegindate")).length() == 19){
            String bgdateTemp = Util.null2String(params.get("videomtbegindate")).substring(0, 16);
            params.put("videomtbegindate",bgdateTemp);
        }
        if(Util.null2String(params.get("videomtenddate")).length() == 19){
            String eddateTemp = Util.null2String(params.get("videomtenddate")).substring(0, 16);
            params.put("videomtenddate",eddateTemp);
        }
        Map zoomMap = new HashMap();
        zoomMap.put("host_id", host_id);
        zoomMap.put("type", "2");
        zoomMap.put("topic", Util.null2String(params.get("videomtname")));
        zoomMap.put("start_time", VideoMeetingUtil.localToUTC(Util.null2String(params.get("videomtbegindate"))+":00"));
        zoomMap.put("end_time", Util.null2String(params.get("videomtenddate")));
        zoomMap.put("starttime", Util.null2String(params.get("videomtbegindate")));//这里多添加一个，是为了保证入库的时候，展示原本的时间。不展示utc时间。
        zoomMap.put("userid", Util.null2String(user.getUID()));
        if (StringUtils.isNotBlank(Util.null2String(params.get("mtpassword")))) {
            zoomMap.put("password", Util.null2String(params.get("mtpassword")));
        }
        zoomMap.put("duration", Util.null2String(minute));
        zoomMap.put("manufacturers", manufacturers);
        zoomMap.put("mouldkey", Util.null2String(params.get("mouldkey")));
        zoomMap.put("frommould", Util.null2String(params.get("frommould")));
        zoomMap.put("hrmids", Util.null2String(params.get("hrmids")));
        zoomMap.put("videoparties", Util.null2String(params.get("videoparties")));
        zoomMap.put("isOtherShare", Util.null2String(params.get("isOtherShare")));
        zoomMap = VideoMeetingUtil.dealParams(zoomMap);
        String manu = "";
        try {
            Map result = new HashMap();
            VideoMeetingUtil videoMeetingUtil = new VideoMeetingUtil();
            if (StringUtils.isNotBlank(id)) {
                zoomMap.put("videoid", id);
                recordSet.executeQuery("select * from meeting_videolist where id = ?", id);
                recordSet.next();
                zoomMap.put("id", Util.null2String(recordSet.getString("videomtid")));
                manu = Util.null2String(recordSet.getString("manufacturers"));
                String hrmidsOld = recordSet.getString("hrmids");
                String[] strOld= hrmidsOld.split(",");
                String[] strNew= Util.null2String(params.get("hrmids")).split(",");
                Set<String> setOld = new HashSet<>();
                Set<String> setNew = new HashSet<>();
                Collections.addAll(setOld, strOld);
                Collections.addAll(setNew, strNew);
                Map<String,Set> diffMap = VideoMeetingUtil.diffSet(setNew,setOld);
                //添加人员
                Set<String> addMemberSet = diffMap.get("add");
                //删除人员
                Set<String> delMemberSet = diffMap.get("del");
                //原封不到的人员
                Set<String> keepMemberSet = diffMap.get("keep");
                if(!manu.equals(manufacturers)){
                    ret.put("msg",SystemEnv.getHtmlLabelName(523363, user.getLanguage()));
                    ret.put("ret", false);
                    return ret;
                }else{
                    result = videoMeetingClient.editMeeting(zoomMap);
                    if(Boolean.parseBoolean(Util.null2String(result.get("api_status")))){
                        if(addMemberSet.size()>0){
                            videoMeetingUtil.remindByThread(id, new User(user.getUID()),999,addMemberSet.stream().collect(Collectors.joining(",")));
                        }
                        if(delMemberSet.size()>0){
                            videoMeetingUtil.remindByThread(id, new User(user.getUID()),1001,delMemberSet.stream().collect(Collectors.joining(",")));
                        }
                        if(keepMemberSet.size()>0){
                            videoMeetingUtil.remindByThread(id, new User(user.getUID()),1000,keepMemberSet.stream().collect(Collectors.joining(",")));
                        }
                    }
                }
            } else {
                if(Boolean.parseBoolean(Util.null2String(result.get("api_status")))){
                    videoMeetingUtil.remindByThread(result.get("maxid")+"", new User(user.getUID()),999);
                }
            }
            boolean api_status = Boolean.parseBoolean(Util.null2String(result.get("api_status")));
            ret.put("maxid",result.get("maxid"));
            ret.put("ret", api_status);
            if(StringUtils.isNotBlank(id) && !api_status){
                if(manu.equals(manufacturers)){
                    ret.put("msg",SystemEnv.getHtmlLabelName(523362, user.getLanguage()));
                }else{
                    ret.put("msg",SystemEnv.getHtmlLabelName(523363, user.getLanguage()));
                }
            }
            if(StringUtils.isNotBlank(Util.null2String(result.get("msg")))){
                ret.put("msg",Util.null2String(result.get("msg")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("ret", "false");
        }
        this.beforeLog();
        String mainSql = "select * from meeting_videolines ";
        logger.setMainSql(mainSql, "id");
        return ret;
    }

    /**
     * 日志操作记录
     */
    public void beforeLog() {
        bizLogContext.setDateObject(new Date());
        bizLogContext.setUserid(user.getUID());
        bizLogContext.setUsertype(Util.getIntValue(user.getLogintype()));
        bizLogContext.setTargetId("1");
        //bizLogContext.setTargetName("应用设置");
        bizLogContext.setLogType(BizLogType.MEETING_ENGINE);
        bizLogContext.setBelongType(BizLogSmallType4VideoMeeting.MEETING_VideMeeting);
        bizLogContext.setLogSmallType(BizLogSmallType4VideoMeeting.MEETING_VideMeeting);
        //bizLogContext.setBelongTypeTargetName(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005423,weaver.general.ThreadVarLanguage.getLang())+"");
        bizLogContext.setParams(params);
        bizLogContext.setClientIp(Util.null2String(params.get(ParamConstant.PARAM_IP)));
        logger.setUser(user);//当前操作人
        logger.setParams(params);//request请求参数

        RecordSet recordSet = new RecordSet();
        String mainSql = "select * from meeting_videoset ";
        logger.setMainSql(mainSql, "id");

        //logger.setMainTargetNameColumn(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005423,weaver.general.ThreadVarLanguage.getLang())+"");
        logger.before(bizLogContext);
    }

    /**
     * 生成logContext对象
     *
     * @return BizLogContext对象
     */
    @Override
    public BizLogContext getLogContext() {
        return logger.getBizLogContext();
    }
}
