<template>
  <div class="store-page">
    <Breadcrumb />

    <a-card title="座位查询">
      <AppQueryFilter>
        <a-row class="queryForm app-query-form query-row">
          <a-col :flex="'900px'" class="query-main">
            <a-form :model="query" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="查询账号">
                    <a-select v-model="query.username" placeholder="请选择账号" allow-search>
                      <a-option v-for="item in accounts" :key="item.username" :value="item.username">
                        {{ item.username }}({{ item.realname || '未知' }})
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="座位区域">
                    <a-cascader
                      v-model="query.roomId"
                      :options="menu"
                      placeholder="请选择座位区域"
                      :field-names="{ label: 'name', value: 'id', children: 'children' }"
                      check-strictly
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="查询日期">
                    <a-date-picker v-model="query.date" placeholder="请选择日期" style="width: 100%" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider class="query-divider" style="height: 42px" direction="vertical" />
          <a-col :flex="1" class="app-query-actions">
            <a-button type="primary" @click="searchSeats">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-col>
        </a-row>
      </AppQueryFilter>
    </a-card>

    <a-card style="margin-top: 16px">
      <a-result v-if="noAccount" status="warning" title="您还没有可使用的统一身份认证账号">
        <template #extra>
          <a-button type="primary" @click="$router.push({ name: 'jwAccount.accountList' })">去添加</a-button>
        </template>
      </a-result>

      <a-spin v-else :loading="loading" style="width: 100%">
        <a-empty v-if="!loading && seats.length === 0" description="请选择条件后查询座位" />
        <a-row v-else :gutter="16">
          <a-col v-for="item in seats" :key="item.devId" :xs="24" :sm="12" :md="8" :lg="6" style="margin-bottom: 16px">
            <a-card hoverable>
              <template #title>
                <a-space>
                  <a-badge :status="item.resvInfo?.length ? 'warning' : 'success'" />
                  {{ item.devName }}
                </a-space>
              </template>
              <p><b>座位区域：</b>{{ item.labName }} - {{ item.roomName }}</p>
              <p>
                <b>占用时段：</b>
                <template v-if="item.resvInfo?.length">
                  <span v-for="(record, index) in item.resvInfo" :key="index">
                    <span v-if="index">、</span>
                    {{ formatTimestamp(record.startTime) }}~{{ formatTimeOnly(record.endTime) }}
                  </span>
                </template>
                <span v-else>空闲</span>
              </p>
              <p><b>预约时长：</b>{{ item.resvRule?.minResvTime }}~{{ item.resvRule?.maxResvTime }}分</p>
              <p><b>提前预约：</b>{{ item.resvRule?.deadlineTime }}~{{ item.resvRule?.rangeNum }}天</p>
              <template #actions>
                <span @click="openOrderModal(item)"><icon-rocket /> 立即预约</span>
                <span @click="handleAddStar(item)"><icon-plus-circle /> 加入志愿</span>
              </template>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>
    </a-card>

    <a-modal
      v-model:visible="orderVisible"
      title="预定座位"
      @before-ok="submitOrder"
      :ok-loading="orderSaving"
      draggable
      esc-to-close
    >
      <a-form :model="orderForm" layout="vertical">
        <a-form-item label="申请人" required>
          <a-select v-model="orderForm.username" placeholder="请选择申请账号">
            <a-option v-for="item in accounts" :key="item.username" :value="item.username">
              {{ item.username }}({{ item.realname || '未知' }})
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="申请时间" required>
          <a-range-picker
            v-model="orderForm.dateRange"
            show-time
            format="YYYY-MM-DD HH:mm"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { getJwAccount } from '@/api/jwAccount'
import { getSeatMenu, getSeatInfo, orderSeat, saveStar } from '@/api/ic'
import { formatTimestamp, formatTimeOnly, formatDateCompact } from '@/utils/icTime'

const loading = ref(false)
const noAccount = ref(false)
const orderVisible = ref(false)
const orderSaving = ref(false)
const accounts = ref([])
const menu = ref([])
const seats = ref([])
const currentSeat = ref(null)

const query = reactive({
  username: '',
  roomId: [],
  date: new Date()
})

const orderForm = reactive({
  username: '',
  dateRange: []
})

const loadAccounts = async () => {
  const res = await getJwAccount()
  if (res?.code !== 0) {
    Notification.error({ title: '获取账号失败', content: res?.msg })
    return
  }
  const verified = (res.data || []).filter((item) => item.state === 1)
  accounts.value = verified
  noAccount.value = verified.length === 0
  if (verified.length) {
    query.username = verified[0].username
    orderForm.username = verified[0].username
    await loadMenu()
  }
}

const loadMenu = async () => {
  if (!query.username) return
  const res = await getSeatMenu({ username: query.username })
  if (res?.code !== 0) {
    Notification.error({ title: '获取位置目录失败', content: res?.msg })
    return
  }
  menu.value = res.data || []
}

const searchSeats = async () => {
  if (!query.username || !query.roomId?.length || !query.date) {
    Notification.warning({ title: '请完整填写查询条件' })
    return
  }
  loading.value = true
  try {
    const roomId = query.roomId[query.roomId.length - 1]
    const date = formatDateCompact(query.date instanceof Date ? query.date : new Date(query.date))
    const res = await getSeatInfo({ username: query.username, roomId, date })
    if (res?.code !== 0) {
      Notification.error({ title: '获取座位信息失败', content: res?.msg })
      return
    }
    seats.value = res.data || []
  } finally {
    loading.value = false
  }
}

const openOrderModal = (item) => {
  currentSeat.value = item
  const baseDate = query.date instanceof Date ? query.date : new Date(query.date)
  orderForm.dateRange = [baseDate, baseDate]
  orderVisible.value = true
}

const formatDateTime = (date) => {
  const d = date instanceof Date ? date : new Date(date)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${y}-${m}-${day} ${h}:${min}:00`
}

const submitOrder = async () => {
  if (!orderForm.username || orderForm.dateRange?.length !== 2) {
    Notification.error({ title: '请完整填写预约信息' })
    return false
  }
  orderSaving.value = true
  try {
    const res = await orderSeat({
      resvDev: [currentSeat.value.devId],
      resvBeginTime: formatDateTime(orderForm.dateRange[0]),
      resvEndTime: formatDateTime(orderForm.dateRange[1]),
      username: orderForm.username
    })
    if (res?.code !== 0) {
      Notification.error({ title: '预约失败', content: res?.msg })
      return false
    }
    Notification.success({ title: '预约成功', content: '请按时前往预定位置，避免违约' })
    return true
  } catch (error) {
    Notification.error({ title: '预约失败', content: error.message })
    return false
  } finally {
    orderSaving.value = false
  }
}

const handleAddStar = async (item) => {
  const res = await saveStar({ devId: item.devId, name: item.devName })
  if (res?.code !== 0) {
    Notification.error({ title: '添加志愿失败', content: res?.msg })
    return
  }
  Notification.success({ title: '添加成功', content: '您可在志愿列表中查看' })
}

onMounted(loadAccounts)
</script>

<style scoped>
p {
  margin: 4px 0;
  font-size: 13px;
}
</style>
