<template>
  <ui-form :model="formData" :rules="formRules" ref="form" label-width="80px">
    <ui-form-item prop="name" label="文件名">
      <ui-textbox v-model="formData.name" placeholder="请输入文件名称"></ui-textbox>
    </ui-form-item>
    <ui-toolbar slot="toolbar" align="right">
      <ui-toolbar-item>
        <ui-button>取消</ui-button>
      </ui-toolbar-item>
      <ui-toolbar-item>
        <ui-button type="primary" :click="handleConfirmClick">确定</ui-button>
      </ui-toolbar-item>
    </ui-toolbar>
  </ui-form>
</template>
<script>
export default {
  name: 'BiDiskManageRename',
  props: {
    type: {
      type: String,
      validator(value) {
        return ['file', 'folder'].includes(value)
      }
    },
    id: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    renameDiskFileNameMethod: {
      type: Function
    },
    renameDiskFolderNameMethod: {
      type: Function
    }
  },
  data() {
    return {
      formData: {
        name: ''
      }
    }
  },
  computed: {
    formRules() {
      return {
        name: [{
          required: true,
          message: '文件名称不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    if (this.name) {
      this.formData.name = this.name
    }
  },
  methods: {
    handleConfirmClick() {
      return this.$refs.form.validate().then(() => {
        const actionFn = this.type === 'folder' ? this.renameDiskFolderNameMethod : this.renameDiskFileNameMethod
        const saveData = Object.assign({}, this.formData)
        const name = saveData.name
        delete saveData.name
        if (this.type === 'folder') {
          saveData.newFilePath = name
        } else {
          saveData.newFileName = name
        }
        return actionFn(Object.assign({
          id: this.id
        }, saveData)).then(() => {
          this.$success('操作成功')
          this.$emit('success')
        })
      })
    }
  }
}
</script>
