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

    <a-card title="我的预约">
      <AppQueryFilter>
        <a-row class="queryForm app-query-form query-row">
          <a-col :flex="'700px'" 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="12">
                  <a-form-item label="查询账号">
                    <a-select v-model="query.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-col>
                <a-col :span="12">
                  <a-form-item label="查询日期">
                    <a-range-picker v-model="query.dateRange" 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="refreshTable">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-col>
        </a-row>
      </AppQueryFilter>

      <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-table
        v-else
        row-key="uuid"
        :data="data"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
        :scroll="{ x: 1100 }"
      >
        <template #columns>
          <a-table-column title="预约日期" data-index="resvDate" :width="120" />
          <a-table-column title="开始时间" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.resvBeginTime) }}</template>
          </a-table-column>
          <a-table-column title="结束时间" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.resvEndTime) }}</template>
          </a-table-column>
          <a-table-column title="预定时间" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.resvCheckTime) }}</template>
          </a-table-column>
          <a-table-column title="实际结束" :width="170">
            <template #cell="{ record }">{{ formatTimestamp(record.resvEndRealTime) }}</template>
          </a-table-column>
          <a-table-column title="座位信息" :width="180">
            <template #cell="{ record }">
              {{ record.resvDevInfoList?.[0]?.roomName }}-{{ record.resvDevInfoList?.[0]?.devName }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="180" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-popconfirm content="该操作不可逆，确认取消预约？" @ok="handleDelete(record)">
                  <a-button type="text" status="danger" size="small">取消预约</a-button>
                </a-popconfirm>
                <a-popconfirm content="确认提前结束本次预约？" @ok="handleEndAhead(record)">
                  <a-button type="text" size="small">提前结束</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { getJwAccount } from '@/api/jwAccount'
import { myOrder, deleteSeat, endAhead } from '@/api/ic'
import { formatTimestamp, formatDateStr } from '@/utils/icTime'

const loading = ref(false)
const noAccount = ref(false)
const accounts = ref([])
const data = ref([])

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

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

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
    await loadList()
  }
}

const loadList = async () => {
  if (!accounts.value.length) return
  loading.value = true
  try {
    const beginDate = formatDateStr(query.dateRange[0] instanceof Date ? query.dateRange[0] : new Date(query.dateRange[0]))
    const endDate = formatDateStr(query.dateRange[1] instanceof Date ? query.dateRange[1] : new Date(query.dateRange[1]))
    const res = await myOrder({
      username: query.username,
      beginDate,
      endDate,
      page: pagination.current,
      pageNum: pagination.pageSize
    })
    if (res?.code !== 0) {
      Notification.error({ title: '获取预约信息失败', content: res?.msg })
      return
    }
    data.value = Array.isArray(res.data) ? res.data : res.data?.list || []
    pagination.total = res.data?.count ?? data.value.length
  } finally {
    loading.value = false
  }
}

const refreshTable = () => {
  pagination.current = 1
  loadList()
}

const onPageChange = (page) => {
  pagination.current = page
  loadList()
}

const handleDelete = async (record) => {
  const res = await deleteSeat({ username: record.logonName, seatuuid: record.uuid })
  if (res?.code !== 0) {
    Notification.error({ title: '取消预约失败', content: res?.msg })
    return
  }
  Notification.success({ title: '取消预约成功' })
  loadList()
}

const handleEndAhead = async (record) => {
  const res = await endAhead({ username: record.logonName, seatuuid: record.uuid })
  if (res?.code !== 0) {
    Notification.error({ title: '提前结束失败', content: res?.msg })
    return
  }
  Notification.success({ title: '提前结束成功' })
  loadList()
}

onMounted(loadAccounts)
</script>
