<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-cascader
        v-model="listQuery.fileModule"
        :options="modules"
        class="filter-item"
        placeholder="所属模块"
        style="margin-rigth: 15px"
        clearable
        @change="getList"
      />
      <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
      <el-button
        v-if="userIdentity === 1"
        icon="el-icon-edit"
        type="primary"
        @click="dialogVisible = true"
      >添加</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
        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="所属模块" align="center" prop="fileModuleType" />
        <el-table-column label="创建时间" width="240px" align="center">
          <template slot-scope="{ row }">
            {{ row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button
              v-if="userIdentity === 1"
              type="primary"
              size="mini"
              style="margin-right:5px"
              icon="el-icon-edit"
              @click="handleEditFile(row)"
            >编辑</el-button>

            <el-button
              type="success"
              size="mini"
              style="margin-right:5px"
              icon="el-icon-document"
              @click="handlePreview(row)"
            >查看</el-button>

            <el-button
              v-if="userIdentity === 1"
              type="danger"
              size="mini"
              style="margin-right:5px"
              icon="el-icon-s-check"
              @click="handleRemove(row)"
            >删除</el-button>

          </template>
        </el-table-column>
      </el-table-column></el-table>
    <!-- 表格区域END -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList(listQuery)" />

    <!-- 文档编辑dialog -->
    <el-dialog
      title="添加文档"
      :visible="dialogVisible"
      width="30%"
      @close="dialogClose"
    >

      <el-form ref="dialogForm" :model="dialogFormData" label-width="86px" :rules="rules">
        <el-form-item label="标题:" prop="fileTitle">
          <el-input v-model="dialogFormData.fileTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="文档路径:" prop="fileUrl">
          <file-upload ref="fileUpload" :file-list="uploadFileList" accept-type=".doc,.docx" @change="fileUploadChange" />
          <el-input v-show="false" v-model="dialogFormData.fileUrl" />
        </el-form-item>
        <el-form-item label="所属模块:" prop="fileModule">
          <el-cascader
            v-if="dialogVisible"
            v-model="dialogFormData.fileModule"
            :options="modules"
            placeholder="所属模块"
            clearable
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="!saveBtnClickable" :loading="requestLoading" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 文档编辑dialog END -->
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import openWindow from '@/utils/open-window'
import { formatDate } from '@/utils'
import { mapGetters } from 'vuex'
import { fetchCourseList, saveCourse, removeCourse } from '@/api/helper'
import { getToutesTree, getModuleType } from '@/utils/formatRoutesToModule'
import { debounce } from '@/utils/tools'
export default {
  components: { Pagination, FileUpload },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },

  data() {
    return {
      listLoading: false,
      dialogVisible: false,
      requestLoading: false,
      total: 0,
      listQuery: {
        fileType: 2, // 文件类型：1视频，2文档
        fileTitle: '', // 文件标题
        fileModule: [], // 文件模块：1品牌授权-授权列表，2机构管理-机构列表
        pageNum: 1,
        pageSize: 10
      },
      modules: [],
      list: [],
      uploadFileList: [],
      dialogFormData: {},
      rules: {
        fileTitle: [{
          required: true,
          message: '请输入标题', trigger: ['change', 'blur']
        }],
        fileUrl: [
          {
            required: true,
            message: '请选择文件', trigger: 'change'
          }
        ],
        fileModule: [{
          required: true,
          message: '请选择所属模块', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'proxyInfo', 'routes']),
    saveBtnClickable() {
      return this.uploadFileList.length > 0
    }
  },
  created() {
    this.dialogFormData = this.resetDialogFormData()
    this.modules = getToutesTree(this.routes)
    this.getList()
  },
  methods: {
    // 初始化dialog formdata
    resetDialogFormData() {
      return {
        fileTitle: '',
        fileUrl: '',
        fileId: '',
        fileName: '',
        fileType: 2,
        fileModule: []
      }
    },

    // 上传文件
    submitUpload() {
      if (this.userIdentity !== 1) return
      this.$refs.dialogForm.validate(valid => {
        console.log(valid)
        if (!valid) return
        this.requestLoading = true // 上传文件 保存 loading

        const uploadFile = this.uploadFileList[0]
        // 文件如果已上传 直接保存
        if (uploadFile && uploadFile.status === 'success') {
          this.handleSave()
        } else {
          // 上传文件
          this.$refs.fileUpload.submit()
        }
        console.log(this.uploadFileList)
      })
    },
    // 监听上传文件的状态变化
    async fileUploadChange(fileList) {
      this.uploadFileList = fileList
      try {
        await this.handleFileUploadStatus(fileList)
        this.handleSave.apply(this)
      } catch (error) {
        console.log(error)
      }
    },
    // 保存 TODO
    handleSave: debounce(function() {
      if (this.userIdentity !== 1) return
      const params = {
        fileId: this.dialogFormData.fileId || '',
        fileTitle: this.dialogFormData.fileTitle,
        fileName: this.dialogFormData.fileName,
        ossName: this.dialogFormData.fileUrl,
        fileType: this.dialogFormData.fileType,
        fileModule: this.dialogFormData.fileModule.join('-')
      }
      saveCourse(params).then(res => {
        this.$message.success(res.data)
        this.dialogVisible = false
        this.getList()
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.requestLoading = false
      })
    }, 200),

    // 处理文件上传状态
    handleFileUploadStatus(fileList) {
      // 文件列表为空
      if (fileList.length <= 0) {
        this.dialogFormData.fileUrl = ''
        return Promise.reject('faild')
      }
      // 取第一个文件
      const { response, status } = fileList[0]
      // 文件已选择但未上传
      if (status === 'ready') {
        this.dialogFormData.fileUrl = status
        return Promise.reject('faild')
      }
      // 文件已上传
      if (status === 'success') {
        this.dialogFormData.fileUrl = response.downloadUrl
        this.dialogFormData.fileName = response.fileName
        return Promise.resolve('success')
      }
      console.log(response)
    },

    // 数据回显 修改
    handleEditFile(row) {
      if (this.userIdentity !== 1) return
      const fileModule = row.fileModule.split('-')
      const i = parseInt(fileModule[0])
      const j = parseInt(fileModule[1])
      // dialog 表单数据
      this.dialogFormData.fileTitle = row.fileTitle
      this.dialogFormData.fileUrl = row.ossName
      this.dialogFormData.fileId = row.fileId
      this.dialogFormData.fileName = row.fileName
      this.dialogFormData.fileType = 2
      this.dialogFormData.fileModule = [i, j]
      // 文件回显列表
      this.uploadFileList = [{ url: row.fileUrl, name: row.fileName }]
      this.dialogVisible = true
    },

    // 获取列表数据
    getList() {
      this.listLoading = true
      const params = {
        ...this.listQuery,
        authUserId: this.authUserId,
        fileModule: this.listQuery.fileModule.join('-')
      }
      fetchCourseList(params)
        .then(res => {
          if (res.code !== 0) return
          this.list = this.formatFileModuleType(res.data.list)
          this.total = res.data.total
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 删除
    async handleRemove(row) {
      if (this.userIdentity !== 1) return
      const text = await this.$confirm('确认删除该帮助文档吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      removeCourse({ fileId: row.fileId })
        .then(res => {
          if (res.code !== 0) return
          this.$message.success(res.data)
          this.getList(this.listQuery)
        })
    },

    // 预览
    handlePreview(row) {
      const url = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(row.fileUrl)}`
      openWindow(url, '', `${row.fileModuleType}-教程`, 800, 460)
    },

    // 关闭添加对话框
    dialogClose() {
      this.uploadFileList = []
      this.$refs.fileUpload.clearAllFiles()
      this.$refs.dialogForm.resetFields()

      this.dialogFormData = this.resetDialogFormData()
      this.dialogVisible = false
    },
    // 获取模块文本
    formatFileModuleType(list) {
      return list.filter(item => {
        item.fileModuleType = getModuleType(item.fileModule)
        return item.fileModuleType !== ''
      })
    },
    // 表格索引
    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;
}

.el-cascader{
&.filter-item{
margin: 0 15px 10px;
}

}

</style>
