<template>
  <div class="container">
    <el-card shadow="always">
      <el-input
        v-model="filterText"
        clearable
        size="small"
        placeholder="输入关键字进行过滤"
      />
      <el-tree
        ref="tree"
        :indent="10"
        style="margin-top: 8px;"
        :expand-on-click-node="false"
        class="filter-tree"
        :data="types"
        :props="{
          label: 'name',
        }"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="treeClick"
      />
    </el-card>

    <card-container>
      <vxe-toolbar>
        <template #buttons>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAdd = true">新增</el-button>
          <el-button icon="el-icon-search" type="primary" plain size="small" @click="getList">搜索</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px;"
        :loading="loading"
        keep-source
        show-overflow
        :column-config="{ resizable: true }"
        :edit-rules="validRules"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true, autoClear: false }"
        :data="tableData"
      >
        <vxe-column type="seq" width="64" align="center" />
        <vxe-column field="document_menu.name" title="所属栏目" width="140" align="center" />
        <vxe-column field="name" title="名称" width="160" align="center" :edit-render="{ name: 'input', attrs: { type: 'text' } }" />
        <vxe-column field="file.original_name" title="文件" min-width="180" header-align="center" align="left" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-upload v-model="row.file" name-field="original_name" progress-text="{percent}%" :more-config="{ maxCount: 1, layout: 'horizontal' }" :limit-size="uploadSize / 1024 / 1024" :show-button-text="false" :upload-method="({file}) => uploadMethod(file, row)"></vxe-upload>
          </template>
        </vxe-column>
        <vxe-column field="operate" title="操作" min-width="240">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)">保存</el-button>
              <el-button size="small" type="primary" plain @click="cancelRowEvent(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="small" type="primary" icon="el-icon-search" @click="preview(row)">预览</el-button>
              <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="destroyRowEvent(row)">删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;"
        :current-page.sync="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size.sync="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="e => {
          select.page_size = e;
          select.page = 1;
          getList();
        }"
        @current-change="e => {
          select.page = e;
          getList();
        }"
      />
    </card-container>

    <AddDocument :is-show.sync="isShowAdd" ref="AddDocument" :list="types" @refresh="getList"></AddDocument>
  </div>
</template>

<script>
import AddDocument from './components/AddDocument.vue'
import { menuIndex, index, destroy, save } from '@/api/document'
import { deepCopy } from "@/utils";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { uploadSize } from "@/settings";
import { formatFileSize } from "@/utils"
export default {
  components: {
    AddDocument
  },
  data() {
    return {
      uploadSize,
      filterText: '',
      isShowAdd: false,
      loading: false,
      validRules: {
      },
      tableData: [],
      total: 0,
      types: [],
      select: {
        show_relation: ['file', 'document_menu'],
        page: 1,
        page_size: 20,
        'filter[0][key]': 'document_menu_id',
        'filter[0][op]': 'eq',
        'filter[0][value]': ''
      },
      form: {
        id: '',
        document_menu_id: '',
        name: '',
        file_id: '',
        update_children_ids: '',
        myindex: ''
      },
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getTypes()
    this.getList()
  },
  methods: {
    formatFileSize,
    preview(row) {
      this.$bus.$emit('online-file', row.file?.url)
    },
    treeClick(data) {
      this.select['filter[0][value]'] = data.id
      this.select.page = 1
      this.getList()
    },

    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    uploadMethod(file, row) {
      const formData = new FormData()
      formData.append('file', file)
      window.$_uploading = true
      return axios.post(process.env.VUE_APP_UPLOAD_API, formData, {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        }
      }).then((response) => {
        window.$_uploading = false
        if (response.status === 200 && !response.data.code) {
          row.file_id = response.data.data.id
          row.file = response.data.data
        } else {
          this.$message.error("上传失败")
        }
      }).catch(err => {
        window.$_uploading = false
      })
    },

    async getList() {
      try {
        this.loading = true
        const res = await index(this.select)
        this.tableData = res.data
        this.total = res.total
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },
    async getTypes() {
      try {
        const res = await menuIndex()
        this.types = res
      } catch (err) {
        console.error(err)
      }
    },
    editRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },
    async saveRowEvent(row) {
      if (window.$_uploading) {
        this.$message.warning("文件正在上传中")
        return
      }
      try {
        const errMap = await this.$refs['table'].validate()
        if (errMap) {
          throw new Error(errMap)
        }
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        const form = deepCopy(this.form)
        for (const key in form) {
          form[key] = row[key]
        }
        this.loading = true
        await save(form)
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        this.loading = true
        if (row.id) {
          await destroy({
            id: row.id
          })
          await this.getList()
        } else {
          console.log(row)
          this.tableData.splice(this.tableData.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY), 1)
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  justify-content: space-between;

  & > *:nth-child(1) {
    flex-basis: 20%;
  }
  & > *:nth-child(2) {
    flex-basis: 78%;
    margin-left: 10px;
  }
}

@media (max-width: 992px) {
  .container {
    display: initial;

    & > *:nth-child(2) {
      margin-top: 10px;
      margin-left: 0;
    }
  }
}
</style>
