<script setup lang="ts">
import type { CaseItem } from '../types'
import { CirclePlus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import ListItem from '../components/ListItem.vue'
import { getCaseList } 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: getCaseList,
      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<CaseItem | undefined | null>(null)
// 新增
function handleAdd() {
  rowData.value = null
  dialogVisible = true
}
// 编辑
function handleUpdate(row: CaseItem) {
  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="'teacher-experiment-cases-create'"
          >新增案例原文</el-button
        >
      </template>
      <template #body="{ data }: { data: CaseItem[] }">
        <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>
