<template>
  <div style="height: 100%">
    <vxe-grid
      :size="'mini'"
      ref="xGrid"
      height="560"
      :keep-source="true"
      border
      resizable
      align="left"
      showHeaderOverflow
      showOverflow
      :row-config="{ isCurrent: true, isHover: true }"
      :columns="formConfig"
      :column-config="{ minWidth: 100 }"
      :data="tableData"
      :loading="listLoading"
      :showFooter="false"
      :printConfig="{}"
      :merge-cells="mergeCells"
    >
    </vxe-grid>
  </div>
</template>

<script>
export default {
  name: 'dynamicTable',
  data() {
    return {
      description: '',
      formName: '',
      refreshTable: false,
      listLoading: false,
      formConfig: [],
      tableData: [],
      mergeCells: [],
      columnDict: [],
      list: [],
      columnList: [],
      dataForm: {
        id: '',
        data: '',
        flowId: ''
      }
    }
  },
  methods: {
    init(data) {
      this.description = data.description
      this.formName = data.formName
      this.setting = data
      let columnConf = data.formConf ? JSON.parse(data.formConf) : {}
      this.columnList = JSON.parse(columnConf.columnList).columnList
      this.columnDict = columnConf.columnDict ? JSON.parse(columnConf.columnDict) : {}
      this.formConfig = this.columnList
      this.dataForm.id = data.id || ''
      this.listLoading = true
      this.$nextTick(() => {
        if (this.dataForm.id) {
          this.dataForm = { data: data.formDataJson, id: data.id, flowId: data.flowId }
          if (!this.dataForm.data) return
          let dataObj = JSON.parse(this.dataForm.data)
          // 使用 Object.values() 将 data 转换为数组
          this.list = Object.values(dataObj);
          const loop = (data, parent) => {
            if (!data) return
            if (data && data.jnpfKey === 'table' && data.children && Array.isArray(data.children)) {
              loop(data.children)
            }
            if (data && data.jnpfKey === 'tab' && data.children && Array.isArray(data.children)) {
              loop(data.children, data.jnpfKey)
            }
            if (Array.isArray(data) && data.length) {
              for (let i = 0; i < data.length; i++) {
                loop(data[i], parent)
              }
            }
            if (Object.prototype.toString.call(data) === '[object Object]' && parent === 'tab' && data.children && data.children.length) {
              loop(data.children, parent)
            }
            if (data && data.jnpfKey && data.propId) {
                data.field = this.columnDict[data.propId]
            }
          }
          loop(this.columnList)
          this.getDataList(this.list)
          //如果导出时 只勾选了部分展示的列
          let fitlerData = Object.keys(this.list[0])
          // console.log(fitlerData)
          // console.log(this.columnList)
          this.columnList = this.columnList.filter((i) => {
            if (fitlerData.includes(this.columnDict[i.propId])) {
              return i
            }
          })
          this.$nextTick(() => {
            this.listLoading = false
            this.refreshTable = false
            this.$emit('setPageLoad')
          })
        } else {
          this.$nextTick(() => {
            this.listLoading = false
            this.refreshTable = false
            this.$emit('setPageLoad')
          })
        }
      })
    },
    // 组装数据
    getDataList(data) {
      data.forEach((item, index) => {
        item.seq = index + 1
      })
      this.mergeCells = []
      let list = []
      const columnListTable = g.T.toTable(this.formConfig, 'children').filter((i) => i.jnpfKey !== 'table')
      let dataView = data && data.length ? data[0] : []
      const foreignKeys = Object.keys(dataView).filter((key) => key.startsWith('FOREIGN_KEY_'))
      list = data.map((v, index) => {
        let records = v
        const mergedPageData = []
        if (foreignKeys.length > 0) {
          const foreignKeysLength = []
          for (let foreignKey of foreignKeys) {
            if (records[foreignKey] && records[foreignKey].pageData) {
              foreignKeysLength.push(records[foreignKey].pageData.length)
            }
          }
          if (foreignKeysLength.length === 0) {
            mergedPageData.push(records)
          } else {
            const numItems = Math.max(...foreignKeysLength)
            for (let i = 0; i < numItems; i++) {
              let mergedItem = {}
              // 循环合并在此索引位置的所有FOREIGN_KEY的pageData对象
              for (let foreignKey of foreignKeys) {
                if (records[foreignKey].pageData && records[foreignKey].pageData[i]) {
                  mergedItem = { ...mergedItem, ...records[foreignKey].pageData[i] }
                }
              }
              // 添加合并后的对象到结果数组
              mergedPageData.push({ ...records, ...mergedItem, ...{ mergeRow: numItems, row: index } })
            }
          }
        } else {
          mergedPageData.push(records)
        }
        return mergedPageData
      })
      let num = 0
      const newList = list.flat()
      let fields = {}
      this.columnList.forEach((i, index) => {
        if (i.children && i.children.length < 1) {
          fields[i.field] = columnListTable.findIndex((o) => o.field === i.field)
        }
      })
      list
        .filter((v) => v)
        .forEach((item) => {
          item.forEach((i, index) => {
            for (const iKey in i) {
              if (fields[iKey] >= 0) {
                this.mergeCells.push({
                  row: num,
                  col: fields[iKey],
                  rowspan: i.mergeRow,
                  colspan: 1
                })
              }
            }
          })
          num += item.length
        })
      // 数组拍平
      this.tableData = newList
    },
    //图片类型处理
    getImgFun(value) {
      try {
        const toObj = JSON.parse(value)
        if (Array.isArray(toObj) && toObj[0].url) {
          return toObj
        }
      } catch {}
      return value
    },
    getImgFunList(val) {
      const list = this.getImgFun(val)
      if (Array.isArray(list) && list.length)
        return list.map((i) => {
          return this.define.comUrl + i.url
        })
    },
    dataFormSubmit(eventType) {
      this.eventType = eventType
      this.dataForm.data = JSON.stringify(this.list)
      this.$emit('eventReciver', this.dataForm, this.eventType)
    }
  }
}
</script>

<style scoped></style>
