package weaver.meeting.video.consumer;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.meeting.cusvideo.util.YealinkVideoUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import weaver.Constants;
import weaver.WorkPlan.WorkPlanHandler;
import weaver.WorkPlan.WorkPlanService;
import weaver.WorkPlan.WorkPlanShare;
import weaver.conn.RecordSet;
import weaver.domain.workplan.WorkPlan;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.meeting.video.util.VideoMeetingUtil;
import weaver.systeminfo.SystemEnv;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: lj
 * @CreateTime: 2023-06-05 15:41
 * @Version: 1.0
 */
public class YealinkVideoClient extends VideoMeetingClient {
    private static BaseBean logger = new BaseBean();

    @Override
    public Map<String, Object> addMeeting(Map<String, Object> otherParam) {
        Map<String, Object> apiData = new HashMap<>();
        try {
            if ("".equals(Util.null2String(getDomainName_url()))) {
                throw new RuntimeException("获取亿联会议地址URl未配置，请检查视频会议是否配置正常！");
            }
            //获取参数
            logger.writeLog("^^^ YealinkVideoClient.addMeeting : otherParam = " + otherParam);
            String userid = Util.null2String(otherParam.get("userid"));//创建人ID
            String topic = Util.null2String(otherParam.get("topic"));//会议标题
            String start_time = Util.null2String(otherParam.get("starttime")) + ":00";//会议开始时间
            String end_time = Util.null2String(otherParam.get("end_time")) + ":00";//会议结束时间
            String hrmids = Util.null2String(otherParam.get("hrmids"));//会议参与人
            String password = Util.null2String(otherParam.get("password"));//会议密码
            String apiKey = Util.null2String(otherParam.get("api_key"));//对应亿联的client id
            String apiSecret = Util.null2String(otherParam.get("api_secret"));//对应亿联的client secret
            //这里需要替换创建人的ID
            String host = StringUtils.removeEnd(getDomainName_url(), "/");
            //获取token
            String token = YealinkVideoUtil.getToken(host, apiKey, apiSecret);
            //开始执行请求
            String createUserId = YealinkVideoUtil.getYeaLinkUserId(host, token, userid);
            String url = host + "/users/" + createUserId + "/meetings";
            //构建请求体
            JSONObject body = new JSONObject();
            //会议主题，长度小于128
            if (topic.length() > 128) {
                topic = StringUtils.substring(topic, 0, 128);
            }
            body.put("subject", topic);
            //会议开始日期，格式为yyyy-MM-dd
            Date start = DateUtils.parseDate(start_time, "yyyy-MM-dd HH:mm:ss");
            if (start.compareTo(new Date()) < 0) {
                start = new Date();
            }
            String startDate = DateFormatUtils.format(start, "yyyy-MM-dd");
            body.put("startDate", startDate);
            //会议开始时间，格式为HH:mm，小时部分使用24小时计算，分钟部分为5的倍数。会议开始时间必须大于当前时间。
            int minute = DateUtil.minute(start);
            start = DateUtils.addMinutes(DateUtils.addMinutes(start, -minute % 5), 5);
            String startTime = DateFormatUtils.format(start, "HH:mm");
            body.put("startTime", startTime);
            //会议持续时间小时部分，取值范围为[0, 48)。
            int[] dateHoursAndMinute = getDateHoursAndMinute(start, DateUtils.parseDate(end_time, "yyyy-MM-dd HH:mm:ss"));
            int durationHour = dateHoursAndMinute[0];
            body.put("durationHour", durationHour);
            //会议持续时间分钟部分，当durationHour为0时，可选值为：30、45；其他情况下，可选值为：0、15、30、45。
            int durationMinute = dateHoursAndMinute[1];
            body.put("durationMinute", durationMinute);
            //参会成员列表。参会成员数量默认支持100个，如需调整请联系亿联会议，默认创建者为组织者
            JSONArray participants = new JSONArray();
            //首先添加组织者
            JSONObject createUser = new JSONObject();
            createUser.put("id", createUserId);
            createUser.put("role", 0);
            participants.add(createUser);
            for (String hrmid : StringUtils.split(hrmids, ",")) {
                JSONObject participant = new JSONObject();
                participant.put("id", YealinkVideoUtil.getYeaLinkUserId(host, token, hrmid));
                participant.put("role", 2);
                participants.add(participant);
            }
            body.put("participants", participants);
            //是否使用随机会议号，true：使用随机会议号，false：使用会议室会议号
            body.put("enableRandomMeetingNumber", true);
            //会议密码，格式为：6位数字
            body.put("meetingPassword", password);
            //添加水印
            body.put("enableWatermark", true);
            //水印配置
            body.put("watermarkTransparency", 2);
            body.put("watermarkFontSize", 1);
            //是否开启自动录制
            body.put("enableAutoRecord",true);
            //
            //执行接口
            JSONObject resultJson = YealinkVideoUtil.doPost(url, token, null, body);
            //返回结果
            apiData.put("maxid", videoData2OA(host, token, createUserId, resultJson, otherParam));
            apiData.put("api_status", true);
        } catch (Exception e) {
            logger.writeLog("^^^ YealinkVideoClient.addMeeting : error !!!", e);
            apiData.put("api_status", false);
            apiData.put("msg", "新增亿联会议失败：" + e.getMessage());
        }
        return apiData;
    }

