<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>
        </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 align="header-center" 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="path">
          <el-upload
  
  :on-preview="handlePreview"
  :on-success="handleSuccess"
  :action="upUrl"
  :headers="upHeaders"
  :limit="1"
  :file-list="fileList"
  >
  <el-button size="small" type="primary" >点击上传</el-button>
  
</el-upload>
        </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>
<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,
  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:[]
    };
  },
  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() {
      this.material = Object.assign({}, defaultmaterial);
      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)
      }
      
    },
    handleSuccess(response, file, fileList) {
      this.material.path = response.data.path
    },
    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.$notify({
                  title: "成功",
                  message: "编辑成功",
                  type: "success",
                  duration: 2000
                });
              }
            });
          } else {
            createMaterial(this.material).then(res => {
                this.getList();
                this.dialogVisible = false
                this.$notify({
                  title: "成功",
                  type: "success",
                })
              
            }).catch(error=>{})
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
