<template>
  <div class="app-container">
    <form-search :searchformShow="searchformShow" @handleQuery="handleQuery" @change="formChange" @resetQuery="resetQuery"></form-search>
    <el-card class="box-card" style="margin-bottom:30px">
      <el-row :gutter="24">
        <el-col :span="4">
          <h3 style="padding-left: 11px;border-left: 2px solid #e6a700;color: #e6a700;">章节目录</h3>
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="treeProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <el-col :span="20">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" v-hasPermi="['front:cloudResource:downloadToPersonResourse']">
              <el-button plain icon="el-icon-download" size="small" @click="downToPersonResourse" :disabled="multiple">下载至个人资源库</el-button>
            </el-col>

            <el-table v-loading="loading" :data="resourcesList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="文件" align="center" prop="resourcesName" v-if="viewName=='Index'">
                <template slot-scope="scope">
                  <img style="width:130px;height:80px ;cursor:pointer" :src="img.ship" @click="handleView(scope.row)" alt />
                </template>
              </el-table-column>
              <el-table-column label="文件名" align="center" prop="resourcesName" />
              <el-table-column label="发布人" align="center" prop="createBy" />
              <el-table-column label="时间" align="center" prop="createTime" />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                v-if="userInfo && userInfo.roles && userInfo.roles[0].roleId == 5"
              >
                <template slot-scope="scope">
                  <el-button v-if="viewName!='Index'" size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">预览</el-button>
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:resources:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList" />
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加或修改云库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资源名称" prop="resourcesName">
          <el-input v-model="form.resourcesName" placeholder="请输入资源名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <upload-dialog
      v-if="dialogVisible"
      :title="title"
      :page-name="queryParams.category"
      :dialogVisible="dialogVisible"
      @handleClose="handleClose"
      @dialogVisibleClose="dialogVisibleClose"
    ></upload-dialog>
    <el-dialog v-if="dialogVideo" title="查看视频" :visible.sync="dialogVideo" width="60%">
      <mx-video :aliIdType="aliIdType" :src="src" controls></mx-video>
    </el-dialog>
  </div>
</template>

<script>
import aliplayer from "../videocourse/compoent/aliplayer";
import {
  addCloudResource,
  deleteCloudResource,
  getCloudResourceDetail,
  getCloudResources,
  getVideoPlayAuth,
  modifyCloudResource,
  downToSchoolResourse,
  downToPersonResourse,
} from "@/api/webApi/cloud";
import { treeList } from "@/api/webApi/webQue.js";
import { mapGetters } from "vuex";

