<template>
  <layout-card>
    <el-form
      ref="formRef"
      :rules="rules"
      :model="data.form"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="课件名称" prop="COURSEWARENAME">
            <el-input v-model="data.form.COURSEWARENAME" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训板块" prop="trainingSection">
            <layout-training-section-cascader
              v-model="data.form.trainingSection"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训行业类型" prop="TRAINTYPE">
            <layout-learning-train-type
              v-model="data.form.TRAINTYPE"
              type="industry"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位培训类型" prop="POSTTYPE">
            <layout-learning-train-type
              v-model="data.form.POSTTYPE"
              type="post"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="讲师名称" prop="SPEAKER">
            <el-input v-model="data.form.SPEAKER" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="课件文件" prop="file">
            <layout-upload
              v-model:file-list="data.form.file"
              accept=".mp4"
              :size="500"
              @preview="fnPreviewVideo"
            >
              <template #tip>
                只能上传mp4文件，最大上传500M
                <el-progress
                  :percentage="progressBar"
                  v-if="progressBarVisible"
                />
              </template>
            </layout-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="课件截图"
            prop="screenshotFile"
            v-if="data.form.screenshotFile.length > 0"
          >
            <layout-upload
              v-model:file-list="data.form.screenshotFile"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="课件描述" prop="COURSEWAREINTRODUCE">
            <el-input
              v-model="data.form.COURSEWAREINTRODUCE"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="大纲类型" prop="ONTLINETYPE">
            <el-select v-model="data.form.ONTLINETYPE">
              <el-option
                v-for="item in outlineTypeList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="tc mt-10">
      <el-button type="primary" @click="fnSubmit">提交</el-button>
    </div>
    <layout-video
      :src="data.videoDialog.src"
      :vid="data.videoDialog.vid"
      :play-auth="data.videoDialog.playAuth"
      v-model:visible="data.videoDialog.visible"
    />
  </layout-card>
</template>

<script setup>
import { reactive, ref } from "vue";
import { debounce } from "throttle-debounce";
import { ElMessage } from "element-plus";
import useFormValidate from "@/assets/js/useFormValidate.js";
import LayoutTrainingSectionCascader from "@/components/training_section_cascader/index.vue";
import LayoutLearningTrainType from "@/components/learning_train_type/index.vue";
import LayoutUpload from "@/components/upload/index.vue";
import { layoutFnGetOutlineType } from "@/assets/js/data_dictionary.js";
import useAliYunUpload from "@/assets/js/useAliYunUpload.js";
import {
  getVideoCoursewareView,
  setVideoCoursewareAdd,
  setVideoCoursewareEdit,
} from "@/request/online_learn_exam.js";
import LayoutVideo from "@/components/video/index.vue";
import useAliYunVideoPreview from "@/assets/js/useAliYunVideoPreview.js";
import { getFileName } from "@/assets/js/utils.js";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/pinia/user.js";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const { VIDEOCOURSEWARE_ID } = route.query;
let uploader;
const rules = {
  COURSEWARENAME: [
    { required: true, message: "请输入课件名称", trigger: "blur" },
  ],
  SPEAKER: [{ required: true, message: "请输入讲师名称", trigger: "blur" }],
  file: [{ required: true, message: "请上传课件文件", trigger: "change" }],
  COURSEWAREINTRODUCE: [
    { required: true, message: "请输入课件描述", trigger: "blur" },
  ],
  ONTLINETYPE: [
    { required: true, message: "请选择大纲类型", trigger: "change" },
  ],
};
const formRef = ref(null);
const progressBarVisible = ref(false);
const progressBar = ref(0);
const data = reactive({
  form: {
    COURSEWARENAME: "",
    trainingSection: [],
    TRAINTYPE: "",
    POSTTYPE: "",
    SPEAKER: "",
    file: [],
    screenshotFile: [],
    COURSEWAREINTRODUCE: "",
    ONTLINETYPE: "",
  },
  videoDialog: {
    src: "",
    vid: "",
    playAuth: "",
    visible: false,
  },
});
const fnGetData = async () => {
  if (!VIDEOCOURSEWARE_ID)
    data.form.TRAINTYPE = userStore.getUserInfo.CORP_TRAINTYPE;
  else {
    const resData = await getVideoCoursewareView({ VIDEOCOURSEWARE_ID });
    data.form = resData.pd;
    data.form.screenshotFile = [
      {
        url: resData.pd.VIDEOCAPTURE,
        name: getFileName(resData.pd.VIDEOCAPTURE),
      },
    ];
    data.form.file = [
      {
        url: resData.pd.VIDEOFILES,
        name: getFileName(resData.pd.VIDEOFILES),
      },
    ];
    data.form.trainingSection = resData.coursewareAllList.map((item) =>
      item.DICTIONARIES_IDS.split(",")
    );
  }
};
fnGetData();
const outlineTypeList = await layoutFnGetOutlineType();
const fnPreviewVideo = async () => {
  const { src, vid, playAuth, visible } = await useAliYunVideoPreview(
    data.form
  );
  data.videoDialog.src = src;
  data.videoDialog.vid = vid;
  data.videoDialog.playAuth = playAuth;
  data.videoDialog.visible = visible;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    if (data.form.file[0].raw) {
      uploader = useAliYunUpload({
        onUploadSucceed: (uploadInfo) => {
          fnSubmitForm(uploadInfo.videoId);
        },
        onUploadstarted: () => {
          progressBarVisible.value = true;
        },
        onUploadFailed: () => {
          progressBarVisible.value = false;
        },
        onUploadProgress: (uploadInfo, totalSize, progress) => {
          progressBar.value = Math.ceil(progress * 100);
        },
      });
      fnSubmitVideo();
    } else {
      await fnSubmitForm();
    }
  },
  { atBegin: true }
);
const fnSubmitVideo = () => {
  uploader.addFile(data.form.file[0].raw, null, null, null, '{"Vod":{}}');
  uploader.startUpload();
};
const fnSubmitForm = async (videoId = "") => {
  const params = {
    ...data.form,
    videoId,
    isEditVideo: !!data.form.file[0].raw,
    trainingSection: data.form.trainingSection.join(";"),
  };
  !VIDEOCOURSEWARE_ID
    ? await setVideoCoursewareAdd(params)
    : await setVideoCoursewareEdit(params);
  ElMessage.success("提交成功");
  router.back();
};
</script>

<style scoped lang="scss"></style>
