<script setup lang="ts">
import type { ExperimentItem } from '../types'
import { CirclePlus, MoreFilled, CopyDocument, Delete, Setting, Edit, EditPen } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { getExperimentList, deleteExperiment } from '../api'
import { useGetCourseList } from '../composables/useGetCourseList'
import { useGetCourseExperimentList } from '../composables/useGetCourseExperimentList'
import { useMapStore } from '@/stores/map'
import { ElMessage, ElMessageBox } from 'element-plus'

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))
const GradeRulesDialog = defineAsyncComponent(() => import('../components/GradeRulesDialog.vue'))
const DMLFormDialog = defineAsyncComponent(() => import('../components/DMLFormDialog.vue'))
const CopyDialog = defineAsyncComponent(() => import('../components/CopyDialog.vue'))

// 数据状态
const status = useMapStore().getMapValuesByKey('system_status')
// 课程列表
const { courses, updateCourses } = useGetCourseList()
updateCourses('')
// 课程实验
const { courseExperiments, updateCourseExperiments } = useGetCourseExperimentList()

const appList = $ref<InstanceType<typeof AppList> | null>(null)

const params = reactive({
  id: '',
  course_id: '',
  name: '',
  status: '',
})
watch(
  () => params.course_id,
  () => {
    updateCourseExperiments(params.course_id)
  }
)
// 列表配置
const listOptions = $computed(() => {
  return {
    remote: {
      httpRequest: getExperimentList,
      params,
      beforeRequest(requestParams: any) {
        if (params.course_id !== requestParams.course_id) {
          requestParams.id = ''
        }
        params.course_id = requestParams.course_id || ''
        return requestParams
      },
      callback(data: { total: number; list: ExperimentItem[] }) {
        const { list, total } = data
        const dataList = list.map((item) => {
          const teacher_names = item.teacher.map((teacher) => teacher.name).join('、')
          return { ...item, teacher_names }
        })
        return { list: dataList, total }
      },
    },
    filters: [
      {
        type: 'select',
        prop: 'course_id',
        label: '实验课程',
        placeholder: '请选择实验课程',
        options: courses.value,
        labelKey: 'name',
        valueKey: 'id',
      },
      {
        type: 'select',
        prop: 'id',
        label: '实验名称',
        placeholder: '请选择实验',
        options: courseExperiments.value,
        labelKey: 'name',
        valueKey: 'id',
      },
      {
        type: 'select',
        prop: 'status',
        label: '生效状态',
        placeholder: '请选择生效状态',
        options: status,
      },
    ],
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '实验课程名称', prop: 'course_name' },
      { label: '实验名称', prop: 'name' },
      { label: '实验学时', prop: 'length' },
      { label: '指导教师', prop: 'teacher_names' },
      { label: '实验类型', prop: 'type_name' },
      { label: '实验总成绩', prop: 'score' },
      { label: '生效状态', prop: 'status_name' },
      { label: '更新人', prop: 'updated_operator_name' },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 250 },
    ],
  }
})

let dialogVisible = $ref(false)
const rowData = ref<ExperimentItem | undefined | null>(null)

// 新增
function handleAdd() {
  rowData.value = null
  dialogVisible = true
}
// 编辑
function handleUpdate(row: ExperimentItem) {
  rowData.value = row
  dialogVisible = true
}

function onUpdateSuccess() {
  appList?.refetch()
}

let gradeRulesDialogVisible = $ref(false)
function handleUpdateGradeRules(row: ExperimentItem) {
  rowData.value = row
  gradeRulesDialogVisible = true
}

// 配置数字营销实验
let dmlDialogVisible = $ref(false)
function handleUpdateDML(row: ExperimentItem) {
  rowData.value = row
  dmlDialogVisible = true
}
// 复制
let copyDialogVisible = $ref(false)
async function handleCopy(row: ExperimentItem) {
  rowData.value = row
  copyDialogVisible = true
}
// 删除
async function handleDelete(row: ExperimentItem) {
  ElMessageBox.confirm('确定要删除该实验吗？', '提示').then(async () => {
    await deleteExperiment({ experiment_id: row.id })
    ElMessage.success('删除成功')
    appList?.refetch()
  })
}
</script>

