<template> 
    <div> 
        <div class="app-container" v-loading="load" :element-loading-text="loadText">
            <el-row :gutter="6" style="padding: 0 10px; background: #fefefe"> 
                <el-col :xs="24" :sm="24" :md="8" :lg="6">
                <leftTab
                    @updateDetail="updateDetail"
                    @updateTab="updateTab" 
                    :loading="!detail?.appId && !detail?.userId && isShow"
                />
                </el-col> 
                <el-col :xs="24" :sm="24" :md="16" :lg="18">
                <div
                    class="right-content"  
                    v-loading='isShowLoading'
                > 
                    <div class="right-content-title">
                    {{ tabValue == 1 ? '协作信息' : '员工信息' }}   
                    </div>
                    <div
                        class="agency-detail-massage-cont right-content-message"
                        v-if="isShow && tabValue == 1" 
                    >
                    <div class="agency-detail-cont-item">
                        <span class="agency-detail-item-title">发起人</span>
                        <span class="agency-detail-item-content">
                        {{ detail.initiator }}
                        </span>
                    </div>
                    <div class="agency-detail-cont-item">
                        <span class="agency-detail-item-title">协作时间</span>
                        <span class="agency-detail-item-content">
                        {{
                            detail.created_at ?
                            parseTime(detail.created_at, '{y}年{m}月{d}日') +
                            ' ' +
                            weekName[new Date(detail.created_at).getDay()] +
                            ' ' +
                            parseTime(detail.created_at, '{h}:{i}')
                            : '暂无'
                        }}
                        </span>
                    </div>
                    <div class="agency-detail-cont-item">
                        <span class="agency-detail-item-title">成员</span>
                        <span
                        class="agency-detail-item-content"
                        v-if="detail?.all_participants?.length"
                        style="display: flex; flex-wrap: wrap"
                        >
                        <span
                            v-for="(items, indexs) in detail.all_participants"
                            :key="indexs"
                        >
                            {{
                            (items.display_name || items.user_uid) +
                            (indexs + 1 == detail.all_participants.length
                                ? ''
                                : '、')
                            }}
                        </span>
                        </span>
                    </div>
                    <div class="agency-detail-cont-item">
                        <span class="agency-detail-item-title">协作时长</span>
                        <span class="agency-detail-item-content">
                        {{ getTime() }}
                        </span>
                    </div>
                    </div>
        
                    <div class="right-content-file" v-if="isShow && tabValue == 1" >
                    <el-row :gutter="15">
                        <el-col :xs="24" :sm="24" :md="16" :lg="18">
                        <div class="content-file-video">
                            <div class="file-top">协作视频</div>
                            <div class="file-video-bottom">
                            <!-- autoplay="autoplay" -->
                            <video
                                v-if="detail.remoteVideoFile?.storage_url"
                                :src="detail.remoteVideoFile.storage_url"
                                id="videoPlayer" 
                                loop
                                autoplay
                                controls
                            ></video>
                            <div v-else class="video-null">暂无视频</div>
                            </div>
                        </div>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="8" :lg="6">
                        <div>
                            <div class="file-top">
                            附件（{{
                                detail?.fileList?.length ? detail.fileList.length : 0
                            }}）
                            </div>
                            <div class="content-file-list">
                            <el-scrollbar
                                class="file-list"
                                height="calc(100vh - 390px)"
                            >
                                <div
                                class="file-list-content"
                                v-if="detail?.fileList?.length"
                                >
                                <div
                                    class="file-list-item"
                                    v-for="(item, index) in detail.fileList"
                                    :key="index"
                                >
                                    <div class="file-list-item-icon"></div>
                                    <div class="file-list-item-text">
                                    <div class="list-item-text text-out-of-hiding-1">
                                        {{ item.file_name }}
                                    </div> 
                                    <el-icon
                                        :size="18"
                                        color="#0d74ff"
                                        style="cursor: pointer"
                                        @click="handlePreview(item)"
                                        >
                                        <View />
                                    </el-icon>
                                    <el-link
                                        :href="item.source_url"
                                        type="primary"
                                        target="_blank"
                                        :underline="false"
                                    >
                                        <el-icon
                                            :size="18"
                                            color="#0d74ff"
                                            style="cursor: pointer"
                                            >
                                            <Download />
                                        </el-icon>
                                    </el-link> 
                                    </div>
                                </div>
                                </div>
                            </el-scrollbar>
                            </div>
                        </div>
                        </el-col>
                    </el-row>
                    </div>
                    <div
                    class="message-user"
                    v-else-if="isShow && tabValue == 2"
                    style="height: calc(100vh - 90px)"  
                    v-loading="userLoading"
                    >
                    <div class="message-user-card">
                        <div class="user-card-nickName">
                        <img v-if="detail.avatar" :src="detail.avatar" />
                        <img v-else src="@/assets/images/profile.jpg" />
                        <span>{{ detail.nickName || detail.name || '暂无信息' }}</span>
                        </div>
                        <div class="user-card-information">
                        <div class="user-information-item">
                            <div class="user-information-title">
                            <img src="@/assets/images/user-information1.png" alt="" />
                            <span>性别</span>
                            </div>
                            <div class="user-information-text">
                            <!-- <dict-tag
                                v-if="detail.sex"
                                :options="sys_user_sex"
                                :value="detail.sex"
                            />
                            <div v-else>
                                {{ '暂无' }}
                            </div> -->
                            </div>
                        </div>
                        <div class="user-information-item">
                            <div class="user-information-title">
                            <img src="@/assets/images/user-information2.png" alt="" />
                            <span>手机号</span>
                            </div>
                            <div class="user-information-text">
                            {{ detail.phonenumber || '暂无' }}
                            </div>
                        </div>
                        <div class="user-information-item">
                            <div class="user-information-title">
                            <img src="@/assets/images/user-information3.png" alt="" />
                            <span>邮箱</span>
                            </div>
                            <div class="user-information-text">
                            {{ detail.email || '暂无' }}
                            </div>
                        </div>
                        <div class="user-information-item">
                            <div class="user-information-title">
                            <img src="@/assets/images/user-information4.png" alt="" />
                            <span>所属部门</span>
                            </div>
                            <div class="user-information-text">
                            {{ detail.organization || '暂无' }}
                            </div>
                        </div>
                        </div>
                        <div class="user-card-btn">
                            <el-button 
                                type="info" 
                                @click="clickInitiate"
                                :loading="initiateLoading"
                                :disabled="initiateLoading"
                            >
                                {{ initiateLoading ? '正在发起邀请' : '发起协作' }}
                            </el-button>
                        </div> 
                    </div>
                    </div>
                    <div v-else class="message-null">
                    <el-empty description="暂无内容" />
                    </div>
                </div>
                </el-col>
            </el-row>  
            <!-- <el-dialog
                v-model="inviteDialog"
                title="远程协作"
                width="400px"
                :close-on-press-escape="false"
                :close-on-click-modal="false"
                :show-close="false"
            > 

                <div style="width: 100%; margin-bottom: 30px; font-size: 20px">
                    "
                    {{
                    socketInformation.room_name
                        ? socketInformation.room_name
                        : ''
                    }}
                    " 邀请您参加远程协作
                </div>
                <div style="text-align: center">
                    <el-button
                    size="large"
                    type="danger"
                    style="font-size: 16px"
                    @click="clickRefuseJoin"
                    >
                    拒 绝
                    </el-button>
                    <el-button
                    size="large"
                    type="primary"
                    style="font-size: 16px"
                    @click="clickJoin"
                    >
                    加 入
                    </el-button> 
                </div>
            </el-dialog> -->
        </div> 
         <!-- 文件预览 -->
         <BrowseFile ref="browseFileRef" />   
    </div>
