<template>
  <div>
    <template v-if="ifHasData">
      <template v-if="item.openAdd">
        <div class="suite-item" v-for="(form, index) in faNode[nodeKey]" :key="index">
          <mg-detail v-if="item.ifDetail || disabled" :config="options" :form="form" />
          <mg-form v-else :config="options" :form="form" :ref="formatRef(index)" label-position="top" />
          <template v-if="!item.ifDetail && !disabled">
            <span v-if="faNode[nodeKey].length > 1" class="suite-item-remove" @click="removeItem(index)"><i class="suite-item-add-icon el-icon-minus"></i></span>
            <span v-if="index === faNode[nodeKey].length - 1" class="suite-item-add" @click="addItem"><i class="suite-item-add-icon el-icon-plus"></i></span>
          </template>
        </div>
      </template>
      <template v-else>
        <mg-detail v-if="item.ifDetail || disabled" :config="options" :form="faNode[nodeKey]" ref="detail" label-position="top" />
        <mg-form v-else :config="options" :form="faNode[nodeKey]" ref="singleForm" label-position="top" />
      </template>
    </template>
    <div v-else class="placeholder">{{ placeholder }}</div>
  </div>
</template>

<script>
import { getSuiteCompDetail } from '../api/suite.js'
let uuid = 0
export default {
  name: "mgSuite",
  props: {
    item: {
      type: Object,
      required: true
    },
    faNode: {
      type: Object,
      required: true
    },
    nodeKey: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: 'input'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [], // 单个组件套内部元素的数组
      formsList: {}, // 存储form对应的ref的值
    }
  },
  computed: {
    placeholder() {
      return '暂无相关数据'
    },
    ifHasData() {
      if (this.faNode[this.nodeKey] instanceof Array) {
        if (this.faNode[this.nodeKey].length > 0) {
          if (this.item.ifDetail || this.disabled) {
            for (var key in this.faNode[this.nodeKey][0]) {
              return true
            }
            return false
          }
          return true
        }
        return false
      } else if(this.faNode[this.nodeKey] instanceof Object) {
        if (this.item.ifDetail || this.disabled) {
          for (var key in this.faNode[this.nodeKey]) {
            return true
          }
          return false
        }
        return true
      } else {
        return false
      }
    }
  },
  watch: {
    item: {
      handler(item) {
        if (item.ifDetail) {
          // 详情模式，只能有一条数据，传递对象
          this.$set(this.faNode, this.nodeKey, {})
        } else {
          if (item.openAdd) {
            // 开启系列新增，传递数组
            this.$set(this.faNode, this.nodeKey, [{}])
          } else {
            // 关闭系列新增，传递对象
            this.$set(this.faNode, this.nodeKey, {})
          }
        }
        
      },
      deep: true
    }
  },
  created() {
    this.getSuiteComponentDetail()
    this.createdFields()
  },
  mounted() {},
  methods: {
    createdFields() {
        // 有系列新增要用数组形式
      if (this.item.openAdd) {
        if (!this.faNode[this.nodeKey]) {
          this.$set(this.faNode, this.nodeKey, [{}])
        } else {
          try {
            this.$set(this.faNode, this.nodeKey, JSON.parse(this.faNode[this.nodeKey]))
          } catch(e) {}
        }
      } else {
      // 没有系列新增时要用对象形式
        if (!this.faNode[this.nodeKey]) {
          this.$set(this.faNode, this.nodeKey, {})
        } else {
          try {
            this.$set(this.faNode, this.nodeKey, JSON.parse(this.faNode[this.nodeKey]))
          } catch(e) {}
        }
      }
    },
    getSuiteComponentDetail() {
      getSuiteCompDetail({ id: this.type.substring(2) }).then(res => {
        const attributes = JSON.parse(res.data.attributes)
        attributes.fields.map(config => {
          let temp = this.$setForm.setOption(config, {})
          this.options.push(temp)
        })
      })
    },
    addItem() {
      this.faNode[this.nodeKey].push({})
    },
    removeItem(index) {
      this.faNode[this.nodeKey].splice(index, 1)
    },
    // 绑定唯一ref
    formatRef(index) {
      ++uuid
      let key = +new Date()
      const ref = 'suiteForm' + key + uuid
      this.formsList[index] = ref
      return ref
    },
    // 对全部表单循环进行校验
    validate() {
      let self = this
      return new Promise((resolve, reject) => {
        if (!this.ifHasData) {
          resolve()
        } else if (this.item.ifDetail || this.disabled) {
          resolve()
        } else {
          let success = 0 // 表单验证成功的个数
          // 这里循环是组件套的系列新增
          for (let i in self.faNode[self.nodeKey]) {
            // 这里ref绑定的form是mgForm
            self.$refs[self.formsList[i]][0].validate(true)
            .then(form => {
              ++success
              if (i*1 === self.faNode[self.nodeKey].length - 1 && success === self.faNode[self.nodeKey].length) {
                resolve(form)
              }
            })
            .catch(errorMessage => {
              reject(errorMessage)
            })
          }
        }
      })
    }
  }
}
</script>

<style lang='less' scoped>
.suite-item {
  position: relative;

  & + & {
    padding-top: 15px;
    border-top: 1px dashed #dfe4ed;
  }

  & > .suite-item-add,
  & > .suite-item-remove {
    position: absolute;
    right: 0;
    width: 18px;
    height: 18px;
    line-height: 16px;
    text-align: center;
    border-radius: 50%;
    font-size: 12px;
    border: 1px solid;
    cursor: pointer;
  }
}
.suite-item-remove {
  color: #f56c6c;
  top: 30%;
  &:hover {
    background: #f56c6c;
    color: #fff;
  }
}
.suite-item-add {
  color: #67c23a;
  top: 60%;
  &:hover {
    background: #67c23a;
    color: #fff;
  }
}
.placeholder {
  color: #c0c4cc;
}
</style>