<template>
  <el-form v-bind="element.props" label-width="80px" label-position="right" v-loading="requesting" class="lab-form">
    <lab-form-item :element="element" :elements="elements" :index=index :model-data="modelData" />
  </el-form>
</template>

<script>
import LabBase from "../../mixins/LabBase";
import LabRequest from "../../mixins/LabRequest";
import Util from "../../utils/Util";

export default {
  name: "LabForm",
  mixins: [ LabBase,LabRequest],
  provide() {
    return {
      parentElement: this
    }
  },
  created() {
    this.$LabRender.autoFill(this.element, this)
    const { elements } = this.element
    elements.forEach(item => {
      this.$LabRender.autoFill(item, this)
    })
    this.loadSource()
  },
  methods: {
    loadSource(localFilters){
      let sourceRequest = this.findRequest('formSource')
      if (!sourceRequest) {
        sourceRequest = this.findRequest('source')
      }
      if (!sourceRequest) {
        return
      }
      const { props } = this.element
      if (Util.isEmpty(props.rowKey)) {
        return;
      }
      const keyVal = this.modelData[props.rowKey]
      if (Util.isEmpty(keyVal)) {
        return;
      }
      this.addFilter({ field:props.rowKey, op: '=',value:keyVal })
      const bodyArgs = this.getBody(sourceRequest,this.modelData)
      if (!Util.isEmpty(localFilters)) {
        if (Util.isArray(localFilters)) {
          localFilters.forEach(item => this.addFilter(item))
        } else {
          this.addFilter(localFilters)
        }
      }
      this.dispatchRequest('source',this.modelData, bodyArgs)
          .then(res => {
            if (res.code === 200 && !Util.isEmpty(res.data)) {
              const dataProp = sourceRequest.dataProp || 'records'
              this.dataSource = this.$Util.callPropValue(res.data, dataProp)
              if (!Util.isEmpty(this.dataSource)) {
                Util.copyAttr(this.dataSource[0],this.modelData,null,this)
              }
            } else {
              console.info('节点数据源请求:', this.element, res)
            }
            setTimeout(() => {
              this.requesting = false
            }, 100)
          })
    },
  }
}
</script>
