<template>
  <div>
    <!--新建文件/文件夹Dialog-->
    <el-dialog :title="inputParams.dialogTitle" :visible.sync="addFileDialogVisible" class="file-create-dialog">
      <div v-loading="addFileDialogLoading">
        <el-form ref="addFileValidateForm" label-width="100px" :model="currentAddFileFormData" style="min-height:110px;">
          <el-form-item label="上级目录：" prop="parentName">
            <el-input auto-complete="off" disabled v-model="currentAddFileFormData.parentName"></el-input>
          </el-form-item>
          <el-form-item label="文件名称：" prop="name" :verify="['NotNull','Regex=^[a-zA-Z0-9_\\.\\-\\/]+$|只能是数字/字母/下划线/破折号和圆点','Length<150']" v-if="inputParams.fileOrDir=='File'">
            <el-input auto-complete="off" v-model="currentAddFileFormData.name"></el-input>
          </el-form-item>
          <el-form-item label="目录名称：" prop="name" :verify="['NotNull','Regex=^[a-zA-Z0-9_\\.\\-\\/]+$|只能是数字/字母/下划线/破折号和圆点','Length<150']" v-if="inputParams.fileOrDir=='Dir'">
            <el-input auto-complete="off" v-model="currentAddFileFormData.name"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doFileOrDirAdd" :loading="okaddFileBtnLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  data() {
    return {
      currentAddFileFormData: {
        parentName: '',
        name: ''
      }, // 当前新建文件临时数据
      emptyFormData: {},
      okaddFileBtnLoading: false,
      addFileDialogVisible: false,
      addFileDialogLoading: false,

      inputParams: {
        siteID: '',
        platformID: '',
        addOrRename: 'add',
        fileOrDir: 'File',
        dialogTitle: '新建文件',
        parentName: ''
      },
      allowFileType: []
    }
  },
  methods: {
    // 初始化Dialog
    initDialog(params) {
      this.addFileDialogVisible = true
      this.okaddFileBtnLoading = false
      this.clearForm()
      if (!util.isEmptyObject(params)) {
        Object.assign(this.inputParams, params)
        this.currentAddFileFormData.parentName = params.parentName
        if (this.inputParams.addOrRename === 'rename') {
          this.currentAddFileFormData.name = this.inputParams.oldName
        }
      }
      this.inputParams.fileOrDir === 'File' && !this.allowFileType.length && this.loadAllowFileType()
    },

    // 重置表单
    clearForm() {
      Object.assign(this.currentAddFileFormData, this.emptyFormData)
    },

    // 加载允许新建的文件类型
    async loadAllowFileType() {
      let res = await axios.get('/ui/core/file/initallowtypes')
      let data = res.data
      if (data.status === 1) {
        this.allowFileType = data.data.allowedtypes.split(',')
      }
      this.addFileDialogLoading = false
    },

    // 验证新增文件或目录输入是否合法
    verifyFileAddInput() {
      if (this.inputParams.fileOrDir === 'File') {
        if (!this.currentAddFileFormData.name) {
          this.Dialog('请输入文件名 ！')
          return false
        }
        let index = this.currentAddFileFormData.name.lastIndexOf('.')
        if (index === -1 || this.currentAddFileFormData.name.endsWith('.')) {
          this.Dialog('请输入文件后缀名 ！')
          return false
        }
        let ext = this.currentAddFileFormData.name.substring(index + 1)
        let flag = false
        for (var types of this.allowFileType) {
          if (ext.toLowerCase() === types.toLowerCase()) {
            flag = true
            break
          }
        }
        if (!flag) {
          this.Dialog('不支持后缀名为 ' + ext + ' 的文件')
          return false
        }
      } else if (this.inputParams.fileOrDir === 'Dir') {
        if (!this.currentAddFileFormData.name) {
          this.Dialog('请输入目录名 ！')
          return false
        }
      }
      return true
    },

    // 确认新建文件或目录
    async doFileOrDirAdd() {
      try {
        await util.validateForm(this.$refs.addFileValidateForm)
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      if (!this.verifyFileAddInput()) {
        return
      }

      let param = {
        name: this.currentAddFileFormData.name,
        path: this.currentAddFileFormData.parentName,
        type: this.inputParams.fileOrDir,
        siteID: this.inputParams.siteID,
        platformID: this.inputParams.platformID
      }
      if (this.inputParams.addOrRename === 'add') {
        this.okaddFileBtnLoading = true
        let res = await axios.post(`/ui/core/file`, param)
        this.okaddFileBtnLoading = false
        let data = res.data
        if (data.status === 1) {
          this.addFileDialogVisible = false
          this.MsgPop(data.message || '操作成功 ！', 'success')
          this.$emit('success')
        } else {
          this.Dialog(data.message)
        }
      } else if (this.inputParams.addOrRename === 'rename') {
        if (this.inputParams.oldName === param.name.trim()) {
          this.addFileDialogVisible = false
          return
        }
        this.okaddFileBtnLoading = true
        Object.assign(param, { oldName: this.inputParams.oldName })
        let res = await axios.patch(`/ui/core/file/${this.inputParams.oldName}/rename/${param.name}`, param)
        let data = res.data
        if (data.status === 0) {
          this.Dialog(data.message)
        } else {
          this.MsgPop(data.message || '操作成功 ！', 'success')
          this.addFileDialogVisible = false
          this.$emit('success')
        }
      }
      this.okaddFileBtnLoading = false
    },

    // 消息Dialog封装
    Dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },

    // 消息显示封装
    MsgPop(msg, type) {
      if (!type) {
        this.$message(msg)
        return
      }
      this.$message({
        message: msg,
        type: type
      })
    }
  },
  computed: {},
  created() {
    Object.assign(this.emptyFormData, this.currentAddFileFormData)
  },
  props: {
    params: {
      type: Object,
      default: function() {
        return {
          addOrRename: 'add',
          fileOrDir: 'file',
          dialogTitle: '新建文件'
        }
      }
    }
  },
  watch: {}
}
</script>
<style>
.file-create-dialog .el-dialog {
  width: 500px;
}

@media (max-width: 480px) {
  .file-create-dialog .el-dialog {
    width: 96%;
  }
}
</style>
