<template>
  <el-drawer title="自定义组件套设置" size="80%" destroy-on-close append-to-body :visible="drawerVisible" :wrapperClosable="false" @close="handleClose">
    <div class="header m15">
      <el-input class="header-title" v-model="editData.name" placeholder="请输入组件名称" />
      <div class="header-btn">
        <el-button round @click="handleCancel">取消</el-button>
        <el-button round type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>
    <AsyncForm ref="asyncForm" :form="editData" from-edit="1" :flowConfig="flowConfig" />
  </el-drawer>
</template>

<script>
import { addSuiteComp, updateSuiteComp } from '../../api/suite.js'

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    formData: {
      type: Object,
      required: true
    }
  },
  components: {
    AsyncForm: () => import('../asyncForm.vue')
  },
  data() {
    return {
      editData: {},
      flowConfig: [],
      drawerVisible: false,
      form: {}
    }
  },
  computed: {
    isModify() {
      return !!this.formData.name
    }
  },
  watch: {
    visible(bool) {
      this.drawerVisible = bool
      if (bool) {
        this.createFields()
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    createFields() {
      if (this.isModify) {
        this.editData = { ...this.formData }
      } else {
        this.editData = {}
      }
    },
    handleClose() {
      this.drawerVisible = false
      this.$emit('update:visible', false)
    },
    handleCancel() {
      this.handleClose()
    },
    handleSubmit() {
      this.editData.attributes = JSON.stringify(
        this.$refs.asyncForm.AssembleFormData()
      )
      this.editData.label = this.editData.name
      if (this.isModify) {
        updateSuiteComp(this.editData).then(() => {
          this.$message.success('修改成功')
          this.handleClose()
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
      } else {
        addSuiteComp(this.editData).then(() => {
          this.$message.success('新增成功')
          this.handleClose()
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
      }
    }
  }
}
</script>

<style lang='less'>
.header {
  position: relative;

  &-title {
    width: 80%;
  }

  &-btn {
    position: absolute;
    right: 20px;
    top: 0;
  }
}
</style>