import { getUserInfo } from "@/utils/auth";
export default {
  components: {
    aliplayer,
  },
  data() {
    return {
      src: "",
      aliIdType: "",
      coverUrl: "",
      dialogVideo: false,
      videoId: null,
      isVideo: null,
      searchformShow: {},
      dialogVisible: false,
      img: {
        ship: require("@/assets/images/ship.png"),
      },
      treeProps: {
        children: "children",
        label: "name",
        code: "id",
      },
      deptOptions: undefined,
      deptName: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 云库表格数据
      resourcesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 资源类型字典
      typeOptions: [],
      // 资源分类字典
      categoryOptions: [],
      // 是否删除字典
      delFlagOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourcesName: null,
        type: null,
        category: null,
        province: null,
        city: null,
        county: null,
        chapterId: null,
        resourcesUrl: null,
        bookId: null,
        subjectId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        resourcesName: [
          { required: true, message: "资源名称不能为空", trigger: "blur" },
        ],
        category: [
          { required: true, message: "资源分类不能为空", trigger: "change" },
        ],
        chapterId: [
          { required: true, message: "章节不能为空", trigger: "blur" },
        ],
        bookId: [{ required: true, message: "学册不能为空", trigger: "blur" }],
        subjectId: [
          { required: true, message: "科目不能为空", trigger: "blur" },
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "change" },
        ],
        createBy: [
          { required: true, message: "创建者Id不能为空", trigger: "blur" },
        ],
      },
      viewName: "",
    };
  },
  computed: {
    ...mapGetters(["currentUser"]),
    userInfo() {
      // TODO: hht 22.1.5 兼容历史写法，待清理
      return this.currentUser;
    },
  },
  created() {
    this.viewName = this.$route.name;
    if (this.viewName == "Index") {
      this.searchformShow = {
        province: "",
        subjectid: "",
        edition: "",
        slipid: "",
      };
    } else if (this.viewName == "Courseware") {
      this.searchformShow = {
        province: "",
        subjectid: "",
        edition: "",
        slipid: "",
        coursewareType: "",
      };
    }
    this.getList();
    this.getDicts("resource_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("category").then((response) => {
      this.categoryOptions = response.data;
    });
    this.getDicts("bool_flag").then((response) => {
      this.delFlagOptions = response.data;
    });
  },
  methods: {
    handlePlay() {
      console.log(111);
    },
    handleView(row) {
      if (row.resourcesUrl.indexOf(".pdf") != -1) {
        window.open("/pdfView/index.html?src=" + row.resourcesUrl);
      } else if (
        row.resourcesUrl.indexOf(".doc") != -1 ||
        row.resourcesUrl.indexOf(".ppt") != -1 ||
        row.resourcesUrl.indexOf(".xls") != -1 ||
        row.resourcesUrl.indexOf(".xlsx") != -1
      ) {
        window.open(
          "https://view.officeapps.live.com/op/view.aspx?src=" +
            row.resourcesUrl
        );
      } else {
        this.src = row.resourcesUrl;
        this.aliIdType = row.aliIdType;
        this.dialogVideo = true;
      }
    },

    /** 查询个人资源库列表 */
    getList() {
      this.loading = true;
      if (this.viewName == "Index") {
        this.queryParams.category = "微课视频";
      } else if (this.viewName == "Courseware") {
        this.queryParams.category = "课件资源";
      }
      let Ajax = {
        subjectId: this.queryParams.subjectid, //科目
        bookId: this.queryParams.slipid, //学册
        chapterId: this.queryParams.chapterId, //章节
        coursewareType: this.queryParams.coursewareType,
        province: this.queryParams.province,
        city: this.queryParams.city,
        county: this.queryParams.area,
        schoolId: this.queryParams.schoolid,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        category: this.queryParams.category,
      };
      getCloudResources(Ajax)
        .then((response) => {
          this.resourcesList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 资源类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 资源分类字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    // 是否删除字典翻译
    delFlagFormat(row, column) {
      return this.selectDictLabel(this.delFlagOptions, row.delFlag);
    },

    handleClose(type, name) {
      let _this = this;
      if (this.title == "下载至个人资源库") {
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item,
          };
          if (name) {
            Ajax.resourcesName = name;
          }
          downToPersonResourse(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess("操作成功");
              _this.dialogVisible = false;
            }
          });
        });
      } else {
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item,
          };
          if (name) {
            Ajax.resourcesName = name;
          }
          downToSchoolResourse(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess("操作成功");
              _this.dialogVisible = false;
            }
          });
        });
      }
    },
    downToPersonResourse() {
      let _this = this;
      const resourcesIds = this.ids.join(",");
      this.title = "下载至个人资源库";
      this.dialogVisible = true;
    },
    downToSchoolResourse() {
      let _this = this;
      const resourcesIds = this.ids.join(",");
      this.title = "下载至校本资源库";
      this.dialogVisible = true;
    },
    dialogVisibleClose() {
      this.dialogVisible = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resourcesId: null,
        resourcesName: null,
        sourceId: null,
        category: null,
        chapterId: null,
        knowledgeBasicId: null,
        resourcesUrl: null,
        type: null,
        linkWay: null,
        bookId: null,
        customerId: null,
        subjectId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        remark: null,
      };
    },
    formChange(data, type) {
      console.log(data);
      this.queryParams = data;
      this.getTreeselect(type);
    },
    /** 搜索按钮操作 */
    handleQuery(data) {
      this.pageNum = 1;
      this.queryParams = Object.assign(this.queryParams, data);
      this.getList();
      // this.getTreeselect()
    },
    /** 重置按钮操作 */
    resetQuery(data) {
      this.queryParams = data;
      this.queryParams.chapterId = "";
      this.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.resourcesId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加云库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getCloudResourceDetail({ resourcesId: row.resourcesId }).then(
        (response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改云库";
        }
      );
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.resourcesId != null) {
            modifyCloudResource(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCloudResource(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const resourcesIds = row.resourcesId || this.ids;
      this.$confirm(
        '是否确认删除云库名称为"' + row.resourcesName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteCloudResource(row.resourcesId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有云库数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportList(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        });
    },

    /** 查询部门下拉树结构 */
    getTreeselect(type) {
      if (!this.queryParams.slipid) {
        this.deptOptions = [];
        return;
      }
      if (type != "slipid") {
        return;
      }
      let Ajax = {
        editionId: this.queryParams.edition, //版本
        subjectId: this.queryParams.subjectid, //科目
        pharseId: this.queryParams.pharseId, //pharseId
        gradeId: this.queryParams.slipid, //学册
        // gradeid:301
      };
      this.treeLoading = true;
      treeList(Ajax)
        .then((response) => {
          this.deptOptions = response.data;
          this.treeLoading = false;
        })
        .catch((response) => {
          this.treeLoading = false;
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (!data.children?.length) {
        this.pageNum = 1;
        this.queryParams.chapterId = data.id;
        this.getList();
      } else {
        this.queryParams.chapterId = "";
      }
    },
  },
};
</script>