</template>

<script setup> 
import { onActivated, onMounted, reactive, toRefs, watch, getCurrentInstance ,ref} from 'vue'  
import leftTab from './components/leftTab/index.vue' 
import AssistWx from './components/assistWx/index.vue'
import BrowseFile from '@/views/conferencingRoom/components/fileUpload/browseFile.vue'
import { getInfo } from '@/api/login.js'
import { getStatusApi ,getFileListApi ,getvideoUrlApi,getRoomToken,getInvite} from '@/api/conferencingRoom.js'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { useRoomStore } from '@/stores/modules/room'
import { useUserStore } from '@/stores/modules/user.js'
import { mqttClient } from "@/utils/mqtt.js"; 
import { getToken ,getUserInfo} from '@/utils/auth.js';
import { deepClone,parseTime } from '@/utils/ruoyi.js' 
const roomStore = useRoomStore() 
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const state = reactive({ 
  detail: {},
  weekName: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
  tabValue: 1,
  isShow: true,
  isShowLoading: false,
  load: false,
  loadText: '数据加载中', 
  isLinkKnow: 'F',
  socketInformation: null,
  inviteDialog: false,
  cooperation: import.meta.env.VITE_APP_COOPERATION_TYPE,
  initiateLoading: false, 
}) 
const userLoading = ref(false); // 用户信息加载状态 
//文件预览
const browseFileRef = ref(null);

const isEmptyObject = (obj) => {
  return !obj || Object.keys(obj).length === 0
}

