<template>
  <layout-card>
    <el-divider content-position="left">课程基本信息</el-divider>
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="课程名称" prop="CURRICULUMNAME">
            <el-input v-model="data.form.CURRICULUMNAME" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训类型" prop="TRAINTYPE">
            <layout-learning-train-type
              ref="trainingTypeRef"
              v-model="data.form.TRAINTYPE"
              type="trainingType"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行业类型" prop="INDUSTRY_LAST">
            <layout-learning-train-type
              ref="industryTypeRef"
              v-model="data.form.INDUSTRY_LAST"
              type="industryType"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位类型" prop="POSTTYPE">
            <layout-learning-train-type
              ref="postTypeRef"
              v-model="data.form.POSTTYPE"
              type="postType"
              :search-value="data.form.TRAINTYPE"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训级别" prop="TRAINLEVEL">
            <layout-learning-train-type
              ref="trainingLevelRef"
              v-model="data.form.TRAINLEVEL"
              type="trainingLevel"
              :search-value="data.form.POSTTYPE"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="课程描述" prop="CURRICULUMINTRODUCE">
            <el-input
              v-model="data.form.CURRICULUMINTRODUCE"
              type="textarea"
              :autosize="{ minRows: 3 }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="课程封面" prop="files">
            <layout-upload
              v-model:file-list="data.form.files"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider content-position="left">课程目录</el-divider>
    <div v-if="!CURRICULUM_ID">
      <div class="mb-10">
        <el-button
          :type="data.form.CATALOGUELEVEL === '1' ? 'success' : 'primary'"
          @click="fnChangeCatLevel('1')"
        >
          一级目录样式
        </el-button>
        <el-button
          :type="data.form.CATALOGUELEVEL === '2' ? 'success' : 'primary'"
          @click="fnChangeCatLevel('2')"
        >
          二级目录样式
        </el-button>
      </div>
      <div class="course_directory">
        <div
          v-for="(item, index) in data.chapterList"
          :key="item.no"
          class="course_item"
        >
          <div class="course_row">
            <div class="course_icon">
              <el-icon
                v-if="
                  item.nodes &&
                  item.nodes.length !== 0 &&
                  item.iconDirection === '1'
                "
              >
                <caret-bottom />
              </el-icon>
            </div>
            <div class="course_number">{{ index + 1 }}</div>
            <div class="course_play">
              <el-icon v-if="item.VIDEOCOURSEWARE_ID" size="18">
                <video-camera />
              </el-icon>
            </div>
            <div class="course_input">
              <el-input
                v-if="item.showNameInput"
                id="firstInput"
                v-model="item.NAME"
                @blur="fnInputBlur(item, $event)"
              />
              <template v-else>{{ item.NAME }}</template>
            </div>
            <div>
              <el-button
                type="primary"
                @click="fnDeleteChapter(index, item, 'first')"
              >
                删除
              </el-button>
            </div>
            <div>
              <el-button
                type="primary"
                :disabled="item.showNameInput"
                @click="fnRename(item, 'firstInput')"
              >
                重命名
              </el-button>
            </div>
            <div v-if="data.form.CATALOGUELEVEL === '2'">
              <el-button
                type="primary"
                :disabled="item.showNameInput"
                @click="fnAddSecondChapter(item)"
              >
                新增二级项
              </el-button>
            </div>
            <div v-if="data.form.CATALOGUELEVEL === '1'">
              <el-button
                type="primary"
                :disabled="item.showNameInput"
                @click="fnAddCourseware(index, '', 'radio')"
              >
                {{ item.VIDEOCOURSEWARE_ID ? "更改课件" : "添加课件" }}
              </el-button>
            </div>
            <div v-if="item.VIDEOCOURSEWARE_ID">
              <el-button
                type="primary"
                @click="fnPreview(item.VIDEOCOURSEWARE_ID, '')"
              >
                预览
              </el-button>
            </div>
          </div>
          <div
            v-for="(item1, index1) in item.nodes"
            :key="item1.no"
            class="course_row ml-30"
          >
            <div class="course_icon" />
            <div class="course_number">{{ index + 1 }}-{{ index1 + 1 }}</div>
            <div class="course_play">
              <el-icon v-if="item1.VIDEOCOURSEWARE_ID" size="18">
                <video-camera />
              </el-icon>
            </div>
            <div class="course_input">
              <el-input
                v-if="item1.showNameInput"
                id="secondInput"
                v-model="item1.NAME"
                @blur="fnInputBlur(item1, $event)"
              />
              <template v-else>{{ item1.NAME }}</template>
            </div>
            <div>
              <el-button
                type="primary"
                @click="fnDeleteChapter(index1, item, 'second')"
              >
                删除
              </el-button>
            </div>
            <div>
              <el-button
                type="primary"
                :disabled="item1.showNameInput"
                @click="fnRename(item, 'secondInput')"
              >
                重命名
              </el-button>
            </div>
            <div>
              <el-button
                type="primary"
                :disabled="item1.showNameInput"
                @click="fnAddCourseware(index, index1, 'radio')"
              >
                {{ item1.VIDEOCOURSEWARE_ID ? "更改课件" : "添加课件" }}
              </el-button>
            </div>
            <div v-if="item1.VIDEOCOURSEWARE_ID">
              <el-button
                type="primary"
                @click="fnPreview(item1.VIDEOCOURSEWARE_ID, '')"
              >
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-10">
        <el-button
          :disabled="data.addFirstChapterFlag"
          type="primary"
          @click="fnAddFirstChapter"
        >
          新增一级项
        </el-button>
        <el-button
          :disabled="data.addFirstChapterFlag"
          type="primary"
          @click="fnAddCourseware('', '', 'multiple')"
        >
          批量添加课件
        </el-button>
      </div>
    </div>
    <el-tree
      v-if="!!CURRICULUM_ID"
      :data="data.chapterList"
      :props="{ children: 'nodes', label: 'COURSEWARENAME' }"
      class="directory_style"
      default-expand-all
    >
      <template #default="{ data: item }">
        <div class="directory_row">
          <el-icon
            v-if="item.COURSEWARENAME"
            class="el-icon-video-camera"
            size="18"
          >
            <video-camera />
          </el-icon>
          <span class="directory_name">
            {{ item.NAME || item.COURSEWARENAME }}
          </span>
          <span v-if="item.COURSEWARENAME" class="directory_type">
            课件时长：{{ secondConversion(item.VIDEOTIME) }}
          </span>
          <el-button
            v-if="item.COURSEWARENAME"
            type="primary"
            size="small"
            @click="fnPreview(item.VIDEOCOURSEWARE_ID, item.VIDEOFILES)"
          >
            预览
          </el-button>
        </div>
      </template>
    </el-tree>
    <div class="mt-10 tc">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
    <layout-video
      v-model:visible="data.videoDialog.visible"
      :src="data.videoDialog.src"
    />
    <template v-if="!CURRICULUM_ID">
      <add-courseware
        v-model:visible="data.addCoursewareDialog.visible"
        :chapter-ids="data.addCoursewareDialog.chapterIds"
        :type="data.addCoursewareDialog.type"
        :chapter-list="data.chapterList"
        :catalogue-level="data.form.CATALOGUELEVEL"
        @confirm="fnAddCoursewareConfirm"
      />
    </template>
  </layout-card>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import {
  getCourseManagementView,
  getPreviewingVideo,
  setCourseManagementAdd,
  setCourseManagementEdit,
} from "@/request/training_resource_management.js";
import { nextTick, reactive, ref } from "vue";
import { secondConversion } from "@/assets/js/utils.js";
import { CaretBottom, VideoCamera } from "@element-plus/icons-vue";
import LayoutVideo from "@/components/video/index.vue";
import LayoutUpload from "@/components/upload/index.vue";
import LayoutLearningTrainType from "@/components/learning_train_type/index.vue";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage, ElMessageBox } from "element-plus";
import AddCourseware from "./components/add_courseware.vue";

