<script setup>
import { reactive, onMounted, ref, h } from "vue";
import { ElButton, ElInput, ElUpload } from "element-plus";
import { $message } from "@/utils/useMessage";
import BasicTable from "@/components/BasicElTable/BasicTable.vue";
import {
  getPageListByType,
  getType,
  getMapsItem,
  getPaperList,
} from "@/hooks/useCreateCourseMaps";
import apiCourseFile from "@/api/modules/courseFile";
import { useRoute } from "vue-router";
import Cookies from "vue-cookies";

const route = useRoute();
const props = defineProps({
  resType: {
    type: Number,
    default: "",
  },
});

// 响应式数据
const tableData = ref([]);
const loading = ref(false);
const fileList = ref([]);

// 表单数据
const form = reactive({
  name: "",
  resType: props.resType,
});

// 分页配置
const pagination = reactive({
  pageSize: 10,
  current: 1,
  total: 0,
});

// 视频表单数据
const dialogVideoForm = reactive({
  name: "",
  isDrag: false,
  completeSetup: 0,
  setupTage: "",
});

// 上传配置
const uploadData = reactive({
  headers: {
    "XBOE-Access-Token": Cookies.get("token"),
  },
  data: {
    dir: "course",
  },
  actionUrl: process.env.VUE_APP_SYS_API + "/xboe/sys/xuploader/file/upload",
});

// 表格列配置
const columns = [
  {
    title: "序号",
    render: (params) => {
      return h("span", {}, params.index + 1);
    },
  },
  {
    title: "名称",
    key: "name",
    dataIndex: "name",
  },
  {
    title: "创建人",
    key: "sysCreateBy",
    dataIndex: "sysCreateBy",
  },
  {
    title: "创建时间",
    key: "sysCreateTime",
    dataIndex: "sysCreateTime",
  },
  {
    title: "操作",
    key: "action",
    dataIndex: "action",
    width: 150,
    render: (params) => {
      return h("div", [
        h(
          ElButton,
          {
            type: "primary",
            size: "small",
            style: {
              display: [40, 50, 62].includes(props.resType) ? "" : "none",
            },
            onClick: () => {
              handlePreviewItem(params.row);
            },
          },
          "预览"
        ),
        h(
          ElButton,
          {
            type: "primary",
            size: "small",
            onClick: () => {
              handleChooseItem(params.row);
            },
          },
          "选择"
        ),
      ]);
    },
  },
];

// 事件发射
const emit = defineEmits(["chooseItem", "choosePreviewItem", "chooseCusExam"]);

// 处理选择项目
const handleChooseItem = (row) => {
  switch (props.resType) {
    case 61:
      console.log(row);
      if (row.counts === 0) {
        $message.error("此试卷无试题内容，请重新选择");
        return;
      }
      break;
    default:
      // emit("chooseItem", {
      //   ...row,
      //   isDrag: false,
      //   completeSetup: 0,
      //   setupTage: "",
      //   resType: props.resType,
      //   dir: props.resType === 50 ? "scorm" : "course",
      // });
      break;
  }
  let obj = {
    ...row,
    isDrag: false,
    completeSetup: 0,
    setupTage: "",
    resType: props.resType,
    dir: props.resType === 50 ? "scorm" : "course",
  };
  if (props.resType === 61) {
    obj.paperType = 2;
  }
  emit("chooseItem", obj);
};

const handlePreviewItem = (row) => {
  emit("choosePreviewItem", {
    ...row,
    isDrag: false,
    completeSetup: 0,
    setupTage: "",
    resType: props.resType,
    dir: props.resType === 50 ? "scorm" : "course",
  });
};
// 分页改变处理
const changePagination = (PAGINATION) => {
  Object.assign(pagination, PAGINATION);
  getCourseList();
};

