<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="1">当前可用</el-radio-button>
          <el-radio-button label="2">一小时后可用</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker
            v-model="queryParams.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="timeRange">
        <el-time-picker style="width: 100px"
                        v-model="queryParams.start_time"
                        format="HH:mm"
                        placeholder="开始时间"
                        @change="updateAppointTime"
        />
        <span style="margin: 0 2px">至</span>
        <el-time-picker style="width: 100px"
                        v-model="queryParams.end_time"
                        format="HH:mm"
                        placeholder="结束时间"
                        @change="updateAppointTime"
        />
      </el-form-item>
      <el-form-item label="会议名称" prop="search">
        <el-input
            v-model="queryParams.search"
            placeholder="请输入会议名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </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-row :gutter="10" class="mb8">

    </el-row>

    <el-table v-loading="loading" :data="waringList" @selection-change="handleSelectionChange">
      <el-table-column label="会议名称" align="center" prop="name" />
      <el-table-column label="会议类型" align="center" prop="room_type_name" />
      <el-table-column label="容纳人数" align="center" prop="seats">
        <template #default="scope">
          <span>{{ scope.row.seats === 0 ? '无限制' : scope.row.seats }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预定时间段" align="center">
        <template #default="scope">
          <div v-if="scope.row.usage.appointTime.length > 0">
        <span v-for="(time, index) in scope.row.usage.appointTime" :key="index">
          {{ time.start_time }} - {{ time.end_time }}
          <br v-if="index < scope.row.usage.appointTime.length - 1" />
        </span>
          </div>
          <span v-else>无预定</span>
        </template>
      </el-table-column>
      <el-table-column label="设备" align="center" prop="device_names" />
      <el-table-column label="创建时间" align="center" prop="created_at" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.created_at, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="Meeting">
import { ElMessage } from "element-plus";
import axios from "axios";

const { proxy } = getCurrentInstance();
const {alarm_level} = proxy.useDict('alarm_level');

const waringList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: '', // 默认选中"全部"
    date: new Date().toISOString().split('T')[0], // 格式化为YYYY-MM-DD
    appoint_time: "", // 重置为空
    start_time: "",
    end_time: "",
    interfaceName:"会议预订",
    search: '' // 搜索文本默认为空
  },
});

const { queryParams, form, rules } = toRefs(data);

watch(() => queryParams.value.status, (newStatus) => {
  if(newStatus === "1") { // 当前可用
    queryParams.value.appoint_time = getCurrentTimeRange();
  } else if(newStatus === "2") { // 一小时后可用
    queryParams.value.appoint_time = getCurrentTimeRange(1, true);
  } else {
    queryParams.value.appoint_time = ""; // 选择"全部"时清空
  }
});

function updateAppointTime() {
  if(queryParams.value.start_time && queryParams.value.end_time) {
    queryParams.value.appoint_time = `${queryParams.value.start_time}~${queryParams.value.end_time}`;
  }
}

/** 查询设备告警列表 */
const getList = async () => {
  try {
    loading.value = true;

    // 构建请求数据
    const requestData = {
      date: queryParams.value.date,
      search: queryParams.value.search,
      locationId: [],
      capacity: [],
      deviceType: [],
      roomType: [-1],
      appoint_time: queryParams.value.appoint_time,
      status: 1,
      page: queryParams.value.pageNum,
      page_size: queryParams.value.pageSize
    };

    const response = await axios.post(`${__LOCAL_API__}/Conference/getRoomsByLocation`, requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 修改这里：正确处理返回的数据结构
    if (response.data.code === 200) {
      waringList.value = response.data.data.list || [];
      total.value = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 表单重置
function reset() {
  form.value = {
    status: '', // 默认选中"全部"
    date: new Date(), // 默认当天
    appoint_time: '', // 时间默认为空
    search: '' // 搜索文本默认为空
  };
  proxy.resetForm("waringRef");
}

function getCurrentTimeRange(hoursLater = 0, fullHour = false) {
  const now = new Date();
  now.setHours(now.getHours() + hoursLater);

  const startHours = now.getHours().toString().padStart(2, '0');
  const startMinutes = now.getMinutes().toString().padStart(2, '0');

  let endHours, endMinutes;
  if(fullHour) {
    // 计算一小时后的时间
    const endTime = new Date(now.getTime() + 60 * 60 * 1000);
    endHours = endTime.getHours().toString().padStart(2, '0');
    endMinutes = endTime.getMinutes().toString().padStart(2, '0');
  } else {
    // 只增加一分钟
    endHours = startHours;
    endMinutes = (now.getMinutes() + 1).toString().padStart(2, '0');
  }

  return `${startHours}:${startMinutes}~${endHours}:${endMinutes}`;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备告警";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWaring(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备告警";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["waringRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWaring(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWaring(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备告警编号为"' + _ids + '"的数据项？').then(function() {
    return delWaring(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('waring/waring/export', {
    ...queryParams.value
  }, `waring_${new Date().getTime()}.xlsx`)
}

getList();
</script>
