<template>
  <div>
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> 课程详情 </span>
        </template>
      </el-page-header>
    </div>

    <div class="content">
      <el-form ref="lessonFormRef" :model="form" :rules="formRules" label-width="11vw">

        <el-form-item label="课程名称：" prop="courseName">
          <el-input :disabled="false" v-model="form.courseName" placeholder="此处输入课程名称" />
        </el-form-item>

        <el-form-item label="课程分类：" prop="courseClassify">
          <el-select v-model="form.courseClassify" placeholder="此处选择课程分类" clearable>
            <el-option v-for="dict in course_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属领域：" prop="courseClassify">
          <el-select v-model="form.performWorkId" placeholder="此处选择所属领域" clearable>
            <el-option v-for="dict in perform_work_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="授课方式：" prop="teachingType">
          <el-select v-model="form.teachingType" placeholder="此处选择课程分类" clearable>
            <el-option v-for="dict in give_course_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程简介：" prop="courseBrief">
          <el-input type="textarea" :rows="5" :disabled="false" v-model="form.courseBrief" placeholder="此处输入课程简介" />
        </el-form-item>

        <el-form-item label="封面图片：" prop="coursePic">
          <el-upload :limit="1"
                     ref="coursePicRef"
                     accept=".png, .jpg"
                     class="avatar-uploader"
                     :action="upload.url"
                     :headers="upload.headers"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :on-exceed="handleExceedPicSuccess"
                     :on-error="handleUploadError"
                     :before-upload="beforeAvatarUpload">
            <img v-if="form.coursePic" :src="form.coursePic" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>

            <template #tip>
              <div class="text-left el-upload__tip">
                <span>请选择图片上传：大小128 * 180像素，支持jpg、png等格式，图片需小于10M，仅一张。</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="课程视频:" prop="courseAttachment">

          <el-upload v-if="type == 'add' || type == 'edit'"
                     ref="uploadLWRef"
                     v-model:file-list="courseAttachmentList"
                     :limit="1"
                     accept=".mp4, .avi, .wmv"
                     :headers="upload.headers"
                     :action="upload.url"
                     :on-success="handleUpload"
                     :on-exceed="handleExceedUpload"
                     :auto-upload="true"
                     drag>
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">将视频文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <span>允许导入mp4、avi、wmv格式视频文件。</span>
              </div>
            </template>
          </el-upload>

          <el-empty v-else-if="form.courseAttachment == '' || form.courseAttachment == null"></el-empty>

          <FileOrImage v-else :data="form.courseAttachment" :isEdit="false" width="120px"
            :dataList=[form.courseAttachment] height="100px" objectFit="cover">
          </FileOrImage>


        </el-form-item>

        <div v-if="type != 'add' && type != 'edit'">

          <el-form-item label="操作人：">
            <span>{{ form.userName }}</span>
          </el-form-item>

          <el-form-item label="创建时间：">
            <span>{{ form.createTime }}</span>
          </el-form-item>

          <el-form-item v-if="form.status != '1'"
            :label="form.status == '2' ? '上架时间：' : form.status == '3' ? '下架时间：' : ''">
            <span v-if="form.takedownTime">{{ form.takedownTime }}</span>
            <span v-else>{{ form.createTime }}</span>
          </el-form-item>

        </div>

        <div class="btn">
          <el-button v-if="type == 'edit' || type == 'add'" :loading="buttonLoading" type="primary"
            @click="submitForm">提交</el-button>
          <el-button type="danger" @click="cancel">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FileOrImage from '@/components/FileOrImage/index.vue';