// 获取视频列表
const getCourseList = () => {
  loading.value = true;
  let paramsData = {};

  switch (props.resType) {
    // 考试
    case 61:
      paramsData = {
        keyWord: form.name,
        pageSize: pagination.pageSize,
        pageIndex: pagination.current,
      };
      getPaperList(paramsData).then((res) => {
        loading.value = false;
        tableData.value = res.result.list.map((item) => {
          return {
            ...item,
            name: item.testName,
          };
        });
        pagination.total = res.result.count;
      });
      break;
    default:
      // 非考试列表
      paramsData = {
        ...form,
        pageSize: pagination.pageSize,
        pageIndex: pagination.current,
        self: true,
      };

      getPageListByType(paramsData).then((res) => {
        loading.value = false;
        tableData.value = res.result.list;
        pagination.total = res.result.count;
      });
      break;
  }
};

// 上传成功处理
const handleUploadSuccess = (res, file) => {
  if (res.status === 200) {
    // 上传到课件库
    const routeQuery = route.query;
    const courseWare = {
      fileName: res.result.displayName,
      fileType: res.result.fileType,
      filePath: res.result.filePath,
      resType: props.resType,
      orgId: routeQuery.orgId,
      orgName: routeQuery.orgName,
      duration: routeQuery.duration,
      remark: "课程中直接上传",
    };

    apiCourseFile.saveUpload(courseWare).then((rs) => {
      if (rs.status === 200) {
        emit("chooseItem", {
          ...dialogVideoForm,
          name: res.result.displayName,
          resType: props.resType,
          ...rs.result,
        });
        fileList.value = [];
      } else {
        $message.error(rs.message);
      }
    });
  }
};

// 上传前处理
const handleBeforeUpload = (file) => {
  console.log(file);
  const { fileType, name, uploadSize, uploadSizeName } = getMapsItem(
    props.resType
  );

  if (file.name.lastIndexOf(".") === -1) {
    $message.error(`文件格式不正确!`);
    return false;
  }

  let fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
  fileExtension = fileExtension.toLowerCase();

  // 校检文件类型
  if (fileType.join(",").indexOf(fileExtension) === -1) {
    $message.error(`文件格式不正确, 请上传正确格式的${name}文件!`);
    return false;
  }

  // 校检文件大小
  if (uploadSize) {
    const isLt = file.size / 1024 / 1024 < uploadSize;
    if (!isLt) {
      $message.error(`上传文件大小不能超过 ${uploadSizeName} !`);
      return false;
    }
  }

  if (props.resType === 50) {
    dialogVideoForm.dir = "scorm";
  } else {
    dialogVideoForm.dir = "course";
  }

  return true;
};
const openCusExam = () => {
  emit("chooseCusExam", {
    resType: props.resType,
    dir: props.resType === 50 ? "scorm" : "course",
    paperType: 1,
    name: "自定义考试",
  });
};

// 生命周期
onMounted(() => {
  getCourseList();
});
</script>

<template>
  <div class="add-video">
    <div class="add-vide-header">
      <div style="display: flex; align-items: center">
        <el-upload
          :action="uploadData.actionUrl"
          :headers="uploadData.headers"
          :data="uploadData.data"
          :on-success="handleUploadSuccess"
          :file-list="fileList"
          :before-upload="handleBeforeUpload"
        >
          <el-button
            v-if="[10, 20, 40, 50].includes(props.resType)"
            type="primary"
            >上传新{{ getType(props.resType) }}</el-button
          >
        </el-upload>
        <el-button
          v-if="[61].includes(props.resType)"
          type="primary"
          @click="openCusExam"
          >自定义考试</el-button
        >
        <span class="desc ml10" v-if="![61].includes(props.resType)"
          >文件大小限制：{{
            getMapsItem(props.resType).uploadSizeName
          }},支持的文件类型:{{ getMapsItem(props.resType).fileType.join(",") }}
        </span>
      </div>
      <div>
        <el-input
          style="width: 150px"
          :placeholder="`请输入${getType(props.resType)}名称`"
          v-model="form.name"
          clearable
        ></el-input>
        <el-button class="ml10" @click="getCourseList" type="primary"
          >查询</el-button
        >
      </div>
    </div>
    <div class="mt10">
      <BasicTable
        :columns="columns"
        :data="tableData"
        :pagination="pagination"
        @changePage="changePagination"
        :loading="loading"
      ></BasicTable>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-video {
  .add-vide-header {
    display: flex;
    justify-content: space-between;
    .desc {
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