/** 发起协作邀请 */
const clickInitiate = async () => {
    state.initiateLoading = true
    let userData = null
    try {
        try {
            userData = JSON.parse(sessionStorage.getItem('userData')) || null
        } catch (e) {
            console.error('解析 userData 失败:', e)
        } 
    

    if (isEmptyObject(state.detail)) {
        ElMessage({
        message: '请先选择人员',
        type: 'warning',
        })
        return
    }
    if(state.detail.uid == userData.uid){
        ElMessage({
        message: '不能邀请自己',
        type: 'warning',
        })
        return
    } 
    roomStore.setUserUid(userData.uid)
    roomStore.setDetailUid(state.detail.uid) 
    roomStore.setDetailName(state.detail.name)

    //创建房间
    const res = await getRoomToken({max_participants: 20}); 
    if(res.meta.code != 200){
        ElMessage.error(res.meta.message); 
        return;
    } 
    if(res.data.room.uid){
        await getInvite(res.data.room.uid,{participants:[{user_uid:state.detail.uid,display_name:state.detail.name}], participant_role: "participant"})
    } 
    router.push({
        path: '/conferencingRoom', 
        query:{ 
            room_uid:res.data.room.uid
        }
    })  
    } catch (error) {
        console.error('发起协作失败:', error)
        ElMessage.error('发起协作失败，请重试')
    } finally {
        // 无论成功失败，都重置按钮状态
        state.initiateLoading = false
    }
}

/** 修改展示列表 */
const updateTab = (newValue) => {
  state.detail = {}
  state.tabValue = newValue
}

/** 修改展示区内容 */
const updateDetail = async (details) => {  
    userLoading.value = true 
  if (details) { 
    state.detail = {}
    if (state.tabValue == 1) {
        state.isShowLoading = true
      getTheFileList(details)
    } else { 
        const res = await getInfo(details.uid)    
          state.detail = res.data  
          userLoading.value = false  
    }
  }  
  userLoading.value = false 
}

const getTheFileList = async (details) => {
    try {
        let detail = deepClone(details); 
        const [fileResponse, videoResponse] = await Promise.all([
            getFileListApi(details.room_uid),
            getvideoUrlApi(details.room_uid)
        ]); 
        const processedDetail = {
            ...details,
            fileList: fileResponse.data?.files || [],
            remoteVideoFile: videoResponse.data?.recordings?.[0] || {},
            initiator: details.all_participants?.find(item => 
                item.participant_role === 'moderator' // 使用严格相等
            )?.display_name || '未知发起人'
        }; 
        state.detail = processedDetail;
        state.isShowLoading = false; 
    } catch (error) {
        console.error('获取文件列表失败:', error);
        // 可以根据需要添加错误处理逻辑
    }
}

/** 获取通话时长 */
const getTime = () => {
  let begin = new Date(state.detail.created_at).getTime()
  let end = new Date(state.detail.updated_at).getTime()
  if (begin && end) {
    let diff = end - begin
    const h = Math.floor(diff / (1000 * 60 * 60))
    const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
    const s = Math.floor((diff % (1000 * 60)) / 1000)
    return h > 0 ? `${h}小时 ${m}分钟 ${s}秒`
      : m > 0 ? `${m}分钟 ${s}秒`
      : `${s}秒`
  } else {
    return '暂无'
  }
}

//文件预览
function handlePreview(file) { 
  if (!file.preview_url) {
    ElMessage.error('文件链接无效');
    return;
  }
  browseFileRef.value.showEdit(file) 
}

/** 加入会议 */
// const clickJoin = async () => { 
//   const res = await getStatusApi(state.socketInformation.room_uid,{status:1}) 
//     if(res.meta.code == 200){
//         ElMessage({
//             message: '成功加入该协作',
//             type: 'success',
//         })
//         state.inviteDialog = false
//         router.push({
//         path: '/conferencingRoom', 
//         query:{
//             type:2,//创建房间，加入房间 2
//             room_uid:state.socketInformation.room_uid
//         }
//     }) 
//     }
//   state.inviteDialog = false
 
// }

/** 拒绝加入 */
// const clickRefuseJoin = async () => {
//     //status  1: 同意加入, 5: 拒绝加入
//      const res = await getStatusApi(state.socketInformation.room_uid,{status:5}) 
//     if(res.meta.code == 200){
//         ElMessage({
//             message: '已拒绝加入该协作',
//             type: 'error',
//         })
//         state.inviteDialog = false
//     }
// }

/** 处理加入房间和拒接房间 mqtt 消息 */
// const processingSocket = (message) => { 
//     const res = JSON.parse(message)  
//   if (!res?.status) { 
//     state.socketInformation = res  
//       state.inviteDialog = true
//       showNotification(state.socketInformation)
//   }else if(res.status == 5){
//     ElMessage({
//         message: `${res?.display_name}拒绝加入该协作`,
//         type: 'error',
//     })
//   }
// }

