<script setup name='documentation'>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { addDoc, addGroup, delDoc, delGroup, docGroup, docList } from '@/http/apis/recordManage/documentation'
import { downloadFileUrl, fileFormatVerification, handleFileError, handleFileSuccess, handleFilePreview, fileTypes, fileDesc } from '@/utils/uploadAction'
import store from '@/store'

const { proxy } = getCurrentInstance(),
  uploadUrl = store.dictStore.uploadUrl,
  activeName = ref('1'),
  docGroupList = ref([]),
  getDocGroup = async () => {
    const res = await docGroup()
    docGroupList.value = res.data
    if (docGroupList.value && docGroupList.value.length) activeName.value = docGroupList.value[0].id
    getTableData()
  },
  tableListRef = ref(),
  column = reactive([
    {
      label: '序号',
      type: 'index',
      width: '80'
    },
    {
      label: '文档名称',
      key: 'fileName',
      prop: 'fileName',
      minWidth: '250',
      showOverflowTooltip: true
    },
    {
      label: '上传时间',
      key: 'createOn',
      prop: 'createOn',
      showOverflowTooltip: true,
      width: '180'
    },
    {
      label: '上传者',
      key: 'createBy',
      prop: 'createBy',
      width: '160'
    },
    {
      label: '文档大小(KB)',
      key: 'size',
      prop: 'size',
      width: '120'
    },
    {
      label: '操作',
      slot: 'action',
      width: '160',
      fixed: 'right'
    }
  ]),
  total = ref(0),
  tableData = ref([]),
  // 获取项目列表
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const params = {
      ...pageParams,
      groupId: activeName.value
    }
    const res = await docList(params)
    tableData.value = res.data.records
    total.value = res.data.total
  },
  groupChange = () => {
    tableListRef.value.pageSize = 1
    getTableData()
  },
  down = async (row) => {
    const url = await downloadFileUrl(row.fileId)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.download = row.fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  },
  del = (id) => {
    proxy.$messageBox
      .confirm('确定要删除该项吗?', '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await delDoc(id)
        proxy.$message.success('删除成功！')
        await getTableData()
      })
  },
  groupRemove = async (val) => {
    await delGroup(val)
    proxy.$message.success('删除成功！')
    await getDocGroup()
  },
  // 上传文档/添加分组
  visible = ref(false),
  type = ref(1),
  formRef = ref(),
  formData = ref({
    uploadFile: [],
    name: ''
  }),
  rules = {
    uploadFile: [{ required: true, message: '请上传文件' }],
    name: [{ required: true, message: '请输入分组名称' }]
  },
  showDialog = (val) => {
    type.value = val
    visible.value = true
  },
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        console.log(formData.value)
        const res = type.value === 1 ? await addGroup({ name: formData.value.name }) : await addDoc({
          fileId: formData.value.uploadFile[0].response.data.id,
          groupId: activeName.value
        })
        console.log(res)
        proxy.$message.success('提交成功！')
        if (type.value === 1) {
          await getDocGroup()
        } else {
          await getTableData()
        }
        visible.value = false
        formData.value = {
          uploadFile: [],
          name: ''
        }
      }
    })
  }

onMounted(async () => {
  await getDocGroup()
})
</script>
<template>
  <el-row>
    <el-card class="w-full mt-8 tab-card">
      <template #header>
        <div class="flex justify-between items-center tab-type-card">
          <el-tabs
            v-model="activeName"
            type="card"
            closable
            @tab-change="groupChange"
            @tab-remove="groupRemove"
          >
            <el-tab-pane
              v-for="i in docGroupList"
              :key="i.id"
              :label="i.name"
              :name="i.id"
            />
          </el-tabs>
          <div>
            <el-button
              type="primary"
              size="small"
              plain
              @click="showDialog(2)"
            >
              上传文档
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="plus"
              @click="showDialog(1)"
            >
              新增分类
            </el-button>
          </div>
        </div>
      </template>
      <table-list
        ref="tableListRef"
        :column="column"
        :data="tableData"
        :total="total"
        @get-table-data="getTableData"
      >
        <template #action="{ scope }">
          <a class="text-primary" @click="down(scope.row)">下载</a>
          <a class="text-danger" @click="del(scope.row.id)">删除</a>
        </template>
      </table-list>
    </el-card>
  </el-row>
  <el-dialog
    v-model="visible"
    :title="type===1?'新增分类':'上传文档'"
    width="600px"
    destroy-on-close
    @close="visible=false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90px"
      label-suffix=":"
    >
      <el-form-item v-if="type===1" label="分组名称" prop="name">
        <el-input
          v-model="formData.name"
          maxlength="50"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item v-if="type===2" label="文档" prop="uploadFile">
        <el-upload
          v-model:file-list="formData.uploadFile"
          class="w-full"
          :action="uploadUrl"
          :on-success="res => handleFileSuccess(res, formData.uploadFile)"
          :on-error="handleFileError"
          :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
          :accept="fileTypes.map(i=>`.${i}`).join(',')"
          :limit="1"
          :on-preview="handleFilePreview"
        >
          <el-button type="primary" class="mr-4">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持{{ fileDesc }}文件</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit(formRef)">
        提交
      </el-button>
      <el-button @click="visible = false">
        关闭
      </el-button>
    </template>
  </el-dialog>

</template>
<style lang='less' scoped>
.tab-type-card {
  margin-right: -16px;
  margin-left: -16px;
}

</style>