    @Override
    public Map<String, Object> editMeeting(Map<String, Object> otherParam) {
        Map<String, Object> apiData = new HashMap<>();
        try {
            if ("".equals(Util.null2String(getDomainName_url()))) {
                throw new RuntimeException("获取亿联会议地址URl未配置，请检查视频会议是否配置正常！");
            }
            //获取参数
            logger.writeLog("^^^ YealinkVideoClient.editMeeting : otherParam = " + otherParam);
            String userid = Util.null2String(otherParam.get("userid"));//创建人ID
            String topic = Util.null2String(otherParam.get("topic"));//会议标题
            String start_time = Util.null2String(otherParam.get("starttime")) + ":00";//会议开始时间
            String end_time = Util.null2String(otherParam.get("end_time")) + ":00";//会议结束时间
            String hrmids = Util.null2String(otherParam.get("hrmids"));//会议参与人
            String password = Util.null2String(otherParam.get("password"));//会议密码
            String apiKey = Util.null2String(otherParam.get("api_key"));//对应亿联的client id
            String apiSecret = Util.null2String(otherParam.get("api_secret"));//对应亿联的client secret
            //这里需要替换创建人的ID
            String host = StringUtils.removeEnd(getDomainName_url(), "/");
            //获取token
            String token = YealinkVideoUtil.getToken(host, apiKey, apiSecret);
            //开始执行请求
            String createUserId = YealinkVideoUtil.getYeaLinkUserId(host, token, userid);
            //会议ID
            String meetingId = Util.null2String(otherParam.get("id"));
            String url = host + "/users/" + createUserId + "/meetings/" + meetingId;
            //先获取原始会议信息
            JSONObject meetingInfo = getMeetingInfoById(host, token, createUserId, meetingId);
            //构建请求体
            JSONObject body = new JSONObject();
            //更新类型，可选值：0：更新单个会议，1：更新会议序列
            body.put("updateType", 0);
            //会议顺序号，取值范围为[1, 100]，更新单个会议时必输
            body.put("sequence", 1);
            //时区ID。具体时区列表信息详见基础信息-查询时区列表接口
            body.put("zoneId", meetingInfo.getString("zoneId"));
            //会议主题，长度小于128
            if (topic.length() > 128) {
                topic = StringUtils.substring(topic, 0, 128);
            }
            body.put("subject", topic);
            //会议开始日期，格式为yyyy-MM-dd
            Date start = DateUtils.parseDate(start_time, "yyyy-MM-dd HH:mm:ss");
            if (start.compareTo(new Date()) < 0) {
                start = new Date();
            }
            String startDate = DateFormatUtils.format(start, "yyyy-MM-dd");
            body.put("startDate", startDate);
            //会议开始时间，格式为HH:mm，小时部分使用24小时计算，分钟部分为5的倍数。会议开始时间必须大于当前时间。
            int minute = DateUtil.minute(start);
            start = DateUtils.addMinutes(DateUtils.addMinutes(start, -minute % 5), 5);
            String startTime = DateFormatUtils.format(start, "HH:mm");
            body.put("startTime", startTime);
            //会议持续时间小时部分，取值范围为[0, 48)。
            int[] dateHoursAndMinute = getDateHoursAndMinute(start, DateUtils.parseDate(end_time, "yyyy-MM-dd HH:mm:ss"));
            int durationHour = dateHoursAndMinute[0];
            body.put("durationHour", durationHour);
            //会议持续时间分钟部分，当durationHour为0时，可选值为：30、45；其他情况下，可选值为：0、15、30、45。
            int durationMinute = dateHoursAndMinute[1];
            body.put("durationMinute", durationMinute);
            //参会成员列表。参会成员数量默认支持100个，如需调整请联系亿联会议，默认创建者为组织者
            JSONArray participants = new JSONArray();
            //首先添加组织者
            JSONObject createUser = new JSONObject();
            createUser.put("id", createUserId);
            createUser.put("role", 0);
            participants.add(createUser);
            for (String hrmid : StringUtils.split(hrmids, ",")) {
                JSONObject participant = new JSONObject();
                participant.put("id", YealinkVideoUtil.getYeaLinkUserId(host, token, hrmid));
                participant.put("role", 2);
                participants.add(participant);
            }
            body.put("participants", participants);
            //是否使用随机会议号，true：使用随机会议号，false：使用会议室会议号
            body.put("enableRandomMeetingNumber", true);
            //会议密码，格式为：6位数字
            body.put("meetingPassword", meetingInfo.getString("meetingPassword"));
            //执行接口
            JSONObject resultJson = YealinkVideoUtil.doPut(url, token, null, body);
            if (resultJson == null) {
                resultJson = new JSONObject();
                resultJson.put("id", meetingId);
            }
            //返回结果
            apiData.put("maxid", videoData2OA(host, token, createUserId, resultJson, otherParam));
            apiData.put("api_status", true);
        } catch (Exception e) {
            logger.writeLog("^^^ YealinkVideoClient.editMeeting : error !!!", e);
            apiData.put("api_status", false);
            apiData.put("msg", "编辑亿联会议失败：" + e.getMessage());
        }
        return apiData;
    }

