<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             @submit.native.prevent>
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
        <el-button v-if="resourceBase.isView" plain icon="el-icon-close" size="mini" @click="closeCurrentTab">关闭
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!resourceBase.isView">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="warning"-->
      <!--    plain-->
      <!--    icon="el-icon-download"-->
      <!--    size="mini"-->
      <!--    @click="handleExport"-->
      <!--    v-hasPermi="['system:resources:export']"-->
      <!--  >导出-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <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="name"/>
      <el-table-column label="资源类别" align="center" prop="resourceName"/>
      <el-table-column label="下载次数" align="center" prop="download"/>
      <el-table-column label="点赞次数" align="center" prop="thumbsUp"/>
      <el-table-column label="收藏次数" align="center" prop="collection"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownLoad(scope.row)"
                     v-hasPermi="['system:resources:edit']">下载
          </el-button>
          <el-button size="mini" type="text" @click="handleThumbUp(scope.row)" v-hasPermi="['system:resources:edit']">
            <svg-icon icon-class="thumb-up"></svg-icon>
            <span v-html="`&nbsp;点赞`"></span>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-star-off" @click="handleCollection(scope.row)"
                     v-hasPermi="['system:resources:edit']">收藏
          </el-button>
          <el-button v-if="!resourceBase.isView" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)" v-hasPermi="['system:resources:edit']">修改
          </el-button>
          <el-button v-if="!resourceBase.isView" 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>

    <ExPagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>

    <!-- 添加或修改学校资源库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <!--<el-form-item v-if="form.id" label="文件">-->
          <!--  <el-link :href="form.url" type="primary" :underline="false" @click="downloadFile(form.url)">{{-->
          <!--      form.name-->
          <!--    }}-->
          <!--  </el-link>-->
          <!--</el-form-item>-->
          <el-col :span="12">
            <el-form-item label="资源类型" prop="resourcesId">
              <el-select v-model="form.resourcesId">
                <el-option v-for="item in selectOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件上传" prop="url">
              <el-upload class="upload-demo" ref="upload" action="#" :auto-upload="true" :before-upload="beforeUpload"
                         :on-change="fileChange" :http-request="uploadFile" :on-remove="handleRemoveFile"
                         :file-list="fileList">
                <el-button slot="trigger" size="small" type="primary">选取文件
                </el-button>
                <!--<el-button-->
                <!--  v-show="upload.hasFile"-->
                <!--  style="margin-left: 10px"-->
                <!--  size="small"-->
                <!--  type="success"-->
                <!--  @click="submitFile"-->
                <!--&gt;上传文件-->
                <!--</el-button>-->
              </el-upload>
              <el-progress v-if="upload.isUploading" :percentage="upload.progress"></el-progress>
            </el-form-item>
          </el-col>
        </el-row>
      </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>
  </div>
</template>

<script>
import {
  addResourceDetail,
  deleteResourceDetail,
  editResourceDetail,
  getInfo,
  getList,
  updateCollection, updateDownload,
  updateThumbsUp
} from "@/api/smartSchool/schoolResources/resourceInfo";
import {getList as getResouceList} from "@/api/smartSchool/schoolResources/resource";
import {commonUpload} from "@/api/common";
import {isString} from "@/utils/validate";
import {downLoadFile} from "@/utils/utilLibrary/downloadFile";
import {closeCurrentTab} from "@/utils/utilLibrary/routerBatch/routerBatch";

