<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <span>文件标题:</span>
      <el-input
        v-model="listQuery.fileTitle"
        placeholder="文件标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="getList"
      />
      <span>审核状态:</span>
      <el-select
        v-model="listQuery.auditStatus"
        placeholder="审核状态"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="getList"
      >
        <el-option label="全部" value="" />
        <el-option label="待审核" :value="2" />
        <el-option label="审核通过" :value="1" />
        <el-option label="审核未通过" :value="0" />
      </el-select>
      <span>上线状态:</span>
      <el-select
        v-model="listQuery.status"
        placeholder="上线状态"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="getList"
      >
        <el-option label="全部" value="" />
        <el-option label="已上线" :value="1" />
        <el-option label="待上线" :value="2" />
        <el-option label="未上线" :value="0" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
      <el-button
        v-if="userIdentity === 2 || proxyInfo !== null"
        icon="el-icon-edit"
        type="primary"
        @click="handleShowDialog('add')"
      >添加文件</el-button>
    </div>
    <!-- 搜索区域END -->
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
      fit
      highlight-current-row
      cell-class-name="table-cell"
    >
      <el-table-column label="序号" :index="indexMethod" type="index" width="80" align="center" />
      <el-table-column label="文件标题" prop="fileTitle" align="center" />
      <el-table-column label="审核状态" width="180px" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.auditStatus === 2" size="small" type="warning">待审核</el-tag>
          <el-tag v-if="row.auditStatus === 1" size="small" type="success">审核通过</el-tag>
          <!-- 未通过原因展示 -->
          <template v-if="row.auditStatus === 0">
            <!-- <span class="status danger">审核未通过&nbsp;</span> -->
            <el-popover placement="top-start" title="审核说明" width="400" trigger="hover" :content="row.invalidReason">
              <el-tag slot="reference" size="small" type="danger" class="reason">
                <span>审核未通过</span>
                <span class="el-icon-question status danger " />
              </el-tag>
            </el-popover>
            <!-- 未通过原因展示END -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="上线状态" width="180px" align="center">
        <template slot-scope="{ row }">
          <!-- 只有审核通过了才能操作上下线 auditStatus ：审核状态 -->
          <template v-if="row.auditStatus === 1">
            <template v-if="row.status === 0">
              <span style="margin-right:10px;" class="status danger">已下线</span>
              <el-button
                v-if="userIdentity === 2 || proxyInfo !== null"
                type="primary"
                size="mini"
                @click="handleChangeStatus(row)"
              >上线</el-button>
            </template>
            <template v-else>
              <span style="margin-right:10px;" class="status success ">已上线</span>
              <el-button
                v-if="userIdentity === 2 || proxyInfo !== null"
                type="info"
                size="mini"
                plain
                @click="handleChangeStatus(row)"
              >下线</el-button>
            </template>
          </template>
          <template v-else>
            <!-- <el-tag type="warning">待上线</el-tag> -->
            <span style="margin-right:10px;" class="status warning">待上线</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="240px" align="center">
        <template slot-scope="{ row }">
          {{ row.createTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            style="margin-right:5px"
            icon="el-icon-view"
            @click="handlePreviewFile(row)"
          >预览</el-button>
          <el-button
            type="primary"
            size="mini"
            style="margin-right:5px"
            icon="el-icon-edit"
            @click="handleShowDialog('edit', row)"
          >编辑</el-button>
          <el-button
            type="danger"
            size="mini"
            style="margin-right:5px"
            icon="el-icon-s-check"
            @click="handleRemoveFile(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格区域END -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList(listQuery)"
    />
    <!-- 视频预览对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="dialogColosed"
      @close="beforeDialogClose"
    >
      <el-form ref="formRef" :model="dialogData" label-width="110px" :rules="dialogFormRules">
        <el-form-item label="标题：" prop="fileTitle">
          <el-input v-model="dialogData.fileTitle" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="上传文件：" prop="filePreviewUrl" style="margin-bottom:0">
          <div class="file-upload-box">
            <!-- 上传文件组件 -->
            <el-upload
              ref="uploadFileRef"
              accept=".pdf"
              :class="{ hidden: hasFile }"
              :auto-upload="false"
              :headers="headers"
              :action="action"
              :on-success="fileUploadSuccess"
              :on-change="fileUploadChange"
              :on-remove="fileUploadRemove"
              :before-upload="beforeUpload"
              :file-list="fileList"
            >
              <el-button size="mini" type="primary" style="width:100%">上传文件</el-button>
            </el-upload>
            <el-input v-model="dialogData.filePreviewUrl" type="hidden" class="hiddenInput" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSave">提 交</el-button>
      </div>
    </el-dialog>
    <!-- 视频预览对话框END -->
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { formatDate } from '@/utils'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { changeFileStatus, getFileList, removeFile, saveFile } from '@/api/doc'
import openWindow from '@/utils/open-window'
export default {
  components: { Pagination },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      listLoading: false, // 列表加载
      submitLoading: false, // 按钮加载
      total: 0, // 列表条数
      dialogVisible: false, // 是否显示dialog
      dialogTitle: '添加文件', // dialog标题
      hasFile: false, // 是否上传了文件
      previewUrl: '', // 上传文件成功后的url
      downloadUrl: '',
      chooseNewFile: false, // 是否选择了新的图片上传
      listQuery: {
        authUserId: '', // 供应商用户id
        listType: 1, // 列表类型：1视频列表，2视频审核列表
        fileTitle: '', // 文件标题
        auditStatus: '', // 审核状态：0审核未通过，1审核通过，2待审核
        status: '', // 视频状态：0已下线，1已上线，2待上线
        pageNum: 1, // 页码
        pageSize: 10 // 分页大小
      },
      fileList: [],
      // dialog表单中的数据
      dialogData: {
        authUserId: '',
        fileTitle: '',
        fileId: '',
        // fileUrl: '',
        fileName: '',
        filePreviewUrl: '',
        fileDownloadUrl: ''
      },
      // dialog表单数据校验规则
      dialogFormRules: {
        fileTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        filePreviewUrl: [{ required: true, message: '文件不能为空', trigger: 'change' }]
      },
      list: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'proxyInfo']),
    headers() {
      return {
        'X-Token': getToken()
      }
    },
    action() {
      return `${process.env.VUE_APP_UPLOAD_API}/upload/file`
    }
  },
  created() {
    this.getList()
  },
  methods: {

    // 小窗口浏览pdf文件
    handlePreviewFile(row) {
      console.log(row)
      openWindow(row.filePreviewUrl, row.fileTitle, row.fileTitle, 1200, 600)
    },

    // 获取列表数据
    getList() {
      this.listLoading = true
      this.listQuery.authUserId = this.authUserId
      getFileList(this.listQuery)
        .then(res => {
          if (res.code !== 0) return
          this.list = res.data.list
          this.total = res.data.total
          console.log(res)
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 点击保存按钮
    handleSave() {
      if (!this.dialogData.fileTitle || !this.dialogData.filePreviewUrl) {
        this.$refs.formRef.validateField('fileTitle')
        this.$refs.formRef.validateField('filePreviewUrl')
        return
      }
      // 对标题字段进行规则校验
      console.log(this.dialogData)
      this.$refs.formRef.validateField('fileTitle', error => {
        if (!error) {
          this.submitLoading = true
          this.hasFile && !this.chooseNewFile ? this.save() : this.$refs.uploadFileRef.submit()
        }
      })
    },
    // 调用保存数据接口
    save() {
      this.$refs.formRef.validate(valide => {
        if (!valide) return
        this.dialogData.authUserId = this.authUserId
        if (this.previewUrl && this.downloadUrl) {
          this.dialogData.filePreviewUrl = this.previewUrl
          this.dialogData.fileDownloadUrl = this.downloadUrl
        }
        console.log(this.dialogData)
        console.log('保存')
        saveFile(this.dialogData)
          .then(res => {
            console.log(res)
            if (res.code !== 0) return
            this.dialogVisible = false
            this.getList()
            this.$message({
              type: 'success',
              message: res.data,
              duration: 500
            })
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    // 删除视频
    async handleRemoveFile(row) {
      const text = await this.$confirm('视频删除后不可恢复，确认删除该视频吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      removeFile({ fileId: row.fileId }).then(res => {
        if (res.code !== 0) return
        this.$message.success(res.data)
        this.getList()
      })
    },
    // 显示dialog对话框
    handleShowDialog(type, row) {
      this.dialogTitle = type === 'add' ? '添加文件' : '修改文件'
      this.$refs?.formRef?.resetFields()
      this.dialogVisible = true
      if (type !== 'add') {
        this.setDialogData(row)
      }
    },
    // 设置表单初始值
    setDialogData(row) {
      console.log(row)
      if (!row) return
      for (const key in this.dialogData) {
        if (Object.hasOwnProperty.call(this.dialogData, key)) {
          this.dialogData[key] = row[key]
        }
      }
      if (this.dialogData.filePreviewUrl) {
        this.fileList = [{ name: row.fileName, url: row.filePreviewUrl }]
        this.hasFile = true
      }
    },
    // dialog对话框关闭时的回调
    dialogColosed() {
      this.dialogData.authUserId = ''
      this.dialogData.fileTitle = ''
      this.dialogData.fileId = ''
      this.dialogData.filePreviewUrl = ''
      this.dialogData.fileDownloadUrl = ''
      this.dialogData.fileName = ''
      this.previewUrl = ''
      this.downloadUrl = ''
      this.chooseNewFile = false
      this.hasFile = false
      this.fileList = []
      this.submitLoading = false
      console.log(this.dialogData)
    },
    // 对话框关闭前的回调
    beforeDialogClose() {
      console.log('对话框关闭')
      // this.$refs.formRef.clearValidate()
      // 停止上传文件
      this.$refs.formRef.resetFields()
      this.$refs.uploadFileRef.abort()
    },
    // 上传文件成功
    fileUploadSuccess(response) {
      // this.dialogData.fileUrl = response.fileUrl
      this.previewUrl = response.previewUrl
      this.downloadUrl = response.downloadUrl
      this.dialogData.fileName = response.fileName
      this.save()
      console.log(response)
    },
    // 上传文件成功，选择文件，上传文件失败的回调
    fileUploadChange(file, fileList) {
      this.hasFile = fileList.length > 0
      this.dialogData.filePreviewUrl = '-'
      this.dialogData.fileDownloadUrl = '-'
      this.chooseNewFile = true
    },
    // 移除文件
    fileUploadRemove(file, fileList) {
      this.dialogData.filePreviewUrl = ''
      this.dialogData.fileDownloadUrl = ''
      this.hasFile = fileList.length > 0
    },
    beforeUpload(file, fileList) {
      const flag = file.size <= 100 * 1024 * 1204
      if (!flag) {
        this.$message({
          message: '文件大小超过100MB，请重新选择！',
          duration: 1000,
          type: 'warning'
        })
        this.fileList = []
      }
      return flag
    },
    // 状态改变
    handleChangeStatus(item) {
      this.listLoading = true
      // const params = {
      //   authId: item.authId,
      //   status: item.status ? 1 : 0
      // }
      console.log(item)
      const params = {
        fileId: item.fileId,
        status: item.status === 1 ? 0 : 1
      }
      changeFileStatus(params)
        .then(res => {
          // this.$message.success(res.data)
          this.$message({
            message: res.data,
            duration: 500,
            type: 'success'
          })
          this.getList()
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  span {
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
    font-size: 14px;
  }
  .el-button {
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
  }
  .el-input,
  .el-select {
    margin-right: 10px;
    margin-left: 10px;
  }
}
.el-table .cell {
  overflow: visible;
}
.el-badge {
  margin: 0 6px;
}
</style>
