<template>
  <div class="p-2">
    <transition>
      <div class="search mb-[10px]">
        <el-card shadow="hover">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true">
            <el-form-item label="参与者名称" prop="display_name" :label-width="120">
              <el-input
                v-model="queryParams.display_name"
                placeholder="请输入参与者名称"
                clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="状态" clearable>
                  <el-option v-for="dict in statusList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select> 
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="userList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="参与者名称"
          prop="display_name"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="STATUS_CONFIG[scope.row.status]?.type">
              {{ STATUS_CONFIG[scope.row.status]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="参与角色" align="center" prop="participant_role">
          <template #default="scope">
            {{ scope.row.participant_role == "moderator" ? "发起者" : "参与者" }}
          </template>
        </el-table-column>
        <el-table-column label="参与时间" align="center" prop="duration">
          <template #default="scope">
            {{ formatMinutesSeconds(scope.row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="created_at" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.created_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="踢出房间" placement="top" v-if="scope.row.status === 1">
              <el-button
                link
                type="primary"
                icon="CircleClose"
                @click="removeParticipantHandld(scope.row)"
              >
              </el-button> 
            </el-tooltip>
            <el-tooltip content="静音" placement="top" v-if="scope.row.status === 1">
              <el-button
                link
                type="primary"
                icon="Mute"
                @click="muteParticipantHandld(scope.row)"
              >
              </el-button> 
            </el-tooltip>
            <!-- <el-tooltip content="解除静音" placement="top" v-if="scope.row.status === 1">
              <el-button
                link
                type="primary"
                icon="Microphone"
                @click="muteParticipantHandld(scope.row)"
              >
              </el-button> 
            </el-tooltip>  -->
            <el-tooltip content="删除" placement="top" >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.page_size"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup name="authRole">
import { participantUserList, delParticipant ,removeParticipant ,muteParticipant} from "@/api/room.js";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const STATUS_CONFIG = {
  1: { type: "success", text: "已同意并加入" },
  2: { type: "info", text: "离开房间" },
  3: { type: "warning", text: "被踢出房间" },
  4: { type: "warning", text: "已邀请但未同意" },
  5: { type: "danger", text: "拒绝加入" },
  6: { type: "danger", text: "异常退出房间" },
}
const statusList = [
    {
      label: "已同意并加入",
      value: 1,
    },
    {
      label: "离开房间",
      value: 2,
    },
    {
      label: "被踢出房间",
      value: 3,
    },
    {
      label: "已邀请但未同意",
      value: 4,
    },
    {
      label: "拒绝加入",
      value: 5,
    },
    {
      label: "异常退出房间",
      value: 6,
    }
]

const userList = ref([]);
const loading = ref(true);
const total = ref(0);

const queryFormRef = ref();

const queryParams = reactive({
  page: 1,
  page_size: 10,
  room_uid: route.params.roomId,
  display_name: undefined,
  status: undefined,
});
// 格式化时分秒时间
function formatMinutesSeconds(seconds) {
  if (!seconds && seconds !== 0) return "0秒";

  if (seconds < 60) {
    return `${seconds}秒`;
  }

  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;

  if (secs === 0) {
    return `${mins}分钟`;
  }

  return `${mins}分${secs}秒`;
}

/** 查询当前用户下的角色 */
const getList = async () => {
  loading.value = true;
  const res = await participantUserList(queryParams);
  userList.value = res.data.data;
  total.value = res.data.total;
  loading.value = false;
};
// 返回按钮
const handleClose = () => {
  router.push("/roomManagement/RoomManagementPage");
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}; 

const muteParticipantHandld = async (row) =>{
    try{
        //muted  true  静音  false 解除禁用
        const res = await muteParticipant(row.room_uid, { muted: true ,participant_uid:row.user_uid});
        if (res.meta.code !== 200) {
            ElMessage.error(res.data.message);
            return;
        }
        getList();
        ElMessage.success(`${row.display_name}参与者静音成功`);

    }catch(err){
        ElMessage.error(`${row.display_name}参与者静音失败`);
    } 
}


const removeParticipantHandld = async (row) => {
  try {
    await ElMessageBox.confirm(`确认要踢出"${row.display_name}" 参与者吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
  
    const res = await removeParticipant(row.room_uid, { participant_uid: row.user_uid });
    if (res.meta.code !== 200) {
      ElMessage.error(res.data.message);
      return;
    }
    getList();
    ElMessage.success(`${row.display_name}参与者踢出成功`);
  } catch (err) { 
    const errorMsg = err?.toString() || ''; 
    if (errorMsg.includes('cancel') || 
        errorMsg.includes('取消') || 
        errorMsg === 'cancel' || 
        err === 'cancel') { 
        return;
    }    
    if (errorMsg.includes('close') || err === 'close') { 
        return;
    }
    ElMessage.error(`${row.display_name}参与者踢出失败`);
  }
};


/**删除按钮操作 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认要删除"${row.display_name}" 参与者吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // delete_participants:是否同时删除参与者信息，默认false
    const res = await delParticipant(row.room_uid, { user_uid: row.user_uid });
    if (res.meta.code !== 200) {
      ElMessage.error(res.data.message);
      return;
    }
    getList();
    ElMessage.success(`${row.display_name}参与者删除成功`);
  } catch (err) { 
    const errorMsg = err?.toString() || ''; 
    if (errorMsg.includes('cancel') || 
        errorMsg.includes('取消') || 
        errorMsg === 'cancel' || 
        err === 'cancel') { 
        return;
    }    
    if (errorMsg.includes('close') || err === 'close') { 
        return;
    }
    ElMessage.error(`${row.display_name}参与者删除失败`);
  }
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped></style>