export default {
  name: "Resourceinfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校资源库表格数据
      resourcesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 文件回显
      fileList: [],
      // 表单校验
      rules: {
        name: [
          {required: true, message: "资源名称不能为空", trigger: "blur"},
        ],
        resourcesId: [
          {required: true, message: "资源类型不能为空", trigger: "change"},
        ],
        url: [{required: true, message: "文件不能为空", trigger: "change"}],
      },
      // 资源类型下拉框选项
      selectQueryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      // 加载下拉框
      selectLoading: false,
      // 数据总数
      selectTotal: 0,
      // 资源下拉框数据
      selectOptions: [],
      // 上传
      upload: {
        isUploading: false,
        progress: 0,
        hasFile: false,
      },
      // 作为共用组件：{主键, 是否只读: 默认可编辑}
      resourceBase: {
        primaryKey: undefined,
        isView: false,
      },
    };
  },
  created() {
    this.resourceBase.primaryKey = this.$route.params && this.$route.params.id;
    this.resourceBase.isView =
      this.$route.query && (this.$route.query.view ? true : false);
    this.getList();
  },
  directives: {
    /** 下拉框懒加载 */
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
  methods: {
    closeCurrentTab,
    /** 查询学校资源库列表 */
    getList() {
      this.loading = true;
      getList({
        ...this.queryParams,
        resourcesId: this.resourceBase.isView
          ? this.resourceBase.primaryKey
          : undefined,
      }).then((response) => {
        this.resourcesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取资源类型数据 */
    getClassifications(name = null) {
      const {pageNum, pageSize} = this.selectQueryParams;
      if (pageNum === 1 || (pageNum - 1) * pageSize < this.selectTotal) {
        this.selectLoading = true;
        getResouceList({pageNum, pageSize, name})
          .then((response) => {
            this.selectLoading = false;
            // this.selectOptions.push(...response.rows);
            this.selectOptions = response.rows;
            this.selectTotal = response.total;
            ++this.selectQueryParams.pageNum;
          })
          .catch((error) => {
            this.selectLoading = false;
          });
      }
    },
    //
    // /** 搜索下拉框中的数据 */
    // filterMethod(queryParams) {
    //   this.throttle(() => {
    //     this.selectQueryParams.pageNum = 1;
    //     this.selectTotal = 0;
    //     this.selectOptions = [];
    //     this.getClassifications(queryParams);
    //   })
    //
    // },

    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.upload.clearFiles();
      this.upload.hasFile = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resourcesId: null,
        name: "",
        url: "",
        resourceName: ""
      };
      this.resetForm("form");
    },

    /** 重置下拉框 */
    resetSelectOptions() {
      this.selectQueryParams.pageNum = 1;
      this.selectQueryParams.pageSize = 20;
      this.selectTotal = 0;
      this.getClassifications();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetSelectOptions();
      this.open = true;
      this.title = "添加学校资源库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.resetSelectOptions();
      const id = row.id || this.ids;
      getInfo(id).then((response) => {
        if (response.data.name) {
          this.fileList = [{
            name: response.data.name,
            url: response.data.url || 0,
          }];
        }
        this.form = response.data;
        this.title = "修改学校资源库";
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validateField("resourcesId", (errMessage) => {
        if (!errMessage) {
          if (!this.form.url) {
            this.$message.warning("请先上传文件");
          } else if (!this.form.name) {
            this.$message.warning("文件名不能为空");
          } else {
            this.$modal.loading("正在上传数据，请稍等...");
            if (this.form.id != null) {
              editResourceDetail(this.form)
                .then((response) => {
                  this.$modal.closeLoading();
                  this.$modal.msgSuccess("修改成功");
                  this.getList();
                  this.cancel();
                })
                .catch((error) => {
                  this.$modal.closeLoading();
                });
            } else {
              addResourceDetail(this.form)
                .then((response) => {
                  this.$modal.closeLoading();
                  this.$modal.msgSuccess("新增成功");
                  this.getList();
                  this.cancel();
                })
                .catch((error) => {
                  this.$modal.closeLoading();
                });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          `是否确认删除选中的 ${Object.hasOwnProperty.call(ids, "length") ? ids.length : 1
          } 条数据项？`
        )
        .then(function () {
          return deleteResourceDetail(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('schoolResources/export', {
    //     ...this.queryParams
    //   }, `resources_${ new Date().getTime() }.xlsx`)
    // },

    /** 下载 */
    handleDownLoad({url, name, id}) {
      if (isString(url) && url.lastIndexOf("/") > -1) {
        // this.$download.name(url.slice(url.lastIndexOf("/") + 1), false);
        // this.download(url, {});
        // downLoadFile(url, name);
        updateDownload(id).then(response => {
          this.$download.resource(url);
          this.getList();
        }).catch(error => {
        })
      } else {
        return "";
      }
    },

    /** 收藏 */
    handleCollection({id}) {
      updateCollection(id).then(response => {
        this.$modal.msgSuccess('收藏成功');
        this.getList();
      }).catch(error => {
      })
    },

    /** 点赞 */
    handleThumbUp({id}) {
      updateThumbsUp(id).then(response => {
        this.$modal.msgSuccess('点赞成功');
        this.getList();
      }).catch(error => {
      })
    },

    /** 上传文件前的钩子 */
    beforeUpload() {
      this.upload.isUploading = false;
      this.upload.progress = 0;
    },

    /** 添加的文件时触发该钩子 */
    fileChange(file, fileList) {
      fileList.length > 0 && (this.upload.hasFile = true);
      this.$refs.upload.uploadFiles = [file];
    },

    /** 上传文件到服务器 */
    submitFile() {
      this.$refs.upload.submit();
    },

    /** 删除文件 */
    handleRemoveFile(file, fileList) {
      fileList.length === 0 && (this.upload.hasFile = false);
    },

    /** 文件上传 */
    uploadFile(file, fileList) {
      const fileData = file.file;
      const fileName = fileData && fileData.name;
      const formData = new FormData();
      formData.append("file", fileData);
      this.upload.isUploading = true;
      commonUpload(formData, (progress) => {
        const {loaded, total} = progress;
        this.upload.progress = Math.round((loaded / total) * 100) | 0;
      }).then((response) => {
        this.$message.success("上传成功");
        this.form.url = response.url;
        this.form.name = fileName;
        this.upload.isUploading = false;
      });
    },

    /** 文件下载 */
    downloadFile(fileUrl) {
    },

    /** 返回资源库 */
    // handleClose() {
    //   this.$tab.closeOpenPage({ path: "/otherManage/resource/schoolResourcesBase" });
    // },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list__item {
  transition: none !important;
}
</style>
