<template>
  <div>
    <template v-if="formData.popupType === 'general'">
      <el-dialog :title="!dataForm.id ? '新建' : '编辑'" :close-on-click-modal="false" :visible.sync="visible" class="JNPF-dialog JNPF-dialog_center" lock-scroll :width="formData.generalWidth">
        <parser :form-conf="formData" :relation-conf="relationConf" :idKey="idKey" @submit="sumbitForm" :key="key" ref="dynamicForm" v-if="!loading" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">{{ formData.cancelButtonText || '取 消' }}</el-button>
          <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading"> {{ formData.confirmButtonText || '确 定' }}</el-button>
        </span>
      </el-dialog>
    </template>
    <template v-if="formData.popupType === 'fullScreen'">
      <transition name="el-zoom-in-center">
        <div class="JNPF-preview-main">
          <div class="JNPF-common-page-header">
            <el-page-header @back="goBack" :content="!dataForm.id ? '新建' : '编辑'" />
            <div class="options">
              <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading"> {{ formData.confirmButtonText || '确 定' }}</el-button>
              <el-button @click="goBack">{{ formData.cancelButtonText || '取 消' }}</el-button>
            </div>
          </div>
          <div class="dynamic-form-main" :style="{ margin: '0 auto', width: formData.fullScreenWidth }">
            <parser :form-conf="formData" @submit="sumbitForm" :key="key" ref="dynamicForm" v-if="!loading" />
          </div>
        </div>
      </transition>
    </template>
  </div>
</template>

<script>
import { createModel, updateModel, getModelInfo } from '@/api/onlineDev/visualDev'
import Parser from '@/components/Generator/parser/Parser'
import { useDateList } from '@/components/Generator/generator/comConfig'
import { deepClone } from '@/utils'
import moment from 'moment'
export default {
  components: { Parser },
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        data: ''
      },
      modelId: '',
      formData: {},
      idKey: '',
      formValue: {},
      key: +new Date(),
      btnLoading: false,
      loading: true,
      isPreview: false,
      useDateList,
      relationConf: []
    }
  },
  methods: {
    goBack() {
      this.$emit('refreshDataList')
    },
    init(formData, modelId, id, isPreview, row, idKey, columnDict) {
      this.formData = deepClone(formData)
      this.idKey = idKey
      this.modelId = modelId
      this.isPreview = isPreview
      this.dataForm.id = id || ''
      this.loading = true
      this.$nextTick(() => {
        if (this.dataForm.id) {
          // getModelInfo(modelId, this.dataForm.id).then(res => {
          //   this.dataForm = res.data.data
          //   if (!this.dataForm.data) return
          //   this.formValue = JSON.parse(this.dataForm.data)
          //   this.fillFormData(this.formData, this.formValue)
          this.fillFormData(this.formData, row, columnDict)
          this.$nextTick(() => {
            this.visible = true
            this.loading = false
            let oldData = this.formData.fields.map((item) => {
              let value = item.__config__.defaultValue
              let id = item.__vModel__
              return { value: value, id: id }
            })
            oldData.forEach((item, index) => {
              try {
                item.value = JSON.parse(item.value)
              } catch {}
            })
            this.dataForm.oldData = this.arrTransferObj(oldData, 'id', 'value')
            this.dataForm.oldData = JSON.stringify(this.dataForm.oldData)
          })
          // })
        } else {
          this.dataForm.oldData = null
          this.formValue = {}
          this.visible = true
          this.loading = false
        }
        this.key = +new Date()
      })
    },
    /** 数组转对象* @param {Object} e 原始数组 * @param {Object} key 键* @param {Object} val 值*/
    arrTransferObj(e, key, val) {
      // 数组的reduce方法，使数组的obj初始值为{}，将数组中每一个对象所需的值，分别作为对象中的键与值
      return e.reduce((obj, item) => ((obj[item[key]] = item[val]), obj), {})
    },
    fillFormData(form, data, columnDict) {
      const loop = (list) => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            const val = data[columnDict[item.__vModel__]]
            if (val) item.__config__.defaultValue = val
            if (item.__config__.viewDataType === 'DATETIME') {
              if (this.useDateList.indexOf(item.__config__.jnpfKey) < 0) {
                item.__config__.defaultValue = moment(val).valueOf()
              }
            }
            if (item.__config__ && item.__config__.jnpfKey === 'uploadImg') {
              try {
                let defaultValue = JSON.parse(item.__config__.defaultValue)
                item.__config__.defaultValue = defaultValue.length ? defaultValue : []
              } catch {}
            }
          }
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
    },
    getSerialincNumberData(fields, data) {
      let obj = fields.find((o) => o.__config__.jnpfKey === 'serialNumber')
      if (obj) {
        let copySet = deepClone(obj.serialgz)
        copySet.forEach((i, k) => {
          //根据设置生成数据
          if (i.type === 'createTime') {
            this.$set(i, 'chars', moment().format(i.format))
          }
          if (i.type === 'widget') {
            this.$set(i, 'chars', data[i.widgetvModel])
          }
        })
        return { _serialNumber: obj.__vModel__, _serialNumberConfig: copySet }
      } else {
        return null
      }
    },
    sumbitForm(data) {
      if (!data) return
      //获取流水号数据
      let serialincNumberData = this.getSerialincNumberData(this.formData.fields, data)
      this.btnLoading = true
      let subimtData = []
      //查询是否新增 新增的情况下 查询有没有子表
      if (!this.dataForm.id) {
        // 输入查询字符和对象，返回匹配的键的值组成的对象
        function searchHostObject(query, object) {
          const result = {}
          for (const key in object) {
            if (!object.hasOwnProperty(key) || !key.includes(query)) {
              result[key] = object[key]
            }
          }
          return result
        }
        function searchAssistantObject(query, object) {
          let result = []
          for (const key in object) {
            if (object.hasOwnProperty(key) && key.includes(query)) {
              result = object[key]
            }
          }
          return result
        }
        //查询主表字段
        const HostObj = searchHostObject('tableField', data)
        //查询子表字段
        const AssistantArray = searchAssistantObject('tableField', data)
        //存在子表
        if (AssistantArray.length) {
          //数据合并
          AssistantArray.forEach((i, k) => {
            Object.assign(i, HostObj)
          })
          subimtData = AssistantArray.map((i, k) => {
            return {
              id: '',
              oldData: null,
              data: JSON.stringify(i),
              ...serialincNumberData
            }
          })
        } else {
          subimtData = [{ data: JSON.stringify(data), id: '', oldData: null, ...serialincNumberData }]
        }
      } else {
        subimtData = [{ data: JSON.stringify(data), id: this.dataForm.id, oldData: this.dataForm.oldData }]
      }
      const formMethod = this.dataForm.id ? updateModel : createModel
      formMethod(this.modelId, subimtData, this.dataForm.id)
        .then((res) => {
          this.$message({
            message: res.data.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.btnLoading = false
              let flagInit = this.dataForm.id ? true : false
              this.$emit('refreshDataList', this.dataForm.id, res.data.data)
            }
          })
        })
        .catch(() => {
          this.btnLoading = false
        })
    },
    dataFormSubmit() {
      if (this.isPreview) return this.$message({ message: '功能预览不支持数据保存', type: 'warning' })
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
    }
  }
}
</script>
