<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">{{$t('确认')}}</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)
          let handleEdit = this.form.id ? updateData : addData
          handleEdit(this.form).then(() => this.$message.success(this.$t('操作成功'))).finally(() => this.loading = false)
        }
      })
    },
    init(type, relationId, form, data) {
      this.form = form || {type, relationId}
      let sapData = form ? JSON.parse(form.sapData) : {}
      let params = { type, parentId: 0 }
      listViewVo(params).then(res => {
        this.sapFieldList = res.data
        this.sapForm = this.initSapForm(res.data, sapData, data)
        console.log(this.sapFieldList, this.sapForm, type, relationId)
      })
    },
    initSapForm(sapFieldList, sapData, data = {}) {
      let sapForm = {}
      for (let i = 0; i < sapFieldList.length; i++) {
        const item = sapFieldList[i]
        let itemData = data[item.field] || sapData[item.sapField]

        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>