import { getLearningCourse, updateLearningCourse, addLearningCourse } from '@/api/study/lesson';
import { globalHeaders } from '@/utils/request';
import {genFileId, UploadProps, UploadRawFile} from "element-plus";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { give_course_type, resource_status, course_type,perform_work_type } = toRefs<any>(proxy?.useDict('give_course_type', 'resource_status', 'course_type','perform_work_type'));
const type = computed(() => proxy.$route.query.type);
const _id = computed(() => proxy.$route.query.id);
const buttonLoading = ref(false)
const router = useRouter();
const route = useRoute();
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const goBack = () => {
  router.back();
}
const lessonFormRef = ref<ElFormInstance>();
const uploadLWRef = ref<ElUploadInstance>()
const coursePicRef = ref<ElUploadInstance>()
const courseAttachmentList = ref([])
const initForm = {
  courseName: '',
  courseClassify: '',
  performWorkId: '',
  teachingType: '',
  courseBrief: "",
  coursePic: "",
  courseAttachment: "",
  status: "",
  remark: null,
  userName: null,
  takedownTime: null,
  createTime: null
}
const form = ref({ ...initForm });
//提交
const submitForm = async () => {

  ElMessageBox.confirm('确认提交以上信息吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    lessonFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (type.value == 'add') {

          form.value.status = '1';

          const res = await addLearningCourse(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("提交成功");
            router.back();
          }

        } else if (type.value == 'edit') {
          const res = await updateLearningCourse(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("修改成功");
            router.back();
          }
        }
        // const res = await addExpertRecommend(form.value).finally(() => { buttonLoading.value = false });
        // if (res.code == 200) {
        //   proxy?.$modal.msgSuccess("提交成功");
        //   router.back();
        // }
        reset();

      }

    });
  }).catch(() => {

  })
}
const handleExceedPicSuccess: UploadProps['onExceed'] = (files) => {
  coursePicRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  coursePicRef.value!.handleStart(file)
  coursePicRef.value!.submit()
}
//上传成功
const handleAvatarSuccess = (res: any) => {
  // 如果上传成功
  if (res.code === 200) {
    form.value.coursePic = res.data.url;
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.msgError('图片插入失败');
    proxy?.$modal.closeLoading();
  }
}

//上传失败
const handleUploadError = (err: any) => {
  proxy?.$modal.msgError('上传文件失败');
};
//上传之前
const beforeAvatarUpload = (file: any) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
  const isJPG = type.includes(file.type);
  //检验文件格式
  if (!isJPG) {
    proxy?.$modal.msgError(`图片格式错误!`);
    return false;
  }
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 10;
  if (!isLt) {
    proxy?.$modal.msgError(`上传图片大小不能超过 10 MB!`);
    return false;
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  return true;
}
//重置表单
const reset = () => {
  form.value = { ...initForm };
  lessonFormRef.value?.resetFields();
}
//取消
const cancel = () => {
  router.back();
  reset();
}
//获取数据详情
const getData = async () => {
  courseAttachmentList.value = []
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await getLearningCourse(_id.value.toString());
  if (res.data.originalName) {
    courseAttachmentList.value = [{
      url: res.data.url,
      name: res.data.originalName
    }]
  }

  if (res.data.coursePic) {
    form.value.coursePic = res.data.coursePic;
  }
  Object.assign(form.value, res.data);

}

const handleExceedUpload: UploadProps['onExceed'] = (files) => {
  uploadLWRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadLWRef.value!.handleStart(file)
  uploadLWRef.value!.submit()
}
/** 附件上传成功处理 */
const handleUpload = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {
  const findMp4TypeFile = file.raw.type.includes('mp4')
  const findAviTypeFile = file.raw.type.includes('avi')
  const findWmvTypeFile = file.raw.type.includes('wmv')
  if (findMp4TypeFile || findAviTypeFile || findWmvTypeFile) {
    if (response.code === 200) {
      form.value.courseAttachment = response.data.ossId;
      ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '上传论文结果', {
        dangerouslyUseHTMLString: true
      });
    } else {
      uploadLWRef.value.clearFiles()
    }
  } else {
    uploadLWRef.value.clearFiles()
  }
};
onActivated(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();

})
onMounted(() => {

  if (type.value == 'add') {
    reset();
    return
  }
  getData();
})

const formRules = ref({
  courseName: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
  courseClassify: [{ required: true, message: '课程分类不能为空', trigger: 'blur' }],
  teachingType: [{ required: true, message: '授课方式不能为空', trigger: 'blur' }],
  courseBrief: [{ required: true, message: '课程简介不能为空', trigger: 'blur' }],
  coursePic: [{ required: true, message: '封面图片不能为空', trigger: 'blur' }],
  // courseAttachment: [{ required: true, message: '课程附件不能为空', trigger: 'blur' }],
})
</script>

<style lang="scss" scoped>
.header {
  margin: 1vh 0 0 2vw;
}

.el-form {
  margin-top: 2vh;
  margin-left: 2vw;
  width: 40%;
}

.btn {
  width: 60%;
  margin: 20px auto;
  display: flex;
  justify-content: space-evenly;

  .el-button {
    width: 30%;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-upload) {
  border: 1px dashed #3d3d3d;
  //border-radius: 1vw;
}
</style>