    @Override
    public Map<String, Object> overMeeting(Map<String, Object> otherParam) {
        otherParam.put("completed", true);
        RecordSet rs = new RecordSet();
        String id = MapUtils.getString(otherParam, "id", "");
        String manufacturers = MapUtils.getString(otherParam, "manufacturers", "");
        rs.executeQuery("select id from meeting_videolist where videomtid=? and manufacturers=?", id, manufacturers);
        if (rs.next()) {
            String videoid = rs.getString(1);
            otherParam.put("videoid", videoid);
        }
        return cancelMeeting(otherParam);
    }

    @Override
    public Map<String, Object> cancelMeeting(Map<String, Object> otherParam) {
        Map<String, Object> apiData = new HashMap<>();
        try {
            if ("".equals(Util.null2String(getDomainName_url()))) {
                throw new RuntimeException("获取亿联会议地址URl未配置，请检查视频会议是否配置正常！");
            }
            //获取参数
            logger.writeLog("^^^ YealinkVideoClient.cancelMeeting : otherParam = " + otherParam);
            String userid = Util.null2String(otherParam.get("userid"));//创建人ID
            //这两个需要重新获取
            otherParam = VideoMeetingUtil.dealParams(otherParam);
            String apiKey = Util.null2String(otherParam.get("api_key"));//对应亿联的client id
            String apiSecret = Util.null2String(otherParam.get("api_secret"));//对应亿联的client secret
            //这里需要替换创建人的ID
            String host = StringUtils.removeEnd(getDomainName_url(), "/");
            //获取token
            String token = YealinkVideoUtil.getToken(host, apiKey, apiSecret);
            //开始执行请求
            String createUserId = YealinkVideoUtil.getYeaLinkUserId(host, token, userid);
            //会议ID
            String meetingId = Util.null2String(otherParam.get("id"));
            String url = host + "/users/" + createUserId + "/meetings/" + meetingId;
            //构建请求体
            JSONObject body = new JSONObject();
            //删除类型，可选值：0：删除单个会议，1：删除会议序列
            body.put("deleteType", 0);
            //会议顺序号，取值范围为[1, 100]，删除单个会议时必输
            body.put("sequence", 1);
            //执行接口
            JSONObject resultJson = YealinkVideoUtil.doDelete(url, token, null, body);
            //处理对应的日程
            String videoid = MapUtils.getString(otherParam, "videoid", "-1");
            if (otherParam.containsKey("completed")) {
                finishWorkPlan(videoid);
            } else {
                deleteWorkPlan(videoid);
            }
            //返回结果
            apiData.put("result", true);
        } catch (Exception e) {
            logger.writeLog("^^^ YealinkVideoClient.editMeeting : error !!!", e);
            apiData.put("result", false);
            apiData.put("msg", "删除亿联会议失败：" + e.getMessage());
        }
        return apiData;
    }

