<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <div class="filter-control">
        <span>资料包标题:</span>
        <el-input v-model="listQuery.fileTitle" placeholder="资料包标题" @keyup.enter.native="getList" />
      </div>
      <div class="filter-control">
        <span>审核状态:</span>
        <el-select v-model="listQuery.auditStatus" placeholder="审核状态" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="2" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核未通过" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>上线状态:</span>
        <el-select v-model="listQuery.status" placeholder="上线状态" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="已上线" :value="1" />
          <el-option label="待上线" :value="2" />
          <el-option label="未上线" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <permission-button type="primary" @click="getList">查询</permission-button>
        <permission-button type="primary" @click="handleShowDialog('add')">添加资料包</permission-button>
      </div>
    </div>
    <!-- 搜索区域END -->
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
      fit
      highlight-current-row
      cell-class-name="table-cell"
      header-row-class-name="tableHeader"
    >
      <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="120px" align="center">
        <template slot-scope="{ row }">
          <audit-status :status="row.auditStatus" :reason="row.invalidReason" />
        </template>
      </el-table-column>
      <el-table-column label="上线状态" width="160px" 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>
              <permission-button type="primary" size="mini" @click="handleChangeStatus(row)">上线</permission-button>
            </template>
            <template v-else>
              <span style="margin-right: 10px" class="status success">已上线</span>
              <permission-button type="info" size="mini" plain @click="handleChangeStatus(row)">下线</permission-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="160px" align="center">
        <template slot-scope="{ row }">
          {{ row.createTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="{ row }">
          <permission-button
            type="primary"
            size="mini"
            style="margin-right: 12px"
            @click="handleShowDialog('edit', row)"
          >编辑</permission-button>
          <permission-button
            type="danger"
            size="mini"
            style="margin-right: 12px"
            @click="handleRemoveFile(row)"
          >删除</permission-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格区域END -->
    <pagination
      :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"
      @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="fileName" style="margin-bottom: 0">
          <upload-file
            ref="fileUpload"
            accept=".zip,.rar,.7z"
            mode="document"
            :file-list="fileList"
            :auto-upload="false"
            :before-upload="beforeUpload"
            @success="handleUploadFileSuccess"
            @remove="handleRemoveUploadFile"
            @change="handleChooseFileChange"
          />
          <el-input v-show="false" v-model="dialogData.fileName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <permission-button @click="dialogVisible = false">取 消</permission-button>
        <permission-button type="primary" :loading="submitLoading" @click="handleSave">提 交</permission-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadFile from '@/components/UploadFile'
import { mapGetters } from 'vuex'
import { changeFileStatus, getFileList, removeFile, saveFile } from '@/api/doc'
import openWindow from '@/utils/open-window'
export default {
  components: { UploadFile },
  data() {
    return {
      listLoading: false, // 列表加载
      submitLoading: false, // 按钮加载
      total: 0, // 列表条数
      dialogVisible: false, // 是否显示dialog
      dialogTitle: '添加资料包：', // dialog标题
      listQuery: {
        fileType: 2,
        authUserId: '', // 供应商用户id
        listType: 1, // 列表类型：1文件列表，2文件审核列表
        fileTitle: '', // 文件标题
        auditStatus: '', // 审核状态：0审核未通过，1审核通过，2待审核
        status: '', // 文件状态：0已下线，1已上线，2待上线
        pageNum: 1, // 页码
        pageSize: 10 // 分页大小
      },
      fileList: [],
      // dialog表单中的数据
      dialogData: {
        fileType: 2,
        fileId: '',
        fileTitle: '',
        fileName: ''
      },
      // dialog表单数据校验规则
      dialogFormRules: {
        fileTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        fileName: [{ required: true, message: '文件不能为空', trigger: 'change' }]
      },
      currentFileData: {
        filePreviewUrl: '',
        fileDownloadUrl: ''
      },
      list: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity'])
  },
  created() {
    this.getList()
  },
  methods: {
    // 小窗口浏览pdf文件
    handlePreviewFile(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() {
      const status = this.fileList.length > 0 && this.fileList[0].status
      if (status === 'success') {
        this.save()
      }
      if (status === 'ready') {
        this.submitLoading = true
        this.$refs.fileUpload.$refs.fileUpload.submit()
      }
    },

    // 调用保存数据接口
    save() {
      this.$refs.formRef.validate((valide) => {
        if (!valide) return
        // 请求参数
        const params = {
          ...this.dialogData,
          ...this.currentFileData,
          authUserId: this.authUserId
        }

        saveFile(params)
          .then((res) => {
            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()
      })
    },

    // 状态改变
    handleChangeStatus(item) {
      this.listLoading = true
      const params = {
        fileId: item.fileId,
        status: item.status === 1 ? 0 : 1
      }
      changeFileStatus(params)
        .then((res) => {
          this.$message({
            message: res.data,
            duration: 500,
            type: 'success'
          })
          this.getList()
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 显示dialog对话框
    handleShowDialog(type, row) {
      this.dialogTitle = '添加资料包'
      if (type === 'edit') {
        this.dialogTitle = '修改资料包'
        this.setDialogData(row)
      }
      this.dialogVisible = true
    },

    // 设置表单初始值
    setDialogData(row) {
      if (typeof row !== 'object') return
      setTimeout(() => {
        for (const key in this.dialogData) {
          if (Object.hasOwnProperty.call(this.dialogData, key)) {
            this.dialogData[key] = row[key]
          }
        }

        this.resetCurrentFileData(row)

        if (row.filePreviewUrl && row.fileDownloadUrl && row.fileId) {
          this.fileList = [{ name: row.fileName }]
        }
      }, 100)
    },

    // 对话框关闭前的回调
    beforeDialogClose() {
      this.$refs.formRef.resetFields()
      this.$refs.fileUpload.$refs.fileUpload.abort()
      this.fileList = []
      this.dialogData.fileId = ''
      this.submitLoading = false
      this.resetCurrentFileData()
    },

    // 上传文件成功
    handleUploadFileSuccess({ response, file, fileList }) {
      console.log(response)
      this.fileList = fileList
      this.dialogData.fileName = response.fileName
      this.currentFileData.filePreviewUrl = response.previewUrl
      this.currentFileData.fileDownloadUrl = response.downloadUrl
      this.save()
    },

    // 移除文件
    handleRemoveUploadFile({ response, file, fileList }) {
      this.fileList = []
      this.dialogData.fileName = ''
      this.resetCurrentFileData()
    },

    // 文件选择
    handleChooseFileChange({ file, fileList }) {
      this.fileList = fileList
      this.dialogData.fileName = file.name
      this.resetCurrentFileData()
    },

    // 重置选中文件数据
    resetCurrentFileData(row = {}) {
      this.currentFileData.filePreviewUrl = row.filePreviewUrl || ''
      this.currentFileData.fileDownloadUrl = row.fileDownloadUrl || ''
    },

    // 文件上传之前
    beforeUpload(file, fileList) {
      let maxSize = 500
      // 文件过大
      if (file.size > maxSize * 1024 * 1024) {
        this.$message.warning('文件大小超过500MB，请重新选择！')
        return Promise.reject()
      }
      maxSize = 30
      // 直接上传
      if (file.size <= maxSize * 1024 * 1024) return true
      // 用户确认上传
      return this.$confirm(`您上传的文件大于${maxSize}MB，是否继续上传？文件上传过程中请您耐心等待!`, '文件上传提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return Promise.resolve()
        })
        .catch(() => {
          this.$message.info('已取消上传')
          this.submitLoading = false
          return Promise.reject()
        })
    },

    // 表格索引
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table .cell {
  overflow: visible;
}
.el-badge {
  margin: 0 6px;
}
</style>
