<script setup lang="ts">
import type { BookItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import ListItem from '../components/ListItem.vue'
import { getBookList } from '../api'
import { useGetExperimentList } from '../composables/useGetExperimentList'

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))
// 实验列表
const { experiments, updateExperiments } = useGetExperimentList()
updateExperiments()

const route = useRoute()

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = $computed(() => {
  return {
    remote: {
      httpRequest: getBookList,
      params: { name: '', experiment_id: route.query.experiment_id || '' }
    },
    filters: [
      { type: 'input', prop: 'name', label: '实验指导书名称', placeholder: '请输入实验指导书名称' },
      {
        type: 'select',
        prop: 'experiment_id',
        label: '关联实验',
        options: experiments.value,
        labelKey: 'name',
        valueKey: 'id',
        placeholder: '请选择关联实验'
      }
    ],
    columns: [{ label: '名称', prop: 'name' }]
  }
})

let dialogVisible = $ref(false)
const rowData = ref<BookItem | undefined | null>(null)
// 新增
function handleAdd() {
  rowData.value = null
  dialogVisible = true
}
// 编辑
function handleUpdate(row: BookItem) {
  rowData.value = row
  dialogVisible = true
}

function onUpdateSuccess() {
  appList?.refetch()
}
</script>

<template>
  <AppCard title="实验指导书管理" :hasBodyBackground="false">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd" v-permission="'v1-teacher-book-create'"
          >新增实验指导书</el-button
        >
      </template>
      <template #body="{ data }">
        <div class="list-card" v-if="data.length">
          <ListItem v-for="item in data" :data="item" :key="item.id" @clickEdit="handleUpdate(item)"></ListItem>
        </div>
        <el-empty description="暂无数据" v-else />
      </template>
    </AppList>
  </AppCard>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
</template>

<style lang="scss" scoped>
:deep(.table-list-filter) {
  padding: 30px 30px 10px;
  background: #fff;
  border-radius: 12px;
}
.list-card {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}
</style>
