<template>
  <div class="customize-field-dialog">
    <el-dialog
      title="自定义属性"
      :visible="true"
      :before-close="handleClose"
    >
      <div class="form-dialog-api-sing">
        <el-form label-width="80px" :model="addAttributeForm" style="margin-right: 20px;">

          <el-row v-for="(item, index) in addAttributeForm.attributes" :key="index" :gutter="10">
            <el-col :span="12">
              <el-form-item label="键">
                <el-input v-model="item.key" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="值">
                <el-input v-model="item.value" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cleanSingAttribute">清空属性</el-button>
        <el-button @click="addAttribute">新增属性</el-button>
        <el-button @click="recommendAttribute">推荐属性</el-button>
        <el-button type="primary" @click="submitAddSingAttribute">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CustomizeField',
  props: {
    customizeField: {
      type: Object,
      require: false,
      default: () => {}
    }
  },
  data() {
    return {
      addAttributeForm: {
        attributes: [
          { key: '', value: '' }
        ]
      },
      submitApiSignFormLoading: false,
      apiSingParamContent: null
    }
  },
  watch: {
    customizeField: {
      immediate: true,
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.addAttributeForm.attributes = []
        for (var key in newVal) {
          this.addAttributeForm.attributes.push({ key, value: newVal[key] })
        }

        if (this.addAttributeForm.attributes.length <= 0) {
          this.addAttributeForm.attributes.push({ key: '', value: '' })
        }
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    recommendAttribute() {
      const attr = {
        'fontColor': '',
        'level': ''
      }
      for (var key in attr) {
        this.addAttributeForm.attributes.push({ key, value: attr[key] })
      }
    },
    cleanSingAttribute() {
      this.addAttributeForm.attributes = [{ key: '', value: '' }]
    },
    submitAddSingAttribute() {
      const attributes = this.addAttributeForm.attributes
      const resultModel = {}
      for (let index = 0; index < attributes.length; index++) {
        const attribute = attributes[index]
        if (!attribute.key || !attribute.value) {
          continue
        }
        resultModel[attribute.key] = attribute.value
      }
      this.$emit('submit', resultModel)
    },

    addAttribute() {
      this.addAttributeForm.attributes.push({ key: '', value: '' })
    }
  }
}
</script>

<style scoped lang="scss">
.sgin-content {
  background: rgb(243, 240, 240);
  padding: 20px;
}
</style>
