<template>
  <div class="app-container">
    <div>
      <el-input
        v-model="listQuery.search"
        placeholder="名称/描述"
        style="width: 300px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-refresh-left"
        @click="resetFilter"
      >刷新重置</el-button>
    </div>
    <div style="margin-top:6px">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate('文档')">文档</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate('视频')">视频</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="materialList.results"
      style="width: 100%;margin-top:10px;"
      border
      fit
      stripe
      highlight-current-row
      max-height="600"
    >
      <el-table-column type="index" width="50" />
      <el-table-column label="名称">
        <template slot-scope="scope">
          <el-link
            type="primary"
            :href="scope.row.path"
            target="_blank"
            v-if="scope.row.path"
          >{{ scope.row.name }}</el-link>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">{{ scope.row.type }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="排序码">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>
      <el-table-column label="上传时间">
        <template slot-scope="scope">{{ scope.row.create_time }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="下载量/播放量">
        <template slot-scope="scope">{{ scope.row.down_count }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            :disabled="!checkPermission(['material_update'])"
            @click="handleUpdate(scope)"
          />
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            :disabled="!checkPermission(['material_delete'])"
            @click="handleDelete(scope)"
          />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="materialList.count>0"
      :total="materialList.count"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='update'?'编辑':'新增'"
      :close-on-click-modal="false"
    >
      <el-form
        ref="Form"
        :model="material"
        label-width="80px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="material.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="material.description" placeholder="描述" />
        </el-form-item>
        <el-form-item label="排序" prop="description">
        <el-input-number v-model="material.sort" :min="1"></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="封面" prop="poster" v-if="material.type=='视频'">
          <el-upload
            accept=".png, .jpeg, .jpg"
            :before-upload="beforeUploadP"
            :action="upUrl"
            :headers="upHeaders"
            :on-success="handleSuccessP"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <img v-if="material.poster" :src="material.poster" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item :label="material.type=='文档'?'文件':'视频'" prop="path" v-if="dialogVisible">
          <el-upload
            v-if="material.type=='文档'"
            :on-preview="handlePreview"
            :on-success="handleSuccess"
            :action="upUrl"
            :headers="upHeaders"
            :limit="1"
            :file-list="fileList"
            accept=".pdf, .doc, .docx"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <!-- <el-upload
            v-else
            class="avatar-uploader"
            :action="upUrl"
            :headers="upHeaders"
            :show-file-list="false"
            :on-success="handleSuccessV"
            :before-upload="beforeUploadV"
            :on-progress="upVideoProgess"
            accept=".mp4, .m3u8"
          >
            <video
              v-if="material.path"
              :src="material.path"
              class="avatar"
              controls="controls"
            >您的浏览器不支持视频播放</video>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <el-progress
              v-if="videoFlag == true"
              :percentage="upVideoPercent"
              style="margin-top:30px;"
            ></el-progress>
          </el-upload>
          <div >请保证视频格式正确，且不超过100M</div> -->
          <el-input v-else v-model="material.path" placeholder="腾讯视频地址" />
        </el-form-item>
      </el-form>

      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 360px;
  height: 200px;
  display: block;
}
</style>
<script>
import {
  getMaterialList,
  createMaterial,
  updateMaterial,
  deleteMaterial,
} from "@/api/cms";
import { upUrl, upHeaders } from "@/api/file";
import Pagination from "@/components/Pagination";
import checkPermission from "@/utils/permission";
const defaultmaterial = {
  id: null,
  name: null,
  description: null,
  path: null,
  poster: null,
  type: "文档",
};
export default {
  components: { Pagination },
  data() {
    return {
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      materialList: { count: 0 },
      material: Object.assign({}, defaultmaterial),
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
      },
      dialogVisible: false,
      dialogType: "create",
      rule1: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        path: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      fileList: [],
      videoFlag:false,
      upVideoPercent:0
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      getMaterialList(this.listQuery).then((response) => {
        if (response.data) {
          this.materialList = response.data;
        }
        this.listLoading = false;
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleDelete(scope) {
      deleteMaterial(scope.row.id).then((res) => {
        this.getList();
      });
    },
    handleCreate(val) {
      this.material = Object.assign({}, defaultmaterial);
      this.material.type = val;
      this.fileList = [];
      this.dialogType = "create";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleUpdate(scope) {
      this.material = Object.assign({}, scope.row); // copy obj
      if (this.material.path) {
        this.fileList = [
          {
            name:
              this.material.name +
              "." +
              this.material.path.split(".")[
                this.material.path.split(".").length - 1
              ],
            url: this.material.path,
          },
        ];
      }
      this.dialogType = "update";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    beforeUploadP(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error("上传封面大小不能超过 1MB!");
      }
      return isLt1M;
    },
    beforeUploadV(file) {
      const isLt1M = file.size / 1024 / 1024 < 100;
      if (!isLt1M) {
        this.$message.error("上传视频大小不能超过 100MB!");
      }
      return isLt1M;
    },
    handleSuccess(response, file, fileList) {
      this.material.path = response.data.path;
    },
    handleSuccessV(response, file, fileList) {
      this.videoFlag = false
      this.material.path = response.data.path;
    },
    handleSuccessP(response, file, fileList) {
      this.material.poster = response.data.path;
    },
    upVideoProgess(event, file, fileList){
    this.videoFlag = true;
    this.upVideoPercent = file.percentage.toFixed(0);
    },
    async confirm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "update";
          if (isEdit) {
            updateMaterial(this.material.id, this.material).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              }
            });
          } else {
            createMaterial(this.material)
              .then((res) => {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              })
              .catch((error) => {});
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
