<template>
  <div>
    <vxe-modal
      :z-index="zIndex"
      :value="isShow"
      show-footer
      title="公共文件柜"
      show-confirm-button
      transfer
      show-zoom
      resize
      :width="defaultModalSize.width"
      :height="defaultModalSize.height"
      :fullscreen="$store.getters.device === 'mobile'"
      esc-closable
      @input="e => $emit('update:isShow',e)"
    >
      <el-form ref="elForm" :model="form" :rules="rules" label-position="top" label-width="100">
        <el-form-item label="所属栏目" prop="document_menu_id" required>
          <Treeselect
            v-model="form.document_menu_id"
            :options="list"
            :multiple="false"
            no-children-text="无子菜单"
            :normalizer="node => ({
              id: node.id,
              label: node.name,
              children: node.children,
              isDefaultExpanded: true
            })"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="文件" prop="file_id">
          <el-upload
            :action="action"
            :headers="{
              Authorization: `Bearer ${getToken()}`
            }"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-remove="uploadRemove"
            :on-error="uploadError"
            multiple
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传文件不超过{{ formatFileSize(uploadSize) }}</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="myindex">
          <el-input-number v-model="form.myindex" :controls="false" :precision="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" :loading="loading" @click="submit">确认</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { save } from '@/api/document'
import { PopupManager } from "element-ui/lib/utils/popup";
import {defaultModalSize, uploadSize} from "@/settings"
import { formatFileSize } from "@/utils"
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    isShow: {
      type: Boolean,
      default: false,
      required: true
    },
    users: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uploadSize,
      action: process.env.VUE_APP_UPLOAD_API,
      fileList: [],

      defaultModalSize,
      zIndex: PopupManager.nextZIndex(),
      loading: false,
      form: {
        document_menu_id: '',
        name: '',
        file_id: '',
        update_children_ids: '',
        myindex: ''
      },
      rules: {
        document_menu_id: [
          { required: true, message: '请选择栏目' }
        ],
        name: [
          { required: true, message: '请输入名称' }
        ]
      }
    }
  },
  computed: {

  },
  watch: {
    isShow(newVal) {
      if(newVal) {
        this.zIndex = PopupManager.nextZIndex()
      } else {
        this.fileList = []
      }
    }
  },
  methods: {
    formatFileSize,
    getToken,
    uploadRemove(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isLt = file.size < uploadSize
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过${formatFileSize(uploadSize)}!`)
      } else {
        window.$_uploading = true
      }
      return isLt
    },
    uploadSuccess(response, file, fileList) {
      window.$_uploading = false
      if (response.code) {
        fileList.splice(fileList.indexOf(file), 1)
        this.$message.warning(response.msg)
      }
      this.fileList = fileList
    },
    uploadError() {
      window.$_uploading = false
    },

    submit() {
      if (window.$_uploading) {
        this.$message.warning("文件正在上传中")
        return
      }
      this.$refs['elForm'].validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            await Promise.all(this.fileList.map(i => save({
              ...this.form,
              file_id: i.response?.data?.id
            })))
            await save(this.form)
            this.$message.success('新增成功')
            this.$emit('refresh')
            this.$emit('update:isShow', false)
            this.loading = false
            this.$refs['elForm'].resetFields()
          } catch (err) {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
