<template>
    <div class="p-2">
      <el-row :gutter="20"> 
        <el-col :lg="24" :xs="24">
          <transition>
            <div class="mb-[10px]" v-show="showSearch">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
                  <el-form-item label="房间名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入房间名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="发起人" prop="owner_uid">
                    <el-input
                      v-model="queryParams.owner_uid"
                      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 style="width: 240px">
                      <el-option v-for="dict in sys_normal_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="创建时间" style="width: 308px;">
                    <el-date-picker
                      v-model="dateRange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                    <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>
  
          <el-card shadow="hover">
            <template #header>
              <el-row :gutter="10"> 
              </el-row>
            </template> 
            <el-table v-loading="loading" :data="roomList" width='100%'>
              <el-table-column label="房间编号" align="center" prop="uid" />
              <el-table-column label="房间名称" align="center" prop="name" :show-overflow-tooltip="true" />  
              <el-table-column label="发起人" align="center" prop="owner_uid"/>
              <el-table-column label="最大人数" align="center" prop="max_participants"/>
              <!-- <el-table-column label="备注" align="center" prop="description"  :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="created_at">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.created_at) }}</span>
                </template>
              </el-table-column> 
              <el-table-column label="操作" fixed="right" class-name="small-padding fixed-width">
                <template #default="scope"> 
                  <el-tooltip content="删除" placement="top" v-if="scope.row.status === 3">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                  </el-tooltip> 
                  <el-tooltip content="参与者信息" placement="top">
                    <el-button link type="primary" icon="User" @click="handleAuthRole(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>
        </el-col>
      </el-row>  
    </div>
</template>
  
  <script setup name="userManagement">
  import { listRoom ,delRoom} from "@/api/room.js"   
  import { ElMessage ,ElMessageBox} from "element-plus"; 
  const router = useRouter();
  const roomList = ref();
  const loading = ref(true);
  const showSearch = ref(true);
  const total = ref(0);
  const dateRange = ref(['', '']);   
  const sys_normal_status = ref([
    {
      label: '进行中',
      value: 1
    },
    {
      label: '已结束',
      value: 3
    }
  ])
  const STATUS_CONFIG = ref({
    1: { type: 'success', text: '进行中' },
    3: { type: 'danger', text: '已结束' }, 
  });

   
  const queryFormRef = ref(); 
  
  const data = reactive({ 
    queryParams: {
      page: 1,
      page_size: 10,
      name: '',
      owner_uid: '', 
      status: undefined,
      min_created_at: '',
      max_created_at: '',
    }, 
  })
  
  const { queryParams } = toRefs(data)

  
  /** 查询用户列表 */
  const getList = async () => {
    loading.value = true;
    if(dateRange.value.length > 0 && dateRange.value[0] && dateRange.value[1]){
        queryParams.value.min_created_at = +new Date(dateRange.value[0]);
        queryParams.value.max_created_at = +new Date(dateRange.value[1]);
    } 
    const res = await listRoom(queryParams.value); 
    loading.value = false;
    roomList.value = res.data.data;
    total.value = res.data.total;
  }

  /** 跳转参与者信息 */
const handleAuthRole = (row) => { 
  router.push("/room-auth/room/" + row.uid);
}
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.page = 1
    getList()
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    dateRange.value = ['', '']
    queryParams.value.min_created_at = ''
    queryParams.value.max_created_at = ''
    queryFormRef.value?.resetFields();
    queryParams.value.page = 1; 
    handleQuery();
  }

    /**删除按钮操作 */
    const handleDelete = async (row) => { 
    try { 
        await ElMessageBox.confirm(
            `确认要删除"${row.name}" 房间吗?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );  
        // delete_participants:是否同时删除参与者信息，默认false
        const res = await delRoom(row.uid,{delete_participants:true});
        if(res.meta.code !== 200){
            ElMessage.error(res.data.message);
            return;
        } 
        getList();
        ElMessage.success(`${row.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.name}房间删除失败`);
    }    
  }
  
  onMounted(() => { 
    getList()
  });
  </script>
  
  <style lang="scss" scoped></style>
  