
<template>
    <!-- 无人机拖动视频 -->
    <DraggerAble v-if="showVideo" v-model="showVideo" ref="RefEqripment"></DraggerAble>
    <!-- 新增音视频会议 -->
    <AudioAndVoice v-model="showDailog" v-if="showDailog"></AudioAndVoice>
    <!-- 音视频会议窗口 -->
    <MeetingView v-model="openMeeting" v-if="openMeeting" ></MeetingView>
</template>

<script setup>
import { getItem } from "@/utils/storage";
import { timeValidate } from '@/utils/tools'
import DraggerAble from './components/draggerAble.vue'
import useConfernceEvent from './components/js/useConfernceEvent';
import { ElMessage,ElMessageBox,ElNotification } from "element-plus";
import useBaseDataModule from '@/components/Consultation/sdk/baseData';
import AudioAndVoice from './components/audioAndVoice.vue'
import MeetingView from './components/meetingView.vue'
import { defineExpose , nextTick, onMounted, onUnmounted, defineEmits, ref} from 'vue';
import { useStore } from "vuex";
const emit = defineEmits(['update']);
const modleType = ref('')
const store = useStore();
const inDustRialId = getItem('inDustRialId'); // 当前用户的警号
const sdkBDModule = useBaseDataModule();
const baseInfo = ref(getItem('rhInfo') || {});
const showVideo = ref(false)//拖动视频
const showDailog = ref(false)//showDailog
const openMeeting = ref(false) //打开会议
const jsonData = ref('');
const loginStatusCallbackId = ref() //token监听状态
const RefEqripment = ref()
const meetList = ref([
    {
        "basedata_id": "8180e3882a0c27f4d3ba998b3dc95c0d280d8e2e7a9d53e4ac36c7ade2c76653",
        "guid": "2a7931e2-5fe6-493b-b918-cd4f220ee62e",
        "number": "908479232",
        "puc_id": "00001",
        "realm": "puc.com",
        "subject": "sgxtcs 预约的会议",
        "type": 1,
        "duration": 30,
        "pre_alarm_time": 1,
        "remark": "",
        "start_date_time": "2025-12-11T02:01:19Z",
        "end_date_time": "2025-12-11T02:01:19Z",
        "create_date_time": "2025-12-11T02:01:19Z",
        "status": 0,
        "lock": 0,
        "emergency_flag": 0,
        "appointment": "2025-12-10T14:57:24Z",
        "creator": {
            "basedata_id": "8180e3882a0c27f4cc200f7987d695ff3ce5274244ba3974e0064423dfe70f71",
            "guid": "Dispatcher::sgxtcs@puc.com",
            "alias": "sgxtcs",
            "nick": "sgxtcs",
            "role": 2
        },
        "members": [
            {
                "basedata_id": "8180e3882a0c27f4cc200f7987d695ff3ce5274244ba3974e0064423dfe70f71",
                "guid": "Dispatcher::sgxtcs@puc.com",
                "alias": "sgxtcs",
                "nick": "sgxtcs",
                "role": 2,
                "joined": 0,
                "speaking_state": 0,
                "member_state": 0,
                "microphone_status": 1,
                "camera_status": 1,
                "prohibition_status": 0,
                "mute_status": 0,
                "device_type": 0,
                "terminal_model": "",
                "full_duplex": 1,
                "raise_hand": 0,
                "removed_flag": 0,
                "join_date_time": "",
                "left_date_time": "",
                "member_remark": "",
                "e2ee_flag": 0,
                "emergency_flag": 0,
                "voice_value": 0
            }
        ]
    }
])

// n 推迟几分钟 - 不传默认10
const handleTime = (n=10) =>{
    var currentDate = new Date();
    var preDate = new Date(currentDate.getTime() + n * 60 * 1000)
    let time = timeValidate(preDate);
    return new Date(time).toISOString()
}

// 创建会议
const conferenceActionSDK = async (record ) => {
    let data = {
        subject: record.hsbt, //主题
        type: 1, //会议类型 0=即时会议，1=预约会议
        emergency_flag: 0, //会议紧急标识 0 = 非紧急会议，1 = 紧急会议
        duration: 60, //预计时长 (分钟)
        pre_alarm_time: 10, //提前通知时间（分钟）
        remark: '',
        appointment: handleTime(), // start_date 和 start_time 对应的 UTC 时间
        members:[
            {
                alias:baseInfo.value.dispatcher_name,
                basedata_id:baseInfo.value.basedata_id,
                guid:baseInfo.value.user_guid,
                number:baseInfo.value.user_id,
            }
        ],//当前创建人
    }
    const createRes = await lemon.conference.createConference(data);
    if (createRes.result === 0) {
        ElMessage.success(jsonData.value['data']['conference.book.result.ok']);
        record.number = createRes.meeting.number;
        emit('update',record);
        enterConferenceByNumber(record) //进入会议
    } else {
        ElMessage.error(jsonData.value['errorCode'][createRes?.result]);
    }
};

// 通过会议编号进入会议
const enterConferenceByNumber = (it) =>{
    openMeeting.value = true;
    nextTick(()=>{
        let params = {
            "number": it.number,
            "nick": it.glxsmc,
            "mute_status": 0,
            "microphone_status": 1,
            "camera_status": 1
        }
        lemon.conference.enterConferenceByNumber(params).then(res=> {
            console.log(res,'=======加入会议=======');
        }).catch(err=> {
            console.log(err,' 加入会议失败......');
        })
    })
}

