<template>
  <el-dialog
    title="编辑名称"
    :visible.sync="dialogVisible"
    width="80%"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose">
    <ElementForm
      ref="form"
      :form="form"
    />
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
import { fields } from './fields'
export default {
  name: 'editItem',
  props: {
    visible: Boolean,
    value: [Object, String],
    defaultValue: Object
  },
  watch: {
    visible (vl) { this.dialogVisible = vl },
    dialogVisible (vl) { this.$emit('update:visible', vl) },
    // value (vl) { this.form = vl },
    // 'form.value': {
    //   handler (vl) {
    //     this.$emit('update:value', vl)
    //   }
    // },
    defaultValue: {
      handler (vl) {
        this.form.map(v => {
          if (v.type === 'Select') {
            v.value = `${vl[v.attr]}`
          } else if (v.type === 'UploadTencent') {
            if (vl[v.attr]) {
              const img = vl[v.attr].split(',')
              // console.log(img)
              v.value = img && img.map(v => { return { url: v } })
              // debugger
            }
          } else {
            v.value = vl[v.attr]
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  data () {
    return {
      form: this.$_.cloneDeepWith(fields),
      dialogVisible: this.visible
    }
  },
  methods: {
    handleClose () {
      this.dialogVisible = false
    },
    submit () {
      const state = this.$refs.form.validateForm()
      const obj = this.$_.cloneDeepWith((this.defaultValue))
      if (state) {
        let img = []
        this.form.map(v => {
          img = []
          if (v.type === 'Select') {
            obj[v.attr] = `${v.value}`
          } else if (v.type === 'UploadTencent') {
            if (v.value && v.value.length > 0) {
              v.value.map(v => img.push(v.url))
            }
            obj[v.attr] = img.toString()
          } else {
            obj[v.attr] = v.value
          }
        })
        console.log(obj)
        // debugger
        this.$emit('success', obj)
        this.handleClose()
      }
    }
  }
}
</script>

<style scoped>

</style>