    @Override
    public Map<String, Object> getUserInfo(Map<String, Object> otherParam) {
        return null;
    }

    /**
     * 获取间隔小时数
     *
     * @param start
     * @param end
     * @return
     */
    private int[] getDateHoursAndMinute(Date start, Date end) {
        int[] arr = new int[2];
        long milliseconds = end.getTime() - start.getTime();
        long seconds = milliseconds / 1000;
        int hours = Math.round(seconds / 3600);
        int minutes = Math.round((seconds % 3600) / 60);
        if (minutes > 45) {
            hours += 1;
            minutes = 0;
        } else if (minutes > 30) {
            minutes = 45;
        } else {
            if (hours > 0) {
                if (minutes > 15) {
                    minutes = 30;
                } else if (minutes > 0) {
                    minutes = 15;
                }
            } else {
                minutes = 30;
            }
        }
        if (hours >= 48) {
            hours = 47;
        }
        arr[0] = hours;
        arr[1] = minutes;
        return arr;
    }

    /**
     * 视频数据同步到OA
     *
     * @param resultJson
     * @param map
     * @return
     */
    private String videoData2OA(String host, String token, String creater, JSONObject resultJson, Map<String, Object> map) {
        logger.writeLog("videoData2OA.param");
        logger.writeLog("videoData2OA.param.host"+host);
        logger.writeLog("videoData2OA.param.token"+token);
        logger.writeLog("videoData2OA.param.creater"+creater);
        logger.writeLog("videoData2OA.param.resultJson"+resultJson);
        logger.writeLog("videoData2OA.param.map"+map);
        String maxId = "";
        String videomthostid = Util.null2String(map.get("host_id"));
        String videomtname = Util.null2String(map.get("topic"));
//        String videomtbegindate = Util.null2String(map.get("start_time"));
        String starttime = Util.null2String(map.get("starttime"));
        String videomtenddate = Util.null2String(map.get("end_time"));
        String videomtcreater = Util.null2String(map.get("userid"));
//        String mtpassword = Util.null2String(map.get("password"));
//        String mtcontrolpassword = Util.null2String(map.get("controlpassword"));
//        String userid = Util.null2String(map.get("userid"));
        String manufacturers = Util.null2String(map.get("manufacturers"));
        String mouldkey = Util.null2String(map.get("mouldkey"));//模块主键
        String frommould = Util.null2String(map.get("frommould"));//所属模块
        String videoid = Util.null2String(map.get("videoid"));
        String hrmids = Util.null2String(map.get("hrmids"));
        int isOtherShare = Util.getIntValue(Util.null2String(map.get("isOtherShare")),1);
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery("SELECT * FROM meeting_videomould WHERE mouldvalue = ? or mouldname = ?", frommould, frommould);
        if (recordSet.next()) {
            //这里强制约定。这里传的标识，必须和表里保持一致，否则，作为垃圾数据处理。
            frommould = Util.null2String(recordSet.getString("mouldvalue"));
        } else {
            frommould = "";
            mouldkey = "";
        }
        //获取接口返回的会议ID
        String videomtstatus = "1";//0，未开始，1进行中，2结束，3取消（根据时间来判断）
        String videomtid = Util.null2String(resultJson.getString("id"));//虚拟会议id
        //这里需要根据会议ID再次查询会议详细信息
        JSONObject json = getMeetingInfoById(host, token, creater, videomtid);
        String mtpwd = Util.null2String(json.getString("meetingPassword"));
        String mtnum = Util.null2String(json.getString("meetingNumber"));
        String url2 = getYealinkUrl(host, token, mtnum, videomtcreater, mtpwd);
        String url1 = url2;
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            url1 = StringUtils.replace(url1, "&name=", "&name=" + URLEncoder.encode(resourceComInfo.getLastname(videomtcreater), "utf-8"));
            if (url1.contains("&autojoin=false")) {
                url1 = StringUtils.replace(url1, "&autojoin=false", "&autojoin=true");
            }
        } catch (Exception e) {
            logger.writeLog("^^^ YealinkVideoClient.videoData2OA : encode error !!!", e);
        }
        //更新到视频会议表
        RecordSet rs = new RecordSet();
        String oaMtid = mtnum;
        VideoMeetingUtil videoMeetingUtil = new VideoMeetingUtil();
        if (StringUtils.isBlank(videoid)) {
            if (rs.getDBType().equalsIgnoreCase("oracle") && Util.null2String(rs.getOrgindbtype()).equals("oracle")) {
                rs.executeUpdate("INSERT INTO meeting_videolist (videomtid ,videomthostid , videomtname ,videomtbegindate ," +
                                "videomtenddate ,videomtcreater ,videomtstatus ,manufacturers ,frommould ,mouldkey,mtpassword," +
                                "oaMtid,videomtstarturl,videomtjoinurl,isOtherShare) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                        videomtid, videomthostid, videomtname, starttime, videomtenddate, videomtcreater, videomtstatus,
                        manufacturers, frommould, mouldkey, mtpwd, oaMtid, url1, url2,isOtherShare);
            } else {
                rs.executeUpdate("INSERT INTO meeting_videolist (videomtid ,videomthostid , videomtname ,videomtbegindate ," +
                                "videomtenddate ,videomtcreater ,videomtstatus ,manufacturers ,frommould ,mouldkey,mtpassword," +
                                "oaMtid,hrmids,videomtstarturl,videomtjoinurl,isOtherShare) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                        videomtid, videomthostid, videomtname, starttime, videomtenddate, videomtcreater, videomtstatus,
                        manufacturers, frommould, mouldkey, mtpwd, oaMtid, hrmids, url1, url2,isOtherShare);
            }
            rs.executeQuery("SELECT max(id) FROM meeting_videolist where videomtcreater = ?", videomtcreater);
            rs.next();
            String MaxID = rs.getString(1);
            if (rs.getDBType().equalsIgnoreCase("oracle") && Util.null2String(rs.getOrgindbtype()).equals("oracle")) {
                rs.executeUpdate("update meeting_videolist set hrmids = empty_clob() where id = ?", MaxID);
                videoMeetingUtil.updateHrmmembers(MaxID, hrmids);
            }
            maxId = MaxID;
        } else {
            if (rs.getDBType().equalsIgnoreCase("oracle") && Util.null2String(rs.getOrgindbtype()).equals("oracle")) {
                rs.executeUpdate("update meeting_videolist set videomtid = ?, videomtname = ?,videomtbegindate = ?," +
                        "videomtenddate = ?,mtpassword = ?,videomtstarturl = ?,videomtjoinurl = ?,hrmids = empty_clob(),isOtherShare = ? " +
                        "where id =?", videomtid, videomtname, starttime, videomtenddate, mtpwd, url1, url2,isOtherShare, videoid);
                videoMeetingUtil.updateHrmmembers(videoid, hrmids);
            } else {
                rs.executeUpdate("update meeting_videolist set videomtid = ?, videomtname = ?,videomtbegindate = ?," +
                        "videomtenddate = ?,mtpassword = ?,videomtstarturl = ?,videomtjoinurl = ?,hrmids=? ,isOtherShare = ? " +
                        "where id =?", videomtid, videomtname, starttime, videomtenddate, mtpwd, url1, url2, hrmids, isOtherShare, videoid);
            }
            maxId = videoid;
        }
        //同步日程
        handleWorkPlan(maxId, Util.getIntValue(videomtcreater), videomtname, hrmids, starttime, videomtenddate, oaMtid);
        return maxId;
    }

    /**
     * 处理日程信息
     *
     * @param videoMtId
     * @param createrId
     * @param title
     * @param hrmids
     * @param start
     * @param end
     * @param mtNum
     */
    private void handleWorkPlan(String videoMtId, int createrId, String title,
                                String hrmids, String start, String end,
                                String mtNum) {
        try {
            WorkPlan workPlan = new WorkPlan();
            RecordSet rs = new RecordSet();
            //查询是否存在此日程
            rs.executeQuery("select id from workplan where videomtid=?", videoMtId);
            int workPlanId = -1;
            if (rs.next()) {
                workPlanId = Util.getIntValue(rs.getString(1));
            }
            if (workPlanId > 0) {//修改
                workPlan.setWorkPlanID(workPlanId);
                //获取原日程信息
                getWorkPlanById(rs, workPlan);
            } else {//新增
                workPlan.setCreateType(1);
                //紧急程度
                workPlan.setUrgentLevel("1");
                //日程提醒方式
                workPlan.setRemindType(com.engine.workplan.util.WorkPlanUtil.getWorkPlanDefaultRemindTypeIds());
                //日程类型
                workPlan.setWorkPlanType(1);
                //是否开始前提醒
                workPlan.setRemindBeforeStart("1");
                //是否结束前提醒
                workPlan.setRemindBeforeEnd("0");
                //
                workPlan.setRemindTimesBeforeStart(10);
                workPlan.setRemindTimesBeforeEnd(10);
                //
                workPlan.setStatus(Constants.WorkPlan_Status_Unfinished);
            }
            //创建人
            workPlan.setCreaterId(createrId);
            //标题
            workPlan.setWorkPlanName(title);
            //接收人
            workPlan.setResourceId(hrmids);  //系统参与人
            if (StringUtils.isBlank(workPlan.getResourceId()) && createrId > 0) {//接收人为空,默认直接
                workPlan.setResourceId(createrId + "");
            }
            //开始时间
            String beginDate = "", beginTime = "";
            if (StringUtils.isNotBlank(start)) {
                String[] s = StringUtils.split(start, " ");
                beginDate = s[0];
                if (s.length > 1) {
                    beginTime = s[1];
                    if (beginTime.length() == 8) {
                        beginTime = StringUtils.substringBeforeLast(beginTime, ":");
                    }
                }
            }
            workPlan.setBeginDate(beginDate);  //开始日期
            workPlan.setBeginTime(beginTime);  //开始时间
            //结束时间
            String endDate = "", endTime = "";
            if (StringUtils.isNotBlank(end)) {
                String[] s = StringUtils.split(end, " ");
                endDate = s[0];
                if (s.length > 1) {
                    endTime = s[1];
                    if (endTime.length() == 8) {
                        endTime = StringUtils.substringBeforeLast(endTime, ":");
                    }
                }
            }
            workPlan.setEndDate(endDate);  //结束日期
            workPlan.setEndTime(endTime);  //结束时间
            //内容
            User user = User.getUser(createrId, 0);
            String description = SystemEnv.getHtmlLabelName(10000849, Util.getIntValue(user.getLanguage())) + "：" + workPlan.getWorkPlanName()
                    + " " + SystemEnv.getHtmlLabelName(81901, user.getLanguage()) + "：" + workPlan.getBeginDate() + " " + workPlan.getBeginTime()
                    + " " + SystemEnv.getHtmlLabelName(525536, user.getLanguage()) + "：[亿联] " + mtNum;
            workPlan.setDescription(description);
            //是否来自外部系统
            workPlan.setIsFromOthSystem(false);
            if (!"".equals(workPlan.getBeginDate()) && null != workPlan.getBeginDate()) {
                List beginDateTimeRemindList = Util.processTimeBySecond(workPlan.getBeginDate(), workPlan.getBeginTime(), workPlan.getRemindTimesBeforeStart() * -1 * 60);
                workPlan.setRemindDateBeforeStart((String) beginDateTimeRemindList.get(0));  //开始前提醒日期
                workPlan.setRemindTimeBeforeStart((String) beginDateTimeRemindList.get(1));  //开始前提醒时间
            }
            if (!"".equals(workPlan.getEndDate()) && null != workPlan.getEndDate()) {
                List endDateTimeRemindList = Util.processTimeBySecond(workPlan.getEndDate(), workPlan.getEndTime(), workPlan.getRemindTimesBeforeEnd() * -1 * 60);
                workPlan.setRemindDateBeforeEnd((String) endDateTimeRemindList.get(0));  //结束前提醒日期
                workPlan.setRemindTimeBeforeEnd((String) endDateTimeRemindList.get(1));  //结束前提醒时间
            }
            //附件
            String workPlanType = workPlan.getWorkPlanType() + "";
            WorkPlanService workPlanService = new WorkPlanService();
            WorkPlanShare workPlanShare = new WorkPlanShare();
            if (workPlan.getWorkPlanID() > 0) {
                //修改
                WorkPlan oldWorkPlan = new WorkPlan();
                oldWorkPlan.setWorkPlanID(workPlan.getWorkPlanID());
                workPlanService.updateWorkPlan(oldWorkPlan, workPlan);
                try {
                    workPlanShare.setShareDetail(workPlan.getWorkPlanID() + "");
                } catch (Exception e) {
                    logger.writeLog("^^^ YealinkVideoClient.handleWorkPlan : setShareDetail error !!!", e);
                }
            } else {
                //新增
                workPlanService.insertWorkPlan(workPlan);  //插入日程
                try {
                    workPlanShare.setDefaultShareDetail(user, String.valueOf(workPlan.getWorkPlanID()), workPlanType);//只在新增的时候设置默认共享
                } catch (Exception e) {
                    logger.writeLog("^^^ YealinkVideoClient.handleWorkPlan : setDefaultShareDetail error !!!", e);
                }
                rs.executeUpdate("update workplan set videomtid=? where id=?", videoMtId, workPlan.getWorkPlanID());
            }
        } catch (Exception e) {
            logger.writeLog("^^^ YealinkVideoClient.handleWorkPlan : 用户[" + createrId + "]日程处理处理失败！", e);
        }
    }

    /**
     * 删除对应的日程
     *
     * @param videoMtId
     */
    private void deleteWorkPlan(String videoMtId) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from workplan where videomtid=?", videoMtId);
        int workPlanId = -1;
        if (rs.next()) {
            workPlanId = Util.getIntValue(rs.getString(1));
        }
        if (workPlanId > 0) {
            new WorkPlanHandler().delete(workPlanId + "");
        }
    }

    /**
     * 完成日程
     *
     * @param videoMtId
     */
    private void finishWorkPlan(String videoMtId) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from workplan where videomtid=?", videoMtId);
        int workPlanId = -1;
        if (rs.next()) {
            workPlanId = Util.getIntValue(rs.getString(1));
        }
        if (workPlanId > 0) {
            new WorkPlanHandler().finishWorkPlan(workPlanId + "");
        }
    }

    /**
     * 获取原日程信息
     *
     * @param rs
     * @param workPlan
     */
    private void getWorkPlanById(RecordSet rs, WorkPlan workPlan) {
        rs.executeQuery("select * from workplan where id=?", workPlan.getWorkPlanID());
        rs.next();
        workPlan.setWorkPlanType(Util.getIntValue(rs.getString("type_n")));
        workPlan.setBeginDate(Util.null2String(rs.getString("begindate")));
        workPlan.setBeginTime(Util.null2String(rs.getString("begintime")));
        workPlan.setEndDate(Util.null2String(rs.getString("enddate")));
        workPlan.setEndTime(Util.null2String(rs.getString("endtime")));
        workPlan.setStatus(Util.null2String(rs.getString("status")));
        workPlan.setCreaterId(Util.getIntValue(rs.getString("createrid")));
        workPlan.setWorkPlanName(Util.null2String(rs.getString("name")));
        workPlan.setCreateType(Util.getIntValue(rs.getString("creatertype")));
        workPlan.setUrgentLevel(Util.null2String(rs.getString("urgentlevel")));
        workPlan.setRemindType(Util.null2String(rs.getString("remindtype")));
        workPlan.setRemindTimesBeforeStart(Util.getIntValue(rs.getString("remindtimesbeforestart")));
        workPlan.setRemindTimesBeforeEnd(Util.getIntValue(rs.getString("remindtimesbeforeend")));
        workPlan.setRemindBeforeStart(Util.null2String(rs.getString("remindbeforestart")));
        workPlan.setRemindBeforeEnd(Util.null2String(rs.getString("remindbeforeend")));
        workPlan.setRemindDateBeforeStart(Util.null2String(rs.getString("reminddatebeforestart")));
        workPlan.setRemindTimeBeforeStart(Util.null2String(rs.getString("remindtimebeforestart")));
        workPlan.setRemindDateBeforeEnd(Util.null2String(rs.getString("reminddatebeforeend")));
        workPlan.setRemindTimeBeforeEnd(Util.null2String(rs.getString("remindtimebeforeend")));
        workPlan.setResourceId(Util.null2String(rs.getString("resourceid")));
        workPlan.setUuid(Util.null2String(rs.getString("uuid")));
    }

    /**
     * 获取入会链接
     *
     * @param host
     * @param token
     * @param mtnum
     * @param userId
     * @param meetingPassword
     * @return
     */
private String getYealinkUrl(String host, String token, String mtnum, String userId, String meetingPassword) {
        String url = host + "/meeting-join-links/" + mtnum;
        JSONObject body = new JSONObject();
        body.put("language", "zh");
        body.put("password", meetingPassword);
        JSONObject resultJson = YealinkVideoUtil.doGet(url, token, null, body);
        return resultJson.getString("joinLink");
    }

    /**
     * 查询会议信息
     *
     * @param host
     * @param token
     * @param userId
     * @param mtId
     * @return
     */
    private JSONObject getMeetingInfoById(String host, String token, String userId, String mtId) {
        String url = host + "/users/" + userId + "/meetings/" + mtId;
        JSONObject body = new JSONObject();
        body.put("sequence", 1);
        return YealinkVideoUtil.doGet(url, token, null, body);
    }
}
