<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="趣选书查询管理">
      <AppQueryFilter>
        <a-row class="query-row">
          <a-col :flex="'1000px'" class="query-main">
            <a-form class="queryForm app-query-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 field="username" label="趣选书账号">
                    <a-input v-model="query.username" placeholder="登录账号" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="realname" label="姓名">
                    <a-input v-model="query.realname" placeholder="真实姓名" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="email" label="邮箱">
                    <a-input v-model="query.email" placeholder="邮箱" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="mobile" label="手机号">
                    <a-input v-model="query.mobile" placeholder="手机号" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="className" label="班级">
                    <a-input v-model="query.className" placeholder="班级名称" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="termName" label="学期">
                    <a-input v-model="query.termName" placeholder="学期名称" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="queryTime" label="查询时间">
                    <a-range-picker v-model="query.queryTime" show-time format="YYYY-MM-DD HH:mm" value-format="x" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider class="query-divider" style="height: 84px" direction="vertical" />
          <a-col :flex="1" class="app-query-actions">
            <a-space class="query-actions-space" direction="vertical" :size="18">
              <a-button type="primary" @click="search">搜索</a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </AppQueryFilter>

      <a-table
        :bordered="false"
        class="table"
        :data="data"
        :loading="loading"
        :scroll="{ x: 1320 }"
        :pagination="{
          showPageSize: true,
          showJumper: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="ID" data-index="id" :width="80" />
          <a-table-column title="趣选书账号" data-index="username" :width="160" ellipsis tooltip />
          <a-table-column title="姓名" data-index="realname" :width="120" ellipsis tooltip />
          <a-table-column title="班级" data-index="className" :width="160" ellipsis tooltip />
          <a-table-column title="邮箱" data-index="email" :width="180" ellipsis tooltip />
          <a-table-column title="手机号" data-index="mobile" :width="130" ellipsis tooltip />
          <a-table-column title="学期" data-index="termName" :width="180" ellipsis tooltip />
          <a-table-column title="书籍数量" data-index="book_count" :width="100" />
          <a-table-column title="查询时间" :width="170">
            <template #cell="{ record }">{{ formatTime(record.create_time) }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="100" :fixed="tableFixed('right')">
            <template #cell="{ record }">
              <a-button type="text" size="small" @click="openDetail(record)">查看书单</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="detailVisible"
      :title="detailTitle"
      width="960px"
      hide-cancel
      esc-to-close
      draggable
    >
      <a-descriptions v-if="detail" :column="2" bordered size="medium" style="margin-bottom: 16px">
        <a-descriptions-item label="账号">{{ detail.username }}</a-descriptions-item>
        <a-descriptions-item label="姓名">{{ detail.realname || '-' }}</a-descriptions-item>
        <a-descriptions-item label="班级">{{ detail.className || '-' }}</a-descriptions-item>
        <a-descriptions-item label="邮箱">{{ detail.email || '-' }}</a-descriptions-item>
        <a-descriptions-item label="手机号">{{ detail.mobile || '-' }}</a-descriptions-item>
        <a-descriptions-item label="学期" :span="2">{{ detail.termName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="查询时间" :span="2">{{ formatTime(detail.create_time) }}</a-descriptions-item>
      </a-descriptions>

      <a-table
        :bordered="false"
        :data="detail?.bookList || []"
        :loading="detailLoading"
        :pagination="false"
        :scroll="{ x: 900 }"
        stripe
      >
        <template #columns>
          <a-table-column title="封面" :width="80">
            <template #cell="{ record }">
              <a-image v-if="record.imgUrl" width="50" height="50" fit="contain" :src="record.imgUrl" />
              <a-avatar v-else shape="square" :size="50">
                <icon-book />
              </a-avatar>
            </template>
          </a-table-column>
          <a-table-column title="书名" data-index="title" :width="220" ellipsis tooltip />
          <a-table-column title="ISBN" data-index="isbn" :width="150" ellipsis tooltip />
          <a-table-column title="课程" :width="180" ellipsis tooltip>
            <template #cell="{ record }">
              {{ record.crouseName || record.courseName || '-' }}
              <span v-if="record.courseType">({{ record.courseType }})</span>
            </template>
          </a-table-column>
          <a-table-column title="价格" :width="120">
            <template #cell="{ record }">
              ￥{{ record.textbookDiscountedPrice ?? record.totalDiscountedPrice ?? record.textbookPrice ?? '-' }}
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { adminQxsAccountList, adminQxsAccountDetail } from '@/api/qxs'
import { useResponsiveTable } from '@/hooks/useResponsiveTable'

const { tableFixed } = useResponsiveTable()
const loading = ref(false)
const data = ref([])
const query = reactive({
  username: '',
  realname: '',
  email: '',
  mobile: '',
  className: '',
  termName: '',
  queryTime: []
})
const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})

const detailVisible = ref(false)
const detailLoading = ref(false)
const detail = ref(null)

const detailTitle = computed(() => {
  if (!detail.value) return '书单详情'
  return `书单详情 · ${detail.value.realname || detail.value.username || ''}`
})

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(Number(time)).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getList = async () => {
  try {
    loading.value = true
    const res = await adminQxsAccountList({
      ...query,
      current: pagination.current,
      pagesize: pagination.pagesize
    })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取查询记录失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data || []
    pagination.total = res.pagination?.total || 0
  } catch (error) {
    Notification.error({
      title: '获取查询记录失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const openDetail = async (record) => {
  try {
    detailLoading.value = true
    detailVisible.value = true
    detail.value = null
    const res = await adminQxsAccountDetail({ id: record.id })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取书单详情失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    detail.value = res.data
  } catch (error) {
    Notification.error({
      title: '获取书单详情失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    detailLoading.value = false
  }
}

const search = () => {
  pagination.current = 1
  getList()
}

const reset = () => {
  query.username = ''
  query.realname = ''
  query.email = ''
  query.mobile = ''
  query.className = ''
  query.termName = ''
  query.queryTime = []
  pagination.current = 1
  getList()
}

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

const onPageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  getList()
}

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

<style scoped>
.query-row {
  margin-bottom: 10px;
}

.query-main {
  min-width: 0;
}

.query-actions-space {
  width: 100%;
}

.table {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .query-row {
    display: block;
  }

  .query-divider {
    display: none;
  }

  .query-actions-space {
    margin-top: 4px;
    flex-direction: row !important;
    gap: 10px !important;
  }

  .query-actions-space :deep(.arco-btn) {
    flex: 1;
  }
}
</style>
