<template>
  <div class="base-info">
    <el-form :model="sapData" ref="form" label-width="130px" size="mini">
      <el-row class="form-wrap" :gutter="gutter">
        <div>
          <template v-for="(sapProperties, key) in sapPropertyMap">
            <el-col :span="24" class="separator">{{ getViewTypeName(key) }}</el-col>
            <template v-for="item in sapProperties">
              <el-col :span="span" :key="item.id">
                <el-form-item :label="item.name" :prop="key + '.' + item.sapField"
                              :rules="item.required ? {required: item.required, validator: (rule, value, callback) => onValidate(rule, value, callback, item), trigger: ['change']} : null">
                  <el-input-all v-model="sapData[key][item.sapField]" :item="item"/>
                </el-form-item>
              </el-col>
            </template>
          </template>
        </div>
      </el-row>

      <div class="footer">
        <el-button type="primary" @click="onConfirm" :loading="loading" size="mini">确认</el-button>
      </div>
    </el-form>

  </div>
</template>

<script>
import {listByType} from '@/api/mes/md/sapproperty'
import { addData, updateData, listData } from '@/api/mes/md/sapPropertyData'

export default {
  dicts: ['sap_property_view', 'sap_property_relation'],
  props: {
    gutter: {type: Number, default: 10},
    span: {type: Number, default: 8},
  },
  data() {
    return {
      loading: false,
      sapPropertyMap: [],
      customer: {},
      form: {
        type: null,
        relationId: null,
      },
      sapData: {
      },
      sapProperty: {
        id: '',
        type: '',
        viewType: '',
        name: '',
        typeId: '',
        sapField: '',
        relationField: '',
        typeName: '',
        dataType: '',
        length: '',
        min: '',
        max: '',
        regEx: '',
        dictId: '',
        errMsg: '',
        dictList: []
      },
    }
  },
  methods: {
    onConfirm() {
      if (!Object.keys(this.sapData).length) return
      console.log(this.sapData)
      if (this.loading) return
      if (!this.form.type || !this.form.relationId) return this.$message.error("对象未创建")
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.form.sapData = JSON.stringify(this.sapData)
          console.log(this.form)
          let handleEdit = this.form.id ? updateData : addData
          handleEdit(this.form).then(() => this.$message.success('操作成功')).finally(() => this.loading = false)
        } else {
          this.$message.error("请检查表单")
        }
      })
    },
    onValidate(rule, value, callback, item) {
      if (value === '' || value == null) {
        callback(new Error(item.errMsg))
      } else {
        if (item.dataType === 1) {
          if (value.length > item.length || !new RegExp(item.regEx).test(value)) callback(new Error(item.errMsg))
        } else if ([2, 3].includes(item.dataType)) {
          if (value < item.min || value > max) callback(new Error(item.errMsg))
        }
        callback()
      }
    },

    getViewTypeName(viewType) {
      let viewTypeDict = this.dict.type.sap_property_view.find(item => item.value == this.form.type && item.raw.cssClass === viewType) || {}
      return viewTypeDict.label || viewType
    },

    setData(data, sapData, sapPropertyMap) {
      let keys = Object.keys(sapPropertyMap)
      for (const key of keys) {
        if (!sapPropertyMap.hasOwnProperty(key)) continue
        if (!sapData[key]) sapData[key] = {}
        let properties = sapPropertyMap[key]
        for (let property of properties) {
          let propertyData = data[property.relationField]
          sapData[key][property.sapField] = propertyData || sapData[key][property.sapField] || ''
        }
      }
      this.sapData = sapData
      console.log(sapData)
      this.sapPropertyMap = sapPropertyMap
      console.log(sapPropertyMap)
    },

    init(type, viewType, relationId, data = {}) {
      this.$refs.form && this.$refs.form.resetFields()
      this.form.type = type
      this.form.relationId = relationId
      this.form.viewType = viewType
      let sapData = {}
      // 获取sap特性列表
      listByType({type, viewType}).then(res => {
        let sapProperties = res.data || []
        let sapPropertyMap = sapProperties.reduce((sapPropertyMap, item) => {
          if (!sapPropertyMap[item.viewType]) sapPropertyMap[item.viewType] = []
          sapPropertyMap[item.viewType].push(item)
          return sapPropertyMap
        }, {})
        if (relationId) {
          // 获取sap特性值
          listData({type, viewType, relationId}).then(resp => {
            let row = resp.rows[0] || {sapData: '{}'}
            this.form.id = row.id
            sapData = JSON.parse(row.sapData)
            // 再次赋值
            this.setData(data, sapData, sapPropertyMap)
          })
        } else {
          this.setData(data, sapData, sapPropertyMap)
        }
      })
    }
  },
  created() {

  }
}
</script>

<style scoped>
.form-wrap {
  max-height: 400px;
  overflow-y: auto;
}

.footer {
  margin: 10px;
  text-align: right;
}

.separator {
  line-height: 30px;
  border-bottom: 1px solid #dddddd;
  padding: 10px 20px;
  margin: 0 20px 20px;
  font-weight: bold;
}
</style>
