<template>
  <el-form ref="form" class="sap-form" :label-width="labelWidth" size="mini">
    <template v-for="item in sapFieldList">
      <SapFormContext v-show="item.show" v-model="sapForm[item.sapField]" :item="item" :key="item.id" :label-width="labelWidth"/>
    </template>
    <div class="form-footer">
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </el-form>
</template>

<script>
import SapFormContext from '@/views/mes/md/sapField/components/SapFormContext'
import { listViewVo } from '@/api/mes/md/sapField'
import { addData, updateData } from '@/api/mes/md/sapPropertyData'

export default {
  components: {
    SapFormContext
  },
  props: {
    labelWidth: { type: String, default: '150px' },
  },
  data() {
    return {
      loading: false,
      relationId: null,
      sapForm: {},
      sapFieldList: []
    }
  },
  methods: {
    onConfirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          let data = {}
          data.sapData = JSON.stringify(this.sapForm)
          console.log(this.form)
          let handleEdit = this.form.id ? updateData : addData
          handleEdit(this.form).then(() => this.$message.success('操作成功')).finally(() => this.loading = false)
        }
      })
    },
    init(type, relationId, data = { ITEM: [{ SIZE: [{}] }, { SIZE: [{}] }] }) {
      console.log(type, relationId)
      let params = { type, parentId: 0 }
      listViewVo(params).then(res => {
        this.sapFieldList = res.data
        this.sapForm = this.initSapForm(res.data, data)
        console.log(this.sapFieldList, this.sapForm)
      })
    },
    initSapForm(sapFieldList, data = {}) {
      let sapForm = {}
      for (let i = 0; i < sapFieldList.length; i++) {
        const item = sapFieldList[i]
        let itemData = data[item.field]

        if (item.dataType == 9) {
          sapForm[item.sapField] = this.initSapForm(item.children, itemData || {})
        } else if (item.dataType == 10) {
          sapForm[item.sapField] = sapForm[item.sapField] || []
          itemData = itemData || []
          for (let j = 0; j < itemData.length; j++) {
            const subItemData = itemData[j]
            sapForm[item.sapField][j] = this.initSapForm(item.children, subItemData)
          }
        } else {
          sapForm[item.sapField] = itemData || item.defaultValue
        }
      }
      return sapForm
    }
  },
  created() {

  }
}
</script>

<style scoped>
.sap-form {
  margin-bottom: 50px;
}
</style>
