<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" :relation-conf="relationConf" :idKey="idKey" @submit="sumbitForm" :key="key" ref="dynamicForm" v-if="!loading" />
          </div>
        </div>
      </transition>
    </template>
  </div>
</template>

<script>
import { createModel, updateModel, getModelInfo, NOcreateModel } 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 },
  props: ['relationData'],
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        data: ''
      },
      modelId: '',
      formData: {},
      idKey: '',
      formValue: {},
      key: +new Date(),
      btnLoading: false,
      loading: true,
      isPreview: false,
      useDateList,
      relationConf: [],
      secondaryDbLinkIdList: [],
      dbLinkId: ''
    }
  },
  methods: {
    goBack() {
      this.$emit('refreshDataList')
    },
    getfilterList(arr, u_key) {
      let map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    },
    init(formData, modelId, id, isPreview, row, idKey, columnDict, secondaryDbLinkId, dbLinkId) {
      this.relationConf = this.relationData || []
      this.secondaryDbLinkIdList = secondaryDbLinkId || []
      this.dbLinkId = dbLinkId
      let copyFields = deepClone(formData)
      //修改时不需要批量
      if (!id) {
        let tableChildren = copyFields.fields.filter((item, k) => item.fatherBoxConfig && item.__fathervModel__)
        //将子表数据格式化
        if (tableChildren && tableChildren.length) {
          let NewList = this.getfilterList(tableChildren, '__fathervModel__')
          let tabelBox = NewList.map((item, k) => {
            return {
              __config__: item.fatherBoxConfig,
              __vModel__: item.__fathervModel__,
              actionText: item.fatherActionText
            }
          })
          let formList = copyFields.fields.filter((item, k) => !item.fatherBoxConfig && !item.__fathervModel__)
          copyFields.fields = formList.concat(tabelBox)
        }
      }
      this.formData = copyFields
      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__
              let typeKey = item.__config__.jnpfKey
              return { value: value, id: id, typeKey: typeKey }
            })
            oldData.forEach((item, index) => {
              //文本输入框不转
              try {
                if (item.typeKey !== 'comInput') {
                  item.value = JSON.parse(item.value)
                }
              } catch {}
              delete item.typeKey
            })
            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 === 'select') {
              try {
                item.__config__.defaultValue = val.toString()
              } catch {}
            }
            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
      }
    },
    //子表整合数据
    flattenedArrayWithKey(foreignObj) {
      const result = []
      for (const key in foreignObj) {
        foreignObj[key].forEach((item) => {
          result.push({ dbLink: key, id: '', oldData: null, data: JSON.stringify(item) })
        })
      }
      return result
    },
    sumbitForm(data) {
      if (!data) return
      this.btnLoading = true
      let params = {}
      //查询是否新增 新增的情况下 查询有没有子表
      if (!this.dataForm.id) {
        //主表数据
        const primaryObj = {}
        //子表数据
        const foreignObj = {}
        //获取提交数据时 查询存在于子表数据集合的key 将主子表数据区分开
        for (const key in data) {
          if (this.secondaryDbLinkIdList.includes(Number(key)) && Array.isArray(data[key])) {
            foreignObj[key] = data[key]
          } else {
            primaryObj[key] = data[key]
          }
        }
        //获取流水号数据
        let serialincNumberData = this.getSerialincNumberData(this.formData.fields, data)
        //主表整合信息
        let primaryTable = {
          dbLink: this.dbLinkId,
          id: '',
          oldData: null,
          data: JSON.stringify(primaryObj),
          ...serialincNumberData
        }
        //子表整合数据
        let foreignTable = this.flattenedArrayWithKey(foreignObj)
        params = {
          primaryTable: primaryTable,
          foreignTable: foreignTable
        }
      }
      const formMethod = this.dataForm.id ? updateModel : NOcreateModel
      formMethod(this.modelId, params, 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>
