<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { VideoItem, VideoCreateItem } from '../types'
import { ElMessageBox, ElMessage } from 'element-plus'

import UploadVideo from '@/components/UploadVideo.vue'
import { createVideo, updateVideo } from '../api'
import { useGetCourseList } from '../composables/useGetCourseList'
import { useGetExperimentList } from '../composables/useGetExperimentList'
import { useMapStore } from '@/stores/map'

interface Props {
  data?: VideoItem | null
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

// 课程列表
const { courses } = useGetCourseList()
// 数据状态
const status = useMapStore().getMapValuesByKey('system_status')
// 实验列表
const { experiments, updateExperiments } = useGetExperimentList()

const formRef = $ref<FormInstance>()
const form = reactive<VideoCreateItem>({
  name: '',
  course_id: '',
  experiment_id: '',
  status: '1',
  source_id: '',
  protocol: false
})
watchEffect(() => {
  if (!props.data) return
  Object.assign(form, { protocol: true }, props.data)
})
watchEffect(() => {
  updateExperiments(form.course_id)
})
const checkProtocol = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请阅读并同意'))
  } else {
    callback()
  }
}
const rules = ref<FormRules>({
  source_id: [{ required: true, message: '请上传实验操作视频' }],
  name: [{ required: true, message: '请输入实验操作视频名称', trigger: 'blur' }],
  course_id: [{ required: true, message: '请选择关联实验课程', trigger: 'change' }],
  experiment_id: [{ required: true, message: '请选择关联实验', trigger: 'change' }],
  protocol: [{ validator: checkProtocol, message: '请阅读并同意', trigger: 'change' }]
})
const isUpdate = $computed(() => {
  return !!props.data?.id
})
const title = $computed(() => {
  return isUpdate ? '编辑实验操作视频' : '新增实验操作视频'
})

function handleBeforeUpload() {
  if (form.source_id) {
    return ElMessageBox.confirm(
      '系统仅支持1个实验操作视频，此操作将覆盖原有实验操作视频文件，确认上传新文件吗？',
      '提示'
    )
  }
  return true
}

function handleUploadSuccess(uploadInfo: any) {
  form.name = uploadInfo.file.name.split('.').shift()
  form.source_id = uploadInfo.videoId
}
// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    isUpdate ? handleUpdate(form) : handleCreate(form)
  })
}
// 新增
function handleCreate(params: VideoCreateItem) {
  createVideo(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate(params: VideoCreateItem) {
  updateVideo(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="600px" @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
      <el-form-item label="实验操作视频文件" prop="source_id">
        <UploadVideo :beforeUpload="handleBeforeUpload" @success="handleUploadSuccess">
          <template #tip>实验操作视频文件支持格式包含：doc docx xls xlsx pdf ppt pptx，大小不超过50M</template>
        </UploadVideo>
      </el-form-item>
      <el-form-item label="实验操作视频名称" prop="name">
        <el-input v-model="form.name"></el-input>
        <p class="form-tips">操作视频名称自动取值于文件名称，可以进行二次修改。</p>
      </el-form-item>
      <el-form-item label="关联实验课程" prop="course_id">
        <el-select v-model="form.course_id" filterable style="width: 100%" @change="form.experiment_id = ''">
          <el-option v-for="item in courses" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联实验" prop="experiment_id">
        <el-select v-model="form.experiment_id" filterable style="width: 100%">
          <el-option v-for="item in experiments" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有效状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="item in status" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="protocol">
        <el-checkbox label="我已阅读并同意" v-model="form.protocol" />
        <a
          href="https://view.officeapps.live.com/op/view.aspx?src=https://webapp-pub.ezijing.com/center_resource/%E7%B4%AB%E8%8D%86%E6%95%99%E8%82%B2%E7%94%A8%E6%88%B7%E5%85%A5%E9%A9%BB%E5%8F%8A%E7%BD%91%E7%BB%9C%E6%95%99%E5%AD%A6%E8%B5%84%E6%BA%90%E5%8D%8F%E8%AE%AE(1).docx"
          target="_blank"
          >《紫荆教育用户入驻及网络教学资源协议》</a
        >
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.form-tips {
  font-size: 12px;
  color: #999;
}
</style>