// 获取会议
const fetchConferences = (it) =>{
    lemon.conference.fetchConferences().then(res=> {
        meetList.value = res.conferenceList; 
        let obj = meetList.value.find(v=>v.number == it.number);
        // 会议存在 ? 进入会议 : 创建会议 ;
        obj ? enterConferenceByNumber(it) : conferenceActionSDK(it) ;
    }).catch(err=> {})
}

// 初始化后需要监听的方法
const listenerEvents = () =>{
    getLoginAccountInfo() //前账号的登录信息
    useConfernceEvent()// 注册会议管理相关事件
    // 无人机对讲机的监听时事件
    window.lemon.call.addMediaStream((call_id, stream, type) => {
        // console.log(call_id, stream, type,'=======无人机对讲机的监听时事件==');
    });
}

const  getLoginAccountInfo =() =>{
    lemon.login.getLoginAccountInfo().then(res => {
        let info = JSON.stringify(res.account_info)
        baseInfo.value = res.account_info;
        window.localStorage.setItem("rhInfo",info);
        window.localStorage.setItem("user_basedata_id",res.account_info.basedata_id);
   }).catch(err => {
         
   })   
}

// 加入会议
const openInit = (it,type) =>{
    modleType.value = type;
    if(type == '会议'){
        //判断是否有会议号
        let into = it.number ? '确定开始会议?' : '没有找到会议，是否创建会议?'
        ElMessageBox.confirm(into,'提示',{
            confirmButtonText:'确定',
            cancelButtonText:'取消',
            type:'warning',
        }).then(res=>{
            // 会议号存在 ?  获取会议列表里面是否包含该条会议 : 创建会议 ;
            it.number ? fetchConferences(it) : conferenceActionSDK(it);
        }).catch(()=>{ })
    }

    if(['对讲机','无人机'].includes(type)){
        showVideo.value = true;
        nextTick(()=>{
            RefEqripment.value.handleBtn(type)
        })
    }
}


const Init = () => {
  let token = window.localStorage.getItem("rhToken");
  if (!token || 'undefined' == token || token == 'null') {
    let userInfo = {
      username: 'sgxtcs', //用户名
    //   username: inDustRialId, //用户名
      password: "123456",
      realm: "puc.com",
      webpucUrl: "https://89.40.9.95:16888"
    };
    lemon.login.login(userInfo).then((esacpe) => {
      token = esacpe.token;
      window.localStorage.setItem("rhToken", esacpe.token);
      listenerEvents()
    })
  } else {
    ConnectWebsocket(token);
  }
};

const ConnectWebsocket = (token) => {
  lemon.login.reConnectWebsocket({
    username: 'sgxtcs', //用户名
    // username: inDustRialId, //用户名
    realm: "puc.com",
    webpucUrl: "https://89.40.9.95:16888",
    token: token
  }).then((resp) => {
        if(resp.result != 0){
            localStorage.removeItem('rhToken')
            localStorage.removeItem('user_basedata_id')
            let messge = jsonData.value['errorCode'][resp.result] +',请重新刷新页面'
            ElMessage.error(messge);
            lemon.login.logout().then(res=> {}).catch(err=> {})   
        }else{
            listenerEvents();
       }
  });
};

onMounted(()=>{
    jsonData.value = require('./components/zh_CN.json');
    nextTick(()=>{
        Init();
    })
});

onUnmounted(()=>{
    //  页面关闭时卸载
    lemon.login.removeLoginStatusChangeListener(loginStatusCallbackId.value);
})

defineExpose({openInit,Init});
</script>

<style lang="scss" scoped>
.meeting-box{
    display: flex;
    width: 100%;
    height: 100%;
    background: rgba(15,30,52,1);
    .meun{
        width: 80px;
        height: 100%;
        background: rgba(0, 40, 108,1);
        border-right: 1px solid #0072ff;
        .item{
            width: 80px;
            height: 74px;
            line-height: 74px;
            background: linear-gradient(90deg,rgba(12,162,255,1) 0% , rgba(162, 247, 255,0) 100%);
            filter: drop-shadow(0 16px 16px rgba(0,0,0,.25));
            text-align: center;
            position: relative;
            cursor: pointer;
            .edg{
                display: block;
                position: absolute;
                left: 0;
                top: 0;
                width: 4px;
                height: 100%;
                border-top-right-radius: 4px;
                border-bottom-right-radius: 4px;
                background-color:rgba(172,249,255,1);
            }
        }
        
    }
    .list-box{
        width: 200px;
        background: rgba(0, 53, 123,1);
        padding: 4px 10px;
        box-sizing: border-box;
        .list{
            margin-top: 10px;
            height: calc(100% - 30px);
        }
    }
    .cnt{
        flex: 1 0 0;
    }
}
::v-deep .el-collapse-item__header{
    background: transparent;
    color: #fff;
    border-bottom: 1px solid #2e4b6e;
}
::v-deep .el-collapse-item__wrap{
    background-color: transparent;
    border-bottom: none;
}
::v-deep .el-collapse-item__content{
    color: #fff;
}
::v-deep .el-collapse{
    border-top: none;
    border-bottom: none;
}
</style>