const route = useRoute();
const router = useRouter();
const { CURRICULUM_ID } = route.query;
const rules = {
  CURRICULUMNAME: [
    { required: true, message: "请输入课程名称", trigger: "blur" },
  ],
  TRAINTYPE: [{ required: true, message: "请选择培训类型", trigger: "change" }],
  INDUSTRY_LAST: [
    { required: true, message: "请选择行业类型", trigger: "change" },
  ],
  POSTTYPE: [{ required: true, message: "请选择岗位类型", trigger: "change" }],
  files: [
    {
      required: true,
      message: "请上传封面",
      trigger: "change",
    },
  ],
  CURRICULUMINTRODUCE: [
    { required: true, message: "请输入课程描述", trigger: "blur" },
  ],
};
const formRef = ref(null);
const industryTypeRef = ref(null);
const trainingTypeRef = ref(null);
const postTypeRef = ref(null);
const trainingLevelRef = ref(null);
const data = reactive({
  form: {
    CURRICULUMNAME: "",
    TRAINTYPE: "",
    INDUSTRY_LAST: "",
    POSTTYPE: "",
    TRAINLEVEL: "",
    CURRICULUMINTRODUCE: "",
    files: [],
    CATALOGUELEVEL: "1",
    COLLECTIVE: 1,
    ISSELL: "1",
  },
  chapterList: [],
  addFirstChapterFlag: false,
  videoDialog: {
    visible: false,
    src: "",
  },
  addCoursewareDialog: {
    chapterIds: [],
    visible: false,
    index: "",
    index1: "",
    type: "",
  },
});
const fnGetData = async () => {
  if (!CURRICULUM_ID) return;
  const resData = await getCourseManagementView({ CURRICULUM_ID });
  data.form = resData.pd;
  data.chapterList = [...resData.chapterList];
};
fnGetData();
const fnPreview = async (VIDEOCOURSEWARE_ID, VIDEOFILES) => {
  const resData = await getPreviewingVideo({
    VIDEOCOURSEWARE_ID,
    VIDEOFILES,
    CURRICULUM_ID,
  });
  data.videoDialog.src = JSON.stringify(resData.urlList);
  data.videoDialog.visible = true;
};
const fnAddFirstChapter = () => {
  const firstChapter = {
    VIDEOCOURSEWARE_ID: "",
    NAME: "",
    showNameInput: true,
    SORT: data.chapterList.length + 1,
    iconDirection: "1",
    nodes: [],
    no: Math.random(),
  };
  data.addFirstChapterFlag = true;
  data.chapterList.push(firstChapter);
};
const fnChangeCatLevel = async (level) => {
  if (data.form.CATALOGUELEVEL === level) return;
  if (data.chapterList.length > 0) {
    await ElMessageBox.confirm("切换目录样式后，将清空目录内容，是否继续？", {
      type: "warning",
    });
  }
  data.addFirstChapterFlag = false;
  data.form.CATALOGUELEVEL = level;
  data.chapterList = [];
};
const fnInputBlur = (item, event) => {
  if (item.NAME) {
    data.addFirstChapterFlag = false;
    item.showNameInput = false;
  } else {
    ElMessage.warning("请输入名称");
    event.target.focus();
  }
};
const fnRename = async (item, element) => {
  item.showNameInput = true;
  await nextTick();
  document.getElementById(element).focus();
};
const fnDeleteChapter = async (index, item, whichNumber) => {
  await ElMessageBox.confirm(
    whichNumber === "first"
      ? "你确定删除该一级项及下面所有二级项内容？"
      : "你确定删除该二级项及关联的所有课件和试卷？",
    {
      type: "warning",
    }
  );
  if (whichNumber === "first") {
    data.chapterList.splice(index, 1);
  } else {
    item.nodes.splice(index, 1);
  }
  data.addFirstChapterFlag = false;
};
const fnAddSecondChapter = (item) => {
  const secondChapter = {
    VIDEOCOURSEWARE_ID: "",
    NAME: "",
    showNameInput: true,
    SORT: item.nodes.length + 1,
    nodes: [],
    no: Math.random(),
  };
  item.nodes.push(secondChapter);
};
const fnAddCourseware = (index, index1, type) => {
  data.addCoursewareDialog.visible = true;
  data.addCoursewareDialog.index = index;
  data.addCoursewareDialog.index1 = index1;
  data.addCoursewareDialog.type = type;
  data.addCoursewareDialog.chapterIds = [];
  for (let i = 0; i < data.chapterList.length; i++) {
    const chapterListItem = data.chapterList[i];
    if (data.form.CATALOGUELEVEL === "1") {
      if (chapterListItem.VIDEOCOURSEWARE_ID) {
        data.addCoursewareDialog.chapterIds.push(
          chapterListItem.VIDEOCOURSEWARE_ID
        );
      }
    } else {
      for (let j = 0; j < chapterListItem.nodes.length; j++) {
        if (chapterListItem.nodes[j].VIDEOCOURSEWARE_ID) {
          data.addCoursewareDialog.chapterIds.push(
            chapterListItem.nodes[j].VIDEOCOURSEWARE_ID
          );
        }
      }
    }
  }
};
const fnAddCoursewareConfirm = (value) => {
  const { index, index1, type } = data.addCoursewareDialog;
  if (type === "radio") {
    if (data.form.CATALOGUELEVEL === "1") {
      data.chapterList[index].VIDEOCOURSEWARE_ID = value.VIDEOCOURSEWARE_ID;
    } else {
      data.chapterList[index].nodes[index1].VIDEOCOURSEWARE_ID =
        value.VIDEOCOURSEWARE_ID;
    }
  } else {
    data.chapterList = [...value];
  }
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    for (let i = 0; i < data.chapterList.length; i++) {
      const chapterListItem = data.chapterList[i];
      if (data.form.CATALOGUELEVEL === "1") {
        if (!chapterListItem.VIDEOCOURSEWARE_ID) {
          ElMessage.warning(`序号${i + 1}课件没空`);
          return;
        }
      } else {
        if (chapterListItem.nodes.length > 0) {
          for (let j = 0; j < chapterListItem.nodes.length; j++) {
            if (!chapterListItem.nodes[j].VIDEOCOURSEWARE_ID) {
              ElMessage.warning(`序号${i + 1}-${j + 1}课件没空`);
              return;
            }
          }
        } else {
          ElMessage.warning(`序号${i + 1}没有下级目录`);
          return;
        }
      }
    }
    const { name, id } = industryTypeRef.value.getIndustryTypeCurrentCheckAll();
    const form = {
      ...data.form,
      TRAINTYPE_NAME: trainingTypeRef.value.getCurrentNode().NAME,
      INDUSTRY_LAST_NAME: name.at(-1),
      INDUSTRY_ALL_NAME: name.join("-"),
      INDUSTRY_ALL_TYPE: id.join("-"),
      POSTTYPE_NAME: postTypeRef.value.getCurrentNode().NAME,
      TRAINLEVEL_NAME: trainingLevelRef.value.getCurrentNode().NAME || "",
      chapterList: JSON.stringify(data.chapterList),
      INDUSTRY_END_ID: data.form.INDUSTRY_LAST,
    };
    const formData = new FormData();
    Object.keys(form).forEach((key) => {
      formData.append(key, form[key]);
    });
    formData.delete("files");
    for (let i = 0; i < data.form.files.length; i++) {
      if (data.form.files[i].raw)
        formData.append("FFILE", data.form.files[i].raw);
    }
    !CURRICULUM_ID
      ? await setCourseManagementAdd(formData)
      : await setCourseManagementEdit(formData);
    ElMessage.success("保存成功");
    router.back();
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss">
.directory_style {
  font-size: 14px;
  margin-bottom: 20px;

  .el-icon-video-camera {
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
  }

  .directory_row {
    .directory_name {
      width: 260px;
      display: inline-block;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      vertical-align: middle;
    }

    .directory_type {
      width: 200px;
      display: inline-block;
      vertical-align: middle;
    }
  }
}

:deep {
  .el-tree-node__content {
    margin-bottom: 10px;
    height: auto;
  }
}

.course_directory {
  .course_item {
    .course_row {
      display: flex;
      align-items: center;
      padding: 3px 10px;
      margin-bottom: 10px;

      &:hover {
        background-color: var(--el-fill-color-light);
        cursor: pointer;
      }

      div + div {
        margin-left: 10px;
      }

      .course_icon {
        color: #c0c4cc;
        font-size: 12px;
        width: 12px;
        height: 14px;
        display: block;
      }

      .course_play {
        color: #fff;
        font-size: 16px;
        width: 16px;
        height: 15px;
        display: block;
      }

      .course_number {
        background-color: #0d5aa3;
        font-size: 13px;
        text-align: center;
        padding: 4px 5px;
        border-radius: 4px;
      }

      .course_input {
        width: 300px;
        font-size: 13px;
      }
    }
  }
}
</style>
