package com.bcxin.identify.api.tencent.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.identify.api.tencent.dto.BroadcastDto;
import com.bcxin.identify.api.tencent.dto.im.*;
import com.bcxin.identify.api.tls.sigcheck.tls_sigcheck;
import com.bcxin.identify.business.dao.ComVideoRoomMapper;
import com.bcxin.identify.business.dao.ImRoammsgTempMapper;
import com.bcxin.identify.business.dao.PerVideoRoomMapper;
import com.bcxin.identify.business.domain.ImRoammsgTemp;
import com.bcxin.identify.business.domain.dto.PushUni2DTO;
import com.bcxin.identify.business.domain.ysp.ComVideoRoom;
import com.bcxin.identify.business.domain.ysp.PerVideoRoom;
import com.bcxin.identify.business.service.ComVideoRoomService;
import com.bcxin.identify.business.service.ImRoammsgTempService;
import com.bcxin.identify.business.service.LogBusinessrequestService;
import com.bcxin.identify.config.exception.BusinessException;
import com.bcxin.identify.startup.CacheService;
import com.bcxin.identify.util.DateUtil;
import com.bcxin.identify.util.HttpUtils;
import com.bcxin.identify.util.JsonConverUtil;
import com.bcxin.identify.util.Result;
import com.bcxin.identify.util.codes.CommonConst;
import com.bcxin.identify.util.codes.DictConst;
import com.bcxin.identify.util.codes.M3u8ToMp4;
import com.bcxin.identify.util.common.Const;
import com.bcxin.identify.util.common.IdWorker;
import com.bcxin.identify.util.common.StringUtil;
import com.bcxin.identify.util.getui.GTErrorEnum;
import com.bcxin.identify.util.getui.GeTuiUtil;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.bcxin.identify.util.tencent.im.ImApiConst;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.trtc.v20190722.TrtcClient;
import com.tencentcloudapi.trtc.v20190722.models.DissolveRoomRequest;
import com.tencentcloudapi.trtc.v20190722.models.DissolveRoomResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <b> 百度认证相关接口业务处理 </b>
 * @author ZXF
 * @create 2021/01/28 0028 16:45
 * @version
 * @注意事项 </b>
 */
@Service
public class TencentIMService {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private CacheService cacheService;
    @Resource
    private LogBusinessrequestService logBusinessrequestService;
    @Resource
    private ComVideoRoomService comVideoRoomService;
    @Resource
    private ComVideoRoomMapper comVideoRoomMapper;
    @Resource
    private PerVideoRoomMapper perVideoRoomMapper;
    @Resource
    private ImRoammsgTempService imRoammsgTempService;
    @Resource
    private ImRoammsgTempMapper imRoammsgTempMapper;

    /**
     * <b> 组装im接口地址 </b>
     * @author ZXF
     * @create 2019/09/24 0024 10:51
     * @version
     * @注意事项 </b>
     */
    private String getImUrl(String api){
        // 管理员用户名
        String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
//        // 管理员签名
//        String adminSig = createImSig(adminUserName);
        /*** 从缓存中拿到adminSig ***/
        String adminSig = cacheService.getTencentAdminSig(adminUserName);
        String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
        String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
        int random = (int) (((Math.random() * 9 + 1) * 100000));
        String contenttype = "json";
        tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
        return tencentImUrl;
    }