/** 浏览器通知 */
// const showNotification = (data) => { 
//   if ('Notification' in window) {
//     Notification.requestPermission().then((permission) => {
//       if (permission === 'granted') {
//         const notification = new Notification('协作邀请', {
//         //   body: String(data.room_name) + '邀请您参加远程协作'
//         body: '远程协作有新的邀请'
//         //   icon: logo,
//         })
//         notification.onclick = () => { clickJoin() }
//       }
//     })
//   }
// }


// 暴露给模板
const { detail, weekName, tabValue, isShow, load, loadText, isLinkKnow, socketInformation, inviteDialog, cooperation,isShowLoading ,initiateLoading } = toRefs(state)
// onMounted(async () => {    
//     await mqttClient.connect(`room${Math.random().toString(16).substr(2, 8)}`);
//     const res = await userStore.getInfo()
//     const topic = `xSynergy/ROOM/+/rooms/${res.uid}`;
//     mqttClient.subscribe(topic, async (shapeData) => { 
//         // console.log(shapeData.toString(),'shapeData发送邀请')
//         processingSocket(shapeData.toString())
//     }); 
// })

</script>


<style lang="scss" scoped>
.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.app-container {
//   padding: 20px;
  // margin: 0 17px; 
  height: calc(100vh - 50px); 
  overflow: auto;
}   

.message-null {
  @extend .flex;
  height: calc(100vh - 90px);
}

.right-content {
  height: calc(100vh - 90px);
  background: #f4f9ff;  
  .right-content-title {
    @extend .flex;
    justify-content: space-between;
    width: 100%;
    height: 50px;
    padding: 0 20px;
    background: #666666;
    color: #fff;
    font-size: 18px;
  }

  .right-content-message {
    width: calc(100% - 30px);
    height: 150px;
    margin: 15px;
    background: #fff;
    border-radius: 10px;
  }

  .right-content-file {
    width: calc(100% - 30px);
    height:calc(100% - 230px);
    margin: 0 15px 15px; 
  }

  .file-top {
    @extend .flex;
    justify-content: flex-start;
    height: 50px;
    padding-left: 20px;
    background: #e6f1ff;
    color: #333;
    font-size: 18px;
  }

  .content-file-video {
    .file-video-bottom {
      width: 100%;
      height: calc(100vh - 360px);
      padding: 15px;
      background: #fff;

      video {
        width: 100%;
        height: 100%;
      }
    }
  }
  .content-file-list {
    background: #fff;
    padding: 15px 5px 15px 10px;

    .file-list {
      width: 100%;
      padding-right: 10px;

      .file-list-content {
        @extend .flex;
        flex-direction: column;
        width: 100%;

        .file-list-item {
          @extend .flex;
          width: 100%;
          margin-bottom: 15px;

          .file-list-item-icon {
            width: 13px;
            height: 13px;
            margin-right: 10px;
            border-radius: 50%;
            background: #89b2ff;
          }

          .file-list-item-text {
            @extend .flex;
            justify-content: space-between;
            width: calc(100% - 23px);
            padding: 13px 6px 13px 6px;
            border-radius: 4px;
            background: #f4f9ff;

            .list-item-text {
              display: inline-block;
              width: calc(100% - 50px);
              margin-right: 2px;
            }
          }
        }
      }
    }
  }
}

.message-user {
  @extend .flex;
  overflow: auto;

  .message-user-card {
    @extend .flex;
    flex-direction: column;
    width: 500px;
    height: 95%;
    max-height: 550px;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;

    .user-card-nickName {
      @extend .flex;
      flex-direction: column;
      width: 100%;
      height: 40%;
      background: linear-gradient(
        180deg,
        rgba(153, 153, 153, 0.22) 0%,
        rgba(153, 153, 153, 0) 100%
      );

      img {
        width: 100px;
        height: 100px;
        margin-top: 10%;
        margin-bottom: 20px;
        border-radius: 50%;
        background: #167bff;
        flex-shrink: 0;
      }

      span {
        color: #051435;
        font-size: 24px;
      }
    }

    .user-card-information {
      @extend .flex;
      flex-direction: column;
      justify-content: space-around;
      width: 100%;
      height: 45%;

      .user-information-item {
        @extend .flex;
        justify-content: space-between;

        .user-information-title {
          @extend .flex;
          justify-content: flex-start;
          width: 150px;

          img {
            width: 24px;
            height: 24px;
            margin-right: 20px;
          }

          span {
            color: #999;
            font-size: 16px;
          }
        }

        .user-information-text {
          width: 130px;
          color: #333333;
          font-size: 16px;
          font-weight: 600;
        }
      }
    }
    .user-card-btn {
      @extend .flex;
      width: 100%;
      height: 15%;
    }
  }
}

.video-null {
  color: #999;
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

::v-deep .user-card-btn .el-button {
  width: 70%;
  height: 55%;
  border-radius: 25px;
  font-size: 18px;
  color: #fff;
}
</style>