<template>
  <AppCard title="实验管理">
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary" :icon="CirclePlus" v-permission="'v1-backend-experiment-create'" @click="handleAdd"
          >新增实验</el-button
        >
      </template>

      <template #table-x="{ row }: { row: ExperimentItem }">
        <el-button type="primary" round v-permission="'v1-backend-experiment-view'">
          <router-link :to="`/admin/lab/experiment/${row.id}`" target="_blank">查看</router-link>
        </el-button>
        <el-button type="primary" round @click="handleUpdate(row)" v-permission="'v1-backend-experiment-update'"
          >编辑</el-button
        >
        <el-button type="primary" round @click="handleDelete(row)">删除</el-button>

        <!-- 功能按钮移入详情里 s  v-if="false" -->
        <el-dropdown style="margin-left: 12px" v-if="false">
          <el-button type="primary" round :icon="MoreFilled"></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Setting" @click="handleUpdateDML(row)" v-if="row.type === '4'"
                >配置数字营销</el-dropdown-item
              >
              <template v-if="!row.stu_commit_count">
                <el-dropdown-item :icon="Edit" @click="handleUpdateGradeRules(row)">编辑成绩规则</el-dropdown-item>
                <el-dropdown-item :icon="EditPen">
                  <router-link :to="`/admin/lab/experiment/report/${row.id}`" target="_blank">编辑报告规则</router-link>
                </el-dropdown-item>
              </template>
              <el-dropdown-item :icon="CopyDocument" @click="handleCopy(row)">复制</el-dropdown-item>
              <el-dropdown-item :icon="Delete" @click="handleDelete(row)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- 功能按钮移入详情里 end -->

        <!-- <template v-if="row.type === '4'">
          <el-button
            type="primary"
            round
            style="width: 132px; margin-bottom: 12px"
            @click="handleUpdateDML(row)"
            v-permission="'experiment_itinerary_config_detail'"
            >配置数字营销实验</el-button
          ><br />
        </template>
        <template v-if="!row.stu_commit_count">
          <el-button
            type="info"
            round
            style="width: 132px; margin-bottom: 12px"
            @click="handleUpdateGradeRules(row)"
            v-permission="'v1-backend-experiment-scorerule-detail'"
            >编辑成绩规则</el-button
          ><br />
          <el-button type="info" round style="width: 132px; margin-bottom: 12px" v-permission="'v1-backend-experiment-report-detail'">
            <router-link :to="`/admin/lab/experiment/report/${row.id}`" target="_blank">编辑报告规则</router-link>
          </el-button>
          <br />
        </template>
        <el-button type="primary" round v-permission="'v1-backend-experiment-view'">
          <router-link :to="`/admin/lab/experiment/${row.id}`" target="_blank">查看</router-link>
        </el-button>
        <el-button type="primary" round @click="handleUpdate(row)" v-permission="'v1-backend-experiment-update'">编辑</el-button>
        <div style="margin-top: 12px">
          <el-button type="primary" round @click="handleCopy(row)">复制</el-button>
          <el-button type="primary" round @click="handleDelete(row)">删除</el-button>
        </div> -->
      </template>
    </AppList>
  </AppCard>
  <FormDialog v-model="dialogVisible" :data="rowData" @update="onUpdateSuccess" v-if="dialogVisible"></FormDialog>
  <!-- 编辑实验成绩规则 -->
  <GradeRulesDialog
    v-model="gradeRulesDialogVisible"
    :data="rowData"
    @update="onUpdateSuccess"
    v-if="gradeRulesDialogVisible && rowData"></GradeRulesDialog>
  <!-- 配置数字营销实验 -->
  <DMLFormDialog v-model="dmlDialogVisible" :data="rowData" v-if="dmlDialogVisible && rowData"></DMLFormDialog>
  <CopyDialog
    v-model="copyDialogVisible"
    :data="rowData"
    @update="onUpdateSuccess"
    v-if="copyDialogVisible && rowData"></CopyDialog>
</template>