    /**
     * @param identifier 用户标示符，即用户 id
     * @return
     * @throws Exception
     */
    private String createImSig(String identifier) {
        BufferedReader br = null;
        String sig = "";
        try {
            // 创建应用时，页面上分配的 sdkappid
            String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            // 动态库的绝对路径 加载动态库
            String libPath = ConfigUtil.getValue(CommonConst.TENCENT_LIBPATH);
            // 私钥
            String private_key_url = ConfigUtil.getValue(CommonConst.TENCENT_EC_KEY);
            // 公钥
            String public_key_url = ConfigUtil.getValue(CommonConst.TENCENT_PUBLIC_KEY);
            tls_sigcheck demo = new tls_sigcheck();
            // 使用前请修改动态库的加载路径
            demo.loadJniLib(libPath);
            File priKeyFile = new File(private_key_url);
            StringBuilder strBuilder = new StringBuilder();
            String s = "";
            br = new BufferedReader(new FileReader(priKeyFile));
            while ((s = br.readLine()) != null) {
                strBuilder.append(s + '\n');
            }
            br.close();
            String priKey = strBuilder.toString();
            int ret = demo.tls_gen_signature_ex2(sdkAppid, identifier, priKey);
            File pubKeyFile = new File(public_key_url);
            br = new BufferedReader(new FileReader(pubKeyFile));
            strBuilder.setLength(0);
            while ((s = br.readLine()) != null) {
                strBuilder.append(s + '\n');
            }
            br.close();
            String pubKey = strBuilder.toString();
            ret = demo.tls_check_signature_ex2(demo.getSig(), pubKey, sdkAppid, identifier);
            sig = demo.getSig();
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
        return sig;
    }

    /**
     * <b> 腾讯IM 获取sig </b>
     * @author ZXF
     * @create 2021/01/30 0030 10:33
     * @version
     * @注意事项 </b>
     */
    public Result getTencentSig (Map<String,Object> params){
        String identifier = String.valueOf(params.get("mobilePhone"));
        //如果不存在sig缓存就去查账户是否已导入没有就做导入
        if(!cacheService.isTencentSig(identifier)){
            Result checkResult = checkImAccount(identifier);
            if(Result.ERROR.equals(checkResult.getRetType())){
                return checkResult;
            }
            if("0".equals(String.valueOf(checkResult.getData()))){
                Result importResult = importImAccount(identifier);
                if(Result.ERROR.equals(importResult.getRetType())){
                    return importResult;
                }
            }
        }
        Result result = cacheService.getTencentSig(identifier);
        Result result1 = createImPortrait(params);
        if(Result.ERROR.equals(result1.getRetType())){
            return result1;
        }
        logBusinessrequestService.save("GET-TENCENT-SIG", Const.N, params.toString(), JSONObject.toJSONString(result));
        return Result.success(Result.SUCCESS_QUERY_MSG,result);
    }

    /**
     * <b> 查询帐号 </b>
     * @author ZXF
     * @create 2021/01/30 0030 10:57
     * @version
     * @注意事项 </b>
     */
    public Result checkImAccount(String identifier) {
        try {
            // 管理员用户名
            String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
            /*** 从缓存中拿到adminSig ***/
            String adminSig = cacheService.getTencentAdminSig(adminUserName);
            String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
            String api = ImApiConst.IM_APT_CHECK_ACCOUNT;
            String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            int random = (int) (((Math.random() * 9 + 1) * 100000));
            String contenttype = "json";
            tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                    + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
            String jsonParamBody = "";
            ImCheckAccount imCheckAccount = new ImCheckAccount();
            List<ImCheckItem> checkItems = new ArrayList<ImCheckItem>();
            ImCheckItem imCheckItem = new ImCheckItem();
            // 姓名
            imCheckItem.setUserID(identifier);
            checkItems.add(imCheckItem);
            imCheckAccount.setCheckItem(checkItems);
            jsonParamBody = JSON.toJSONString(imCheckAccount);
            jsonParamBody = jsonParamBody.replaceAll("userID", "UserID");
            jsonParamBody = jsonParamBody.replaceAll("checkItem", "CheckItem");
            log.info("*********jsonParamBody:" + jsonParamBody);
            log.info("*********tencentImUrl:" + tencentImUrl);
            String result = HttpUtils.postJsonString(tencentImUrl, jsonParamBody);
            log.info("*********returnImPortrait:" + result);
            JSONObject ret = JSONObject.parseObject(result);
            logBusinessrequestService.save("CHECK-IM-ACCOUNT", Const.N, jsonParamBody, result);
            if("FAIL".equals(ret.get("ActionStatus")+"")){
                return Result.fail(String.valueOf(ret.get("ErrorInfo")));
            }
            JSONArray arr = (JSONArray) ret.get("ResultItem");
            JSONObject obj = (JSONObject) arr.get(0);
            //AccountStatus导入状态：Imported 表示已导入（返回1），NotImported 表示未导入（返回0）
            if("Imported".equals(obj.get("AccountStatus"))){
                return Result.success(Result.SUCCESS_QUERY_MSG,1);
            }
            return Result.success(Result.SUCCESS_QUERY_MSG,0);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * <b> 导入单个帐号 </b>
     * @author ZXF
     * @create 2021/01/30 0030 10:57
     * @version
     * @注意事项 </b>
     */
    public Result importImAccount(String identifier) {
        try {
            // 管理员用户名
            String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
            /*** 从缓存中拿到adminSig ***/
            String adminSig = cacheService.getTencentAdminSig(adminUserName);
            String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
            String api = ImApiConst.IM_APT_ACCOUNT_IMPORT;
            String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            int random = (int) (((Math.random() * 9 + 1) * 100000));
            String contenttype = "json";
            tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                    + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
            String jsonParamBody = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Identifier",identifier);
            jsonParamBody = JSON.toJSONString(jsonObject);
            log.info("*********jsonParamBody:" + jsonParamBody);
            log.info("*********tencentImUrl:" + tencentImUrl);
            String result = HttpUtils.postJsonString(tencentImUrl, jsonParamBody);
            log.info("*********returnImPortrait:" + result);
            JSONObject ret = JSONObject.parseObject(result);
            logBusinessrequestService.save("IMPORT-IM-ACCOUNT", Const.N, jsonParamBody, result);
            if("FAIL".equals(ret.get("ActionStatus")+"")){
                return Result.fail(String.valueOf(ret.get("ErrorInfo")));
            }
            return Result.success(Result.SUCCESS_QUERY_MSG,result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * <b> 设置登陆用户资料 </b>
     * @author ZXF
     * @create 2021/01/30 0030 10:57
     * @version
     * @注意事项 </b>
     */
    public Result createImPortrait(Map<String,Object> params) {
        try {
            // 管理员用户名
            String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
            /*** 从缓存中拿到adminSig ***/
            String adminSig = cacheService.getTencentAdminSig(adminUserName);
            String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
            String api = ImApiConst.IM_APT_PORTRAIT_SET;
            String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            int random = (int) (((Math.random() * 9 + 1) * 100000));
            String contenttype = "json";
            tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                    + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
            String jsonParamBody = "";
            ImPortrait imPortrait = new ImPortrait();
            imPortrait.setFrom_Account(String.valueOf(params.get("mobilePhone")));
            List<ImPortraitItem> profileItems = new ArrayList<ImPortraitItem>();
            ImPortraitItem imPortraitItem = new ImPortraitItem();
            // 姓名
            imPortraitItem.setTag("Tag_Profile_IM_Nick");
            imPortraitItem.setValue(String.valueOf(params.get("name")));
            profileItems.add(imPortraitItem);
            // 头像URL
            if (params.get("photoUrl")!=null&&StringUtil.isNotEmpty(String.valueOf(params.get("photoUrl")))) {
                imPortraitItem = new ImPortraitItem();
                imPortraitItem.setTag("Tag_Profile_IM_Image");
                imPortraitItem.setValue(String.valueOf(params.get("photoUrl")));
                profileItems.add(imPortraitItem);
            }
            imPortrait.setFrom_Account(String.valueOf(params.get("mobilePhone")));
            imPortrait.setProfileItem(profileItems);
            jsonParamBody = JSON.toJSONString(imPortrait);
            jsonParamBody = jsonParamBody.replaceAll("from_Account", "From_Account");
            jsonParamBody = jsonParamBody.replaceAll("tag", "Tag");
            jsonParamBody = jsonParamBody.replaceAll("value", "Value");
            jsonParamBody = jsonParamBody.replaceAll("profileItem", "ProfileItem");
            log.info("*********jsonParamBody:" + jsonParamBody);
            log.info("*********tencentImUrl:" + tencentImUrl);
            String result = HttpUtils.postJsonString(tencentImUrl, jsonParamBody);
            log.info("*********returnImPortrait:" + result);
            JSONObject ret = JSONObject.parseObject(result);
            logBusinessrequestService.save("CREATE-IM-PORTRAIT", Const.N, jsonParamBody, result);
            if("FAIL".equals(ret.get("ActionStatus")+"")){
                return Result.fail(String.valueOf(ret.get("ErrorInfo")));
            }
            return Result.success(Result.SUCCESS_QUERY_MSG,result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * <b> 腾讯IM设置登陆用户资料 </b>
     * @author ZXF
     * @create 2021/11/22 0022 13:36
     * @version
     * @注意事项 </b>
     */
    public Result getImRoammsg(Map<String,Object> params) {
        try {
            Integer pcNo;
            Integer pageSize = Integer.parseInt(params.get("pageSize")+"");
            Integer pageNumber = Integer.parseInt(params.get("pageNumber")+"");
            if(params.get("pcNo")==null){

                // 管理员用户名
                String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
                /*** 从缓存中拿到adminSig ***/
                String adminSig = cacheService.getTencentAdminSig(adminUserName);
                String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
                String api = ImApiConst.IM_APT_GETROAMMSG;
                String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
                int random = (int) (((Math.random() * 9 + 1) * 100000));
                String contenttype = "json";
                tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                        + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
                pcNo = DateUtil.getSecondTimestamp(new Date());//当前时间
                Integer minTime = DateUtil.getSecondTimestamp(DateUtil.addDays(new Date(),-15));//历史15天
                ImRoammsg imRoammsg = new ImRoammsg();
                imRoammsg.setFrom_Account(String.valueOf(params.get("fromAccount")));
                imRoammsg.setTo_Account(String.valueOf(params.get("toAccount")));
                imRoammsg.setMaxCnt(100);
                imRoammsg.setMinTime(minTime);
                imRoammsg.setMaxTime(pcNo);
                //删除已有记录
    //            imRoammsgTempService.deleteByAccount(imRoammsg.getFrom_Account(),imRoammsg.getTo_Account());
                //调腾讯接口递归查询聊天记录存入库
                eachRoammsg(imRoammsg,tencentImUrl, pcNo);
            }else {
                pcNo = Integer.parseInt(params.get("pcNo")+"");
            }
            return imRoammsgTempService.findImRoammsgTempByPcNo(String.valueOf(params.get("fromAccount"))
                    ,String.valueOf(params.get("toAccount"))
                    ,pcNo
                    ,String.valueOf(params.get("keyword"))
                    ,pageSize
                    ,pageNumber);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    private void eachRoammsg(ImRoammsg imRoammsg, String tencentImUrl, Integer pcNo){
        String jsonParamBody = JSON.toJSONString(imRoammsg);
        jsonParamBody = jsonParamBody.replaceAll("from_Account", "From_Account")
                .replaceAll("to_Account", "To_Account")
                .replaceAll("maxCnt", "MaxCnt")
                .replaceAll("minTime", "MinTime")
                .replaceAll("maxTime", "MaxTime")
                .replaceAll("lastMsgKey", "LastMsgKey");
//        log.info("*********jsonParamBody:" + jsonParamBody);
//        log.info("*********tencentImUrl:" + tencentImUrl);
        String result = HttpUtils.postJsonString(tencentImUrl, jsonParamBody);
//        log.info("*********returnImPortrait:" + result);
        JSONObject ret = JSONObject.parseObject(result);
        String param = jsonParamBody;
        new Thread(() -> {
            logBusinessrequestService.save("GET-IM-ROAMMSG", Const.N, param, result);
        }).start();
        if("FAIL".equals(ret.get("ActionStatus")+"")){
            throw new BusinessException(Result.ERROR,ret.get("ErrorCode")+"-"+ret.get("ErrorInfo"));
        }
        JSONArray arr = (JSONArray)ret.get("MsgList");
        ImRoammsgTemp irt;
        List<ImRoammsgTemp> list = Lists.newArrayList();
        for(int i=0;i<arr.size();i++){
            String MsgBody = arr.getJSONObject(i).get("MsgBody")+"";
            MsgBody = MsgBody.replace("[{\"MsgContent\":{\"Text\":\"","");
            irt = new ImRoammsgTemp();
            irt.setContent(arr.getJSONObject(i).toJSONString());
            irt.setTextMsg(MsgBody.split("\"},\"MsgType\"")[0]);
            irt.setFromAccount(imRoammsg.getFrom_Account());
            irt.setToAccount(imRoammsg.getTo_Account());
            irt.setPcNo(pcNo);
            list.add(irt);
        }
        //批量存聊天记录
        imRoammsgTempService.batchInsert(list);
        //如果可以续拉就递归请求接口
        if("0".equals(ret.get("Complete")+"")){
            imRoammsg.setMaxTime(Integer.parseInt(ret.get("LastMsgTime")+""));
            imRoammsg.setLastMsgKey(ret.get("LastMsgKey")+"");
            eachRoammsg(imRoammsg,tencentImUrl,pcNo);
        }
    }

    /**
     * <b> 设置登陆用户资料 </b>
     * 注：跟上面im不一样的是用户名用的cid
     * @author ZXF
     * @create 2021/01/30 0030 10:57
     * @version
     * @注意事项 </b>
     */
    public Result createYSPPortrait(Map<String,Object> params) {
        try {
            // 管理员用户名
            String adminUserName = ConfigUtil.getValue(CommonConst.TENCENT_ADMIN);
            /*** 从缓存中拿到adminSig ***/
            String adminSig = cacheService.getTencentAdminSig(adminUserName);
            String tencentImUrl = ConfigUtil.getValue(CommonConst.TENCENT_IM_URL);
            String api = ImApiConst.IM_APT_PORTRAIT_SET;
            String sdkAppid = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            int random = (int) (((Math.random() * 9 + 1) * 100000));
            String contenttype = "json";
            tencentImUrl = tencentImUrl + api + "?usersig=" + adminSig + "&identifier=" + adminUserName + "&sdkappid="
                    + sdkAppid + "&random=" + random + "&contenttype=" + contenttype;
            String jsonParamBody = "";
            ImPortrait imPortrait = new ImPortrait();
            imPortrait.setFrom_Account(String.valueOf(params.get("cid")));
            List<ImPortraitItem> profileItems = new ArrayList<ImPortraitItem>();
            ImPortraitItem imPortraitItem = new ImPortraitItem();
            // 姓名
            imPortraitItem.setTag("Tag_Profile_IM_Nick");
            imPortraitItem.setValue(String.valueOf(params.get("name")));
            profileItems.add(imPortraitItem);
            // 头像URL
            if (params.get("photoUrl")!=null&&StringUtil.isNotEmpty(String.valueOf(params.get("photoUrl")))) {
                imPortraitItem = new ImPortraitItem();
                imPortraitItem.setTag("Tag_Profile_IM_Image");
                imPortraitItem.setValue(String.valueOf(params.get("photoUrl")));
                profileItems.add(imPortraitItem);
            }
            imPortrait.setFrom_Account(String.valueOf(params.get("cid")));
            imPortrait.setProfileItem(profileItems);
            jsonParamBody = JSON.toJSONString(imPortrait);
            jsonParamBody = jsonParamBody.replaceAll("from_Account", "From_Account");
            jsonParamBody = jsonParamBody.replaceAll("tag", "Tag");
            jsonParamBody = jsonParamBody.replaceAll("value", "Value");
            jsonParamBody = jsonParamBody.replaceAll("profileItem", "ProfileItem");
            log.info("*********jsonParamBody:" + jsonParamBody);
            log.info("*********tencentImUrl:" + tencentImUrl);
            String result = HttpUtils.postJsonString(tencentImUrl, jsonParamBody);
            log.info("*********returnImPortrait:" + result);
            logBusinessrequestService.save("CREATE-IM-PORTRAIT", Const.N, jsonParamBody, result);
            return Result.success(Result.SUCCESS_QUERY_MSG,result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * <b> 圈定范围建群 </b>
     *
     * @author ZXF
     * @create 2019/06/20 0020 15:47
     * @version
     * @注意事项 </b>
     */
    public Result scopeImCreateGroup(Map<String,Object> params) {
        String members = String.valueOf(params.get("members"));
        ImCreateGroup imCreateGroup = new ImCreateGroup();
        try {
            //处理MemberList  1,2admin,3,4
            String[] tels = members.split(",");
            Object[] objs = new Object[tels.length-1];
            JSONObject obj = null;
            int count = 0;
            String oAccount = "";
            for(String tel : tels){
                obj = new JSONObject();
                if(tel.contains("admin")){
                    oAccount = tel.replace("admin","");
                }else{
                    obj.put("Member_Account", tel);
                    objs[count] = obj;
                    count ++;
                }
            }
            imCreateGroup.setOwner_Account(oAccount);
            imCreateGroup.setMembers(null);
            imCreateGroup.setMemberList(objs);
            imCreateGroup.setType(String.valueOf(params.get("groupType")));
            imCreateGroup.setName(String.valueOf(params.get("groupName")));

            String tencentImGroupUrl = getImUrl(ImApiConst.IM_APT_CREATE_GROUP);
            String jsonParamBody = JSON.toJSONString(imCreateGroup);
            //首字母转大写
            jsonParamBody = JsonConverUtil.jsonParamNameFirstOneConvert(jsonParamBody, 1);
            log.info("*********tencentImUrl:" + tencentImGroupUrl);
            log.info("*********jsonParamBody:" + jsonParamBody);
            String postResult = HttpUtils.postJsonString(tencentImGroupUrl, jsonParamBody);
            log.info("*********returnPostResult:" + postResult);
            logBusinessrequestService.save("SCOPE-IM-CREATE-GROUP", Const.N, jsonParamBody, postResult);
            if (StringUtil.isEmpty(postResult)) {
                return Result.fail("IM接口返回报文为空！");
            }
            ImResult imResult = JSON.parseObject(postResult, ImResult.class);
            if(Result.SUCCESS.equals(imResult.getErrorCode())){
                // 给主管理员发系统消息
                String tencentImSendUrl = getImUrl(ImApiConst.IM_APT_SEND_SYSTEM_NOTIFICATION);
                String[] oAccounts = {oAccount};
                String content = "您已创建群组，高效、便捷的人员调度从这里开始！";
                sendSystemNotificationByIm(imResult.getGroupId(),tencentImSendUrl, oAccounts, content);

                return Result.success(Result.SUCCESS_MSG,imResult.getGroupId());
            }
            return Result.fail(imResult.getErrorInfo());
        } catch (Exception e) {
            log.error("IM群组创建业务异常！", e);
            return Result.fail("IM群组创建业务异常："+e.getMessage());
        }
    }

    /**
     * <b> 解散音视频房间 </b>
     * @author ZXF
     * @create 2019/09/19 0019 15:05
     * @version
     * @注意事项 </b>
     */
    public Result trtcVideoRoom(Map<String,Object> params) {
        String roomNo = String.valueOf(params.get("roomNo"));
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey
            String secretId = ConfigUtil.getValue(CommonConst.TENCENT_SECRETID);
            String secretKey = ConfigUtil.getValue(CommonConst.TENCENT_SECRETKEY);
            String sdkAppId = ConfigUtil.getValue(CommonConst.TENCENT_SDKAPPID);
            if(StringUtil.isEmpty(secretId)&&StringUtil.isEmpty(secretKey)&&StringUtil.isEmpty(sdkAppId)){
                return Result.fail("配置信息不完善！");
            }
            Credential cred = new Credential(secretId, secretKey);

            // 实例化要请求产品(以cvm为例)的client对象
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);
            //Region 地域：ap-beijing / ap-guangzhou
            TrtcClient client = new TrtcClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象
            DissolveRoomRequest req = new DissolveRoomRequest();
            req.setRoomId(Long.parseLong(roomNo));
            req.setSdkAppId(Long.parseLong(sdkAppId));
            // 通过client对象调用想要访问的接口，需要传入请求对象
            DissolveRoomResponse resp = client.DissolveRoom(req);
            String result = DissolveRoomRequest.toJsonString(resp);
            logBusinessrequestService.save("TRTC-VIDEO-ROOM", Const.N, JSONObject.toJSONString(req), result);
            // 输出json格式的字符串回包
            return Result.success(Result.SUCCESS_QUERY_MSG,result);
        } catch (TencentCloudSDKException e) {
            if(e.toString().contains("FailedOperation.RoomNotExist")){
                return Result.success("房间已解散");
            }else{
                return Result.fail(e.toString());
            }
        }
    }

    /**
     * <b> 初始的时候给群人员发送系统消息 </b>
     * @param groupId 群组id
     * @param apiUrl 组装好的系统消息发送接口地址
     * @param members 接收人数组
     * @param content 发送内容
     * @author ZXF
     * @create 2019/09/24 0024 10:33
     * @version
     * @注意事项 </b>
     */
    private void sendSystemNotificationByIm(String groupId, String apiUrl, String[] members, String content){
        new Thread(()->{
            JSONObject obj = new JSONObject();
            obj.put("GroupId",groupId);
            obj.put("ToMembers_Account",members);
            obj.put("Content",content);
            String jsonParamBody = obj.toJSONString();
            //首字母转大写
            jsonParamBody = JsonConverUtil.jsonParamNameFirstOneConvert(jsonParamBody, 1);
            log.info("*********tencentImUrl-send-N:" + apiUrl);
            log.info("*********jsonParamBody-send-N:" + jsonParamBody);
            String postResult = HttpUtils.postJsonString(apiUrl, jsonParamBody);
            log.info(postResult);
        }).start();
    }

    /**
     * <b> web发起音视频房间，并向被圈定人员推送房间号 </b>
     *
     * @author ZXF
     * @create 2019/06/21 0021 15:37
     * @version
     * @注意事项 </b>
     */
    public Result sendVideoRoomMsg(Map<String,Object> params) {
        String roomNo = String.valueOf(params.get("roomNo"));
        String memberList = String.valueOf(params.get("memberList"));
        String useList = String.valueOf(params.get("useList"));
        String Yardman_Name = String.valueOf(params.get("Yardman_Name"));
        String Yardman_Type = String.valueOf(params.get("Yardman_Type"));
        String Yardman_Task_Name = String.valueOf(params.get("Yardman_Task_Name"));
        String originator = String.valueOf(params.get("originator"));//发起人
        String transcriber = String.valueOf(params.get("transcriber"));//录制
        String comId = String.valueOf(params.get("comId"));
        VideoRoom videoRoom = new VideoRoom();
        videoRoom.setRoom_No(roomNo);
        videoRoom.setMemberList(memberList);
        videoRoom.setUseList(useList);
        videoRoom.setYardman_Name(Yardman_Name);
        videoRoom.setYardman_Type(Yardman_Type);
        videoRoom.setYardman_Task_Name(Yardman_Task_Name);
        videoRoom.setOriginator(originator);
        videoRoom.setTranscriber(transcriber);
        videoRoom.setComId(comId);
        String[] list = videoRoom.getMemberList().split(",");//cid
        String[] ulist = videoRoom.getUseList().split(",");//用户电话号码;用户id（tenant_user_id）;domainId;姓名;音视频type
        //先设置当前环境标识用于IOS推送条件
//        JPushUtilNew.isProEnvi(active);
        videoRoom.setMemberList(CommonConst.BLANK_CHAR);//置空
        String content = CommonConst.BLANK_CHAR;
        Long comVideoRoomId = IdWorker.getId();
        PerVideoRoom pvr;
        List<PerVideoRoom> pvrList = Lists.newArrayList();
        //组装创建人到参会列表
        pvr = new PerVideoRoom();
        String[] oArr = videoRoom.getOriginator().split(";");
        pvr.setComVideoRoomId(comVideoRoomId);
        pvr.setCid(oArr[0]);
        pvr.setUseid(oArr[1]);
        pvr.setPerVideoRoomId(IdWorker.getId());
        pvr.setIsSponsor(1);
        pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_LZ);//发起人默认录制
        pvrList.add(pvr);
        JSONObject json;
        Result getRet;
        int i = 0;
        for (String str : list) {
            //组装参会人员
            pvr = new PerVideoRoom();
            pvr.setComVideoRoomId(comVideoRoomId);
            pvr.setCid(str);
            String[] uTemp = ulist[i].split(";");
            //用户电话号码
            pvr.setUseid(uTemp[0]);
            //用户id
            pvr.setPersonId(uTemp[1]);
            //获取domainId
            pvr.setDomainId(uTemp[2]);
            pvr.setPerVideoRoomId(IdWorker.getId());
            pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_WXY);
            pvrList.add(pvr);
            if(StringUtils.isNotEmpty(videoRoom.getTranscriber())&&videoRoom.getTranscriber().contains(str)){
                videoRoom.setIsTranscribe("1");//设置成需要录制
            }else{
                videoRoom.setIsTranscribe("0");//设置成不需要录制
            }
            //设置用户id


            json = new JSONObject();
            json.put("comId",videoRoom.getComId());//发起方组织id
            json.put("useId",oArr[1]);//发起人userid
            String type = "语音";
            if(uTemp.length==5){
                json.put("name",uTemp[3]);//保安员姓名
                json.put("type",uTemp[4]);
                type = "video".equals(uTemp[4])?"视频":type;
            }
            json.put("taskName",videoRoom.getYardman_Task_Name());
            json.put("yardmanType",videoRoom.getYardman_Type());
            json.put("roomNo",videoRoom.getRoom_No());
            json.put("isTranscribe",videoRoom.getIsTranscribe());
            content = json.toJSONString();
            String[] cids = {str};
            String token = cacheService.getGeTuiToken();
            String title = "指挥调度台";
            String body = "邀请您"+type+"调度>>立即接听";
            getRet = GeTuiUtil.pushSingle(3 * 24 * 3600 * 1000, cids, token, content, title, body);
            if(GTErrorEnum.ERROR_10001.getError_msg().equals(getRet.getMsg())){
                cacheService.delGeTuiTokenCache();
            }
            i++;
        }
        //开始记录房间人数
        cacheService.setRoomPerNum(videoRoom.getRoom_No(),"1");
        //创建房间信息记录
        ComVideoRoom cvr = new ComVideoRoom();
        cvr.setComVideoRoomId(comVideoRoomId);
        cvr.setComId(videoRoom.getComId());
        cvr.setRoomNo(videoRoom.getRoom_No());
        cvr.setYardmanName(videoRoom.getYardman_Name());
        cvr.setYardmanType(videoRoom.getYardman_Type());
        cvr.setYardmanTaskName(videoRoom.getYardman_Task_Name());
        cvr.setStartTime(new Date());
        comVideoRoomService.insertComVideoRoom(cvr);
        perVideoRoomMapper.insertBatchPerVideoRoom(pvrList);
        return Result.success("已向人员发起视频通知！");
    }


    /**
     * <b> (调用uni2.0推送)web发起音视频房间，并向被圈定人员推送房间号 </b>
     *
     * @author ZXF
     * @create 2019/06/21 0021 15:37
     * @version
     * @注意事项 </b>
     */
    public Result sendVideoRoomMsgToUni2(Map<String,Object> params) {
        String roomNo = String.valueOf(params.get("roomNo"));
        String memberList = String.valueOf(params.get("memberList"));
        String useList = String.valueOf(params.get("useList"));
        String Yardman_Name = String.valueOf(params.get("Yardman_Name"));
        String Yardman_Type = String.valueOf(params.get("Yardman_Type"));
        String Yardman_Task_Name = String.valueOf(params.get("Yardman_Task_Name"));
        String originator = String.valueOf(params.get("originator"));//发起人
        String transcriber = String.valueOf(params.get("transcriber"));//录制
        String comId = String.valueOf(params.get("comId"));
        VideoRoom videoRoom = new VideoRoom();
        videoRoom.setRoom_No(roomNo);
        videoRoom.setMemberList(memberList);
        videoRoom.setUseList(useList);
        videoRoom.setYardman_Name(Yardman_Name);
        videoRoom.setYardman_Type(Yardman_Type);
        videoRoom.setYardman_Task_Name(Yardman_Task_Name);
        videoRoom.setOriginator(originator);
        videoRoom.setTranscriber(transcriber);
        videoRoom.setComId(comId);
        String[] list = videoRoom.getMemberList().split(",");//cid
        String[] ulist = videoRoom.getUseList().split(",");//用户电话号码;用户id（tenant_user_id）;domainId;姓名;音视频type
        //先设置当前环境标识用于IOS推送条件
//        JPushUtilNew.isProEnvi(active);
        videoRoom.setMemberList(CommonConst.BLANK_CHAR);//置空
        String content = CommonConst.BLANK_CHAR;
        Long comVideoRoomId = IdWorker.getId();
        PerVideoRoom pvr;
        List<PerVideoRoom> pvrList = Lists.newArrayList();
        //组装创建人到参会列表
        pvr = new PerVideoRoom();
        String[] oArr = videoRoom.getOriginator().split(";");
        pvr.setComVideoRoomId(comVideoRoomId);
        pvr.setCid(oArr[0]);
        pvr.setUseid(oArr[1]);
        pvr.setPerVideoRoomId(IdWorker.getId());
        pvr.setIsSponsor(1);
        pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_LZ);//发起人默认录制
        pvrList.add(pvr);
        JSONObject json;
        Result getRet;
        int i = 0;
        PushUni2DTO pushUni2DTO;
        for (String str : list) {
            //组装参会人员
            pvr = new PerVideoRoom();
            pvr.setComVideoRoomId(comVideoRoomId);
            pvr.setCid(str);
            String[] uTemp = ulist[i].split(";");
            //用户电话号码
            pvr.setUseid(uTemp[0]);
            //用户id
            pvr.setPersonId(uTemp[1]);
            //获取domainId
            pvr.setDomainId(uTemp[2]);
            pvr.setPerVideoRoomId(IdWorker.getId());
            pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_WXY);
            pvrList.add(pvr);
            if(StringUtils.isNotEmpty(videoRoom.getTranscriber())&&videoRoom.getTranscriber().contains(str)){
                videoRoom.setIsTranscribe("1");//设置成需要录制
            }else{
                videoRoom.setIsTranscribe("0");//设置成不需要录制
            }
            //设置用户id


            json = new JSONObject();
            json.put("comId",videoRoom.getComId());//发起方组织id
            json.put("useId",oArr[1]);//发起人userid
            String type = "语音";
            if(uTemp.length==5){
                json.put("name",uTemp[3]);//保安员姓名
                json.put("type",uTemp[4]);
                type = "video".equals(uTemp[4])?"视频":type;
            }
            json.put("taskName",videoRoom.getYardman_Task_Name());
            json.put("yardmanType",videoRoom.getYardman_Type());
            json.put("roomNo",videoRoom.getRoom_No());
            json.put("isTranscribe",videoRoom.getIsTranscribe());
            content = json.toJSONString();
            String title = "指挥调度台";
            String body = "邀请您"+type+"调度>>立即接听";
            //调uni2.0消息推送业务
            pushUni2DTO = new PushUni2DTO();
            pushUni2DTO.setTitle(title);
            pushUni2DTO.setContent(body);
            List<String> cids = new ArrayList<>();cids.add(str);
            pushUni2DTO.setClientids(cids);
            pushUni2DTO.setPayload(content);
            Result ret = sendVideoMsgByUni2(pushUni2DTO);
            if(Result.ERROR.equals(ret.getRetType())&&StringUtils.isNotEmpty(ret.getMsg())&&ret.getMsg().contains("target user is invalid")){
                String token = cacheService.getGeTuiToken();
                String[] cids1 = {str};
                getRet = GeTuiUtil.pushSingle(3 * 24 * 3600 * 1000, cids1, token, content, title, body);
                if(GTErrorEnum.ERROR_10001.getError_msg().equals(getRet.getMsg())){
                    cacheService.delGeTuiTokenCache();
                }
            }
            i++;
        }
        //开始记录房间人数
        cacheService.setRoomPerNum(videoRoom.getRoom_No(),"1");
        //创建房间信息记录
        ComVideoRoom cvr = new ComVideoRoom();
        cvr.setComVideoRoomId(comVideoRoomId);
        cvr.setComId(videoRoom.getComId());
        cvr.setRoomNo(videoRoom.getRoom_No());
        cvr.setYardmanName(videoRoom.getYardman_Name());
        cvr.setYardmanType(videoRoom.getYardman_Type());
        cvr.setYardmanTaskName(videoRoom.getYardman_Task_Name());
        cvr.setStartTime(new Date());
        comVideoRoomService.insertComVideoRoom(cvr);
        perVideoRoomMapper.insertBatchPerVideoRoom(pvrList);
        return Result.success("已向人员发起视频通知！");
    }

    /**
     * <b> uni2.0消息推送接口 </b>
     * @author ZXF
     * @create 2024/12/02 0002 16:23
     * @version
     * @注意事项 </b>
     */
    public Result sendVideoMsgByUni2(PushUni2DTO params) {
        return GeTuiUtil.pushSingleByUni2(params.getContent(), params.getTitle(), params.getClientids(), params.getPayload());
    }

    /**
     * <b> web继续向人员推送房间号 </b>
     *
     * @author ZXF
     * @create 2019/06/21 0021 15:37
     * @version
     * @注意事项 </b>
     */
    public Result continueSendVideoRoomMsg(Map<String,Object> params) {
        String roomNo = String.valueOf(params.get("roomNo"));//1
        String memberList = String.valueOf(params.get("memberList"));//1
        String useList = String.valueOf(params.get("useList"));//1
        String Yardman_Task_Name = String.valueOf(params.get("Yardman_Task_Name"));//1
        String transcriber = String.valueOf(params.get("transcriber"));//录制//1
        String comId = String.valueOf(params.get("comId"));
        ComVideoRoom comVideoRoom = comVideoRoomMapper.getByRoomNo(roomNo);
        VideoRoom videoRoom = new VideoRoom();
        videoRoom.setRoom_No(roomNo);
        videoRoom.setMemberList(memberList);
        videoRoom.setUseList(useList);
        videoRoom.setYardman_Task_Name(Yardman_Task_Name);
        videoRoom.setTranscriber(transcriber);
        videoRoom.setComId(comId);
        String[] list = videoRoom.getMemberList().split(",");
        String[] ulist = videoRoom.getUseList().split(",");
        String content;
        PerVideoRoom pvr;
        Long comVideoRoomId = comVideoRoom.getComVideoRoomId();
        List<PerVideoRoom> pvrList = Lists.newArrayList();
        JSONObject json;
        Result getRet;
        int i = 0;
        for (String str : list) {
            //组装参会人员
            pvr = new PerVideoRoom();
            pvr.setComVideoRoomId(comVideoRoomId);
            pvr.setCid(str);
            String[] uTemp = ulist[i].split(";");
            //用户电话号码
            pvr.setUseid(uTemp[0]);
            //用户id
            pvr.setPersonId(uTemp[1]);
            pvr.setDomainId(uTemp[2]);
            pvr.setPerVideoRoomId(IdWorker.getId());
            pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_WXY);
            pvrList.add(pvr);
            if(StringUtils.isNotEmpty(videoRoom.getTranscriber())&&videoRoom.getTranscriber().contains(str)){
                videoRoom.setIsTranscribe("1");//设置成需要录制
            }else{
                videoRoom.setIsTranscribe("0");//设置成不需要录制
            }
            json = new JSONObject();
            json.put("comId",videoRoom.getComId());
            json.put("useId",ulist[i]);
            String type = "语音";
            if(uTemp.length==5){
                json.put("name",uTemp[3]);//保安员姓名
                json.put("type",uTemp[4]);
                type = "video".equals(uTemp[4])?"视频":type;
            }
            json.put("taskName",videoRoom.getYardman_Task_Name());
            json.put("yardmanType","1");
            json.put("roomNo",videoRoom.getRoom_No());
            json.put("isTranscribe",videoRoom.getIsTranscribe());
            content = json.toJSONString();
            String[] cids = {str};
            String token = cacheService.getGeTuiToken();
            String title = "指挥调度台";
            String body = "邀请您"+type+"调度>>立即接听";
            getRet = GeTuiUtil.pushSingle(3 * 24 * 3600 * 1000,cids,token,content,title,body);
            if(GTErrorEnum.ERROR_10001.getError_msg().equals(getRet.getMsg())){
                cacheService.delGeTuiTokenCache();
            }
            i++;
        }
        perVideoRoomMapper.insertBatchPerVideoRoom(pvrList);
        return Result.success("已向人员发起视频通知！");
    }

    /**
     * <b> web继续向人员推送房间号 </b>
     *
     * @author ZXF
     * @create 2019/06/21 0021 15:37
     * @version
     * @注意事项 </b>
     */
    public Result continueSendVideoRoomMsgToUni2(Map<String,Object> params) {
        String roomNo = String.valueOf(params.get("roomNo"));//1
        String memberList = String.valueOf(params.get("memberList"));//1
        String useList = String.valueOf(params.get("useList"));//1
        String Yardman_Task_Name = String.valueOf(params.get("Yardman_Task_Name"));//1
        String transcriber = String.valueOf(params.get("transcriber"));//录制//1
        String comId = String.valueOf(params.get("comId"));
        ComVideoRoom comVideoRoom = comVideoRoomMapper.getByRoomNo(roomNo);
        VideoRoom videoRoom = new VideoRoom();
        videoRoom.setRoom_No(roomNo);
        videoRoom.setMemberList(memberList);
        videoRoom.setUseList(useList);
        videoRoom.setYardman_Task_Name(Yardman_Task_Name);
        videoRoom.setTranscriber(transcriber);
        videoRoom.setComId(comId);
        String[] list = videoRoom.getMemberList().split(",");
        String[] ulist = videoRoom.getUseList().split(",");
        String content;
        PerVideoRoom pvr;
        Long comVideoRoomId = comVideoRoom.getComVideoRoomId();
        List<PerVideoRoom> pvrList = Lists.newArrayList();
        JSONObject json;
        PushUni2DTO pushUni2DTO;
        int i = 0;
        for (String str : list) {
            //组装参会人员
            pvr = new PerVideoRoom();
            pvr.setComVideoRoomId(comVideoRoomId);
            pvr.setCid(str);
            String[] uTemp = ulist[i].split(";");
            //用户电话号码
            pvr.setUseid(uTemp[0]);
            //用户id
            pvr.setPersonId(uTemp[1]);
            pvr.setDomainId(uTemp[2]);
            pvr.setPerVideoRoomId(IdWorker.getId());
            pvr.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_WXY);
            pvrList.add(pvr);
            if(StringUtils.isNotEmpty(videoRoom.getTranscriber())&&videoRoom.getTranscriber().contains(str)){
                videoRoom.setIsTranscribe("1");//设置成需要录制
            }else{
                videoRoom.setIsTranscribe("0");//设置成不需要录制
            }
            json = new JSONObject();
            json.put("comId",videoRoom.getComId());
            json.put("useId",ulist[i]);
            String type = "语音";
            if(uTemp.length==5){
                json.put("name",uTemp[3]);//保安员姓名
                json.put("type",uTemp[4]);
                type = "video".equals(uTemp[4])?"视频":type;
            }
            json.put("taskName",videoRoom.getYardman_Task_Name());
            json.put("yardmanType","1");
            json.put("roomNo",videoRoom.getRoom_No());
            json.put("isTranscribe",videoRoom.getIsTranscribe());
            content = json.toJSONString();
//            String[] cids = {str};
//            String token = cacheService.getGeTuiToken();
            String title = "指挥调度台";
            String body = "邀请您"+type+"调度>>立即接听";
            //调uni2.0消息推送业务
            pushUni2DTO = new PushUni2DTO();
            pushUni2DTO.setTitle(title);
            pushUni2DTO.setContent(body);
            List<String> cids = new ArrayList<>();cids.add(str);
            pushUni2DTO.setClientids(cids);
            pushUni2DTO.setPayload(content);
            sendVideoMsgByUni2(pushUni2DTO);
            i++;
        }
        perVideoRoomMapper.insertBatchPerVideoRoom(pvrList);
        return Result.success("已向人员发起视频通知！");
    }

    /**
     * <b> 发送广播消息给指定人员 </b>
     * @author ZXF
     * @create 2024/01/17 0017 14:41
     * @version
     * @注意事项 </b>
     */
    public Result sendBroadcastMsg(BroadcastDto dto) {
        String[] cids = dto.getCids().toArray(new String[dto.getCids().size()]);
        String token = cacheService.getGeTuiToken();
        Result getRet = GeTuiUtil.pushListMessage(3 * 24 * 3600 * 1000, token, JSONObject.toJSONString(dto.getData()), dto.getTitle(), dto.getContent());
        if("0".equals(getRet.getRetType())){
            JSONObject json = (JSONObject)getRet.getData();
            String taskId = (String)json.get("taskid");
            log.error("======> sendBroadcastMsg task:"+taskId);
            getRet = GeTuiUtil.pushListCid(cids, token, taskId, true);
        }
        log.error("======> sendBroadcastMsg ret:"+JSON.toJSONString(getRet));
        if(GTErrorEnum.ERROR_10001.getError_msg().equals(getRet.getMsg())){
            cacheService.delGeTuiTokenCache();
        }
        return getRet;
    }

    /**
     * <b> (调用uni2.0推送)发送广播消息给指定人员 </b>
     * @author ZXF
     * @create 2024/01/17 0017 14:41
     * @version
     * @注意事项 </b>
     */
    public Result sendBroadcastMsgToUni2(BroadcastDto dto) {
        //调uni2.0消息推送业务
        PushUni2DTO pushUni2DTO = new PushUni2DTO();
        pushUni2DTO.setTitle(dto.getTitle());
        pushUni2DTO.setContent(dto.getTitle());
        pushUni2DTO.setClientids(dto.getCids());
        pushUni2DTO.setPayload(JSONObject.toJSONString(dto.getData()));
        log.error("======> sendBroadcastMsgToUni2 params:"+JSON.toJSONString(pushUni2DTO));
        Result ret = sendVideoMsgByUni2(pushUni2DTO);
        log.error("======> sendBroadcastMsgToUni2 result:"+JSON.toJSONString(ret));
        return ret;
    }

    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(Result.success("推送成功")));
    }

    public Result test1() {
        return GeTuiUtil.test1(cacheService.getGeTuiToken());
    }

    public Result videoCallBack(Map<String,Object> param) {
        if(true){
            return Result.fail("接口暂停服务");
        }
        if(param == null){
            return Result.fail("接收不到回调信息");
        }
        String file_id = param.get("file_id")!=null?String.valueOf(param.get("file_id")):"";
        String start_time = param.get("start_time")!=null?String.valueOf(param.get("start_time")):"";
        String end_time = param.get("end_time")!=null?String.valueOf(param.get("end_time")):"";
        String stream_id = param.get("stream_id")!=null?String.valueOf(param.get("stream_id")):"";
        String video_url = param.get("video_url")!=null?String.valueOf(param.get("video_url")):"";
        if(perVideoRoomMapper.getPerVideoRoomFileId(file_id) != null){
            return Result.fail("回调信息已接收");
        }
        if(StringUtils.isNotEmpty(video_url)){
            String platform = ConfigUtil.getValue("ENVI_PROD");
            video_url = M3u8ToMp4.getMp4ByM3u8(video_url,platform);
        }
        System.out.println("videoCallBack.M3u8ToMp4.video_url："+video_url);
        PerVideoRoom perVideoRoom = null;
        if(StringUtils.isNotEmpty(stream_id)){
            String roomNo = stream_id.split("_")[1];
            //TODO 腾讯回调会给useid么
            String useid = stream_id.split("_")[2];
            perVideoRoom = perVideoRoomMapper.getByUseidAndCid(roomNo, useid);
        }
        if(perVideoRoom == null){
            return Result.fail("未找到参会人员记录");
        }
        perVideoRoom.setFileId(file_id);
        perVideoRoom.setStreamId(stream_id);
        perVideoRoom.setVideoPath(video_url);
        if(StringUtils.isNotEmpty(start_time)){
            perVideoRoom.setStartTime(cn.hutool.core.date.DateUtil.date(Long.parseLong(start_time+"000")));
        }
        if(StringUtils.isNotEmpty(end_time)){
            perVideoRoom.setEndTime(cn.hutool.core.date.DateUtil.date(Long.parseLong(end_time+"000")));
        }
        perVideoRoom.setAttendExpoStatus(DictConst.ATTENDEXPOSTATUS_LZ);
        perVideoRoomMapper.updateVideo(perVideoRoom);
        return Result.success("回调信息已接收");
    }

    /**
     * 获取腾讯音视频sig信息
     * @param cid app个推唯一标识码
     * @param name
     * @param photoUrl
     * @param isShare
     * @date 2020-05-06
     * @auth zxf
     * @return
     */
    public Result getTencentYSPSig(Map params) {
        String sig = null;
        if(StringUtil.isNotEmpty(String.valueOf(params.get("cid")))) {
            try {
                //是否共享，如果共享就加标识头
                String share = "";
                if("1".equals(params.get("isShare"))){
                    share = "share_";
                }
                sig = cacheService.getYSPSig(share + params.get("cid"));
                createYSPPortrait(params);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return Result.success(Result.SUCCESS_QUERY_MSG, sig);
    }

    /**
     * <b> 分页查询调度记录 </b>
     * @author ZXF
     * @create 2020/06/22 0022 10:41
     * @version
     * @注意事项 </b>
     */
    public Result findComVideoRoomPage(Map<String,Object> params) {
        ComVideoRoom comVideoRoom = new ComVideoRoom();
        comVideoRoom.setComId(String.valueOf(params.get("comId")));
        comVideoRoom.setPageNumber(Integer.parseInt(String.valueOf(params.get("pageNumber"))));
        comVideoRoom.setPageSize(Integer.parseInt(String.valueOf(params.get("pageSize"))));
        comVideoRoom.setYardmanTaskName(params.get("yardmanTaskName")!=null?String.valueOf(params.get("yardmanTaskName")):"");
        return comVideoRoomService.findComVideoRoomPage(comVideoRoom);
    }

    /**
     * <b> 调度记录详情 </b>
     * @author ZXF
     * @create 2020/06/23 0023 10:48
     * @version
     * @注意事项 </b>
     */
    public Result getVideoRoomDetail(Map<String,Object> params) {
        ComVideoRoom comVideoRoom = new ComVideoRoom();
        comVideoRoom.setComVideoRoomId(Long.parseLong(String.valueOf(params.get("comVideoRoomId"))));
        return comVideoRoomService.getComVideoRoom(comVideoRoom);
    }

    /**
     * <b> APP设置参会人员视频接听状态 </b>
     * @author ZXF
     * @create 2020/06/23 0023 11:01
     * @version
     * @注意事项 </b>
     */
    public Result updatePerVideoRoomStatus(Map<String,Object> params) {
        VideoRoomDto dto = new VideoRoomDto();
        dto.setRoomNo(String.valueOf(params.get("roomNo")));
        dto.setCid(String.valueOf(params.get("cid")));
        dto.setUseid(String.valueOf(params.get("useid")));
        dto.setAttendExpoStatus(String.valueOf(params.get("attendExpoStatus")));
        //房间是否已被解散
        String str = cacheService.getRoomPerNum(dto.getRoomNo());
        if(StringUtils.isEmpty(str)){
            return Result.fail("房间已解散！");
        }

        PerVideoRoom perVideoRoom = perVideoRoomMapper.getByUseidAndCid(dto.getRoomNo(), dto.getUseid());
        perVideoRoomMapper.updateStatus(perVideoRoom.getPerVideoRoomId(),dto.getAttendExpoStatus());
        //如果接听，房间人数+1
        if(DictConst.ATTENDEXPOSTATUS_JS.equals(dto.getAttendExpoStatus())){
            cacheService.setRoomPerNum(dto.getRoomNo(),String.valueOf(Integer.parseInt(str) + 1));
        }
        return Result.success(Result.SUCCESS_QUERY_MSG);
    }

    /**
     * <b> 设置房间结束时间 </b>
     * @author ZXF
     * @create 2020/06/23 0023 11:01
     * @version
     * @注意事项 </b>
     */
    public Result updateRoomEndTime(Map<String,Object> params) {
        ComVideoRoom comVideoRoom = new ComVideoRoom();
        comVideoRoom.setRoomNo(String.valueOf(params.get("roomNo")));
        String str = cacheService.getRoomPerNum(comVideoRoom.getRoomNo());
        if(StringUtils.isEmpty(str)){
            return Result.success("房间已解散！");
        }
        int num = Integer.parseInt(str) - 1;
        cacheService.setRoomPerNum(comVideoRoom.getRoomNo(),String.valueOf(num));
        return comVideoRoomService.updateEndTime(comVideoRoom);
    }

    /**
     * <b> app用户点退出房间时计算房间人数，=0时记录最后时间、解散房间 </b>
     * @author ZXF
     * @create 2020/07/10 0010 14:07
     * @version
     * @注意事项 </b>
     */
    public Result statisticsPerNum(Map<String,Object> params) {
        ComVideoRoom comVideoRoom = new ComVideoRoom();
        comVideoRoom.setRoomNo(String.valueOf(params.get("roomNo")));
        String str = cacheService.getRoomPerNum(comVideoRoom.getRoomNo());
        if(StringUtils.isEmpty(str)){
            return Result.success("房间已解散！");
        }
        int num = Integer.parseInt(str) - 1;
        if(num == 0){
            //设置房间结束时间
            Result result = comVideoRoomService.updateEndTime(comVideoRoom);
            if(Result.ERROR.equals(result.getRetType())){
                return result;
            }
            //解散房间业务
            Map map = Maps.newHashMap();
            map.put("room_No",comVideoRoom.getRoomNo());
            map.put("region","ap-beijing");
            result = trtcVideoRoom(map);
            if(Result.ERROR.equals(result.getRetType())){
                throw new BusinessException(Result.ERROR, result.getMsg());
            }
        }else{
            cacheService.setRoomPerNum(comVideoRoom.getRoomNo(),String.valueOf(num));
        }
        return Result.success(Result.SUCCESS_QUERY_MSG,String.valueOf(num));
    }
}
