<template>
  <vxe-modal :title="title" :close-on-click-modal="false" v-model="visible" lock-scroll transfer :width="relationWidth" height="70%" width="60%">
    <div class="JNPF-common-layout">
      <div class="JNPF-common-layout-center">
        <Search ref="Search" :list="columnData.searchList" :columnData="columnData" :treeBoxSearch="treeBoxSearch" @reset="reset" @search="search" />
        <div class="JNPF-common-layout-main JNPF-flex-main">
          <!--        @row-dblclick="dbclick"-->
          <vxe-grid
            :size="tableSpacing === 1 ? 'mini' : 'small'"
            ref="xGrid"
            height="auto"
            :keep-source="true"
            border
            resizable
            :align="formData.labelPosition"
            show-header-overflow
            :data="list"
            :row-config="{ isCurrent: true, isHover: true }"
            :columns="columnList"
            :column-config="{ minWidth: formData.labelWidth }"
            :loading="listLoading"
            :showFooter="columnData.showSummary"
            :printConfig="{}"
            :filter-config="{
              resetButtonText: ' ',
              confirmButtonText: ' '
            }"
            :toolbarConfig="toolbarConfig"
            :merge-cells="mergeCells"
            @checkbox-change="handleSelectionChange"
            @checkbox-all="handleSelectionChange"
            :cell-style="formatColumnCellStyle"
            :row-style="rowStyle"
            :header-cell-style="headerStyle"
          >
            <template #seq="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #default_images="{ row, column }">
              <template v-if="imgList[column.property] && row[column.property]">
                <amis-sdk
                  :datasource="{
                    images: row[column.property]
                      .split(';')
                      .filter((v) => v && !v.includes('uploads/'))
                      .map((o) => comUrlImage + '/api/file/getFileInputStreamById/' + o)
                  }"
                  :amis-json="{
                    type: 'images',
                    enlargeAble: true,
                    showToolbar: true,
                    source: '${images}',
                    thumbMode: 'cover',
                    thumbRatio: '16:9'
                  }"
                />
              </template>
            </template>
            <template #default_file="{ row, column }">
              <template v-if="fileList[column.property] && row[column.property]">
                <el-button v-for="(item, uindex) in row[column.property].split(';').map((o) => fileList[column.property][o] || null)" type="text" size="mini" @click="imgOpenClick(item.filePath)">
                  {{ item?.fileName }}
                </el-button>
              </template>
              <template v-else-if="column.params.jnpfKey === 'uploadFz' && row[column.property] && row[column.property] !== 'null' && row[column.property].includes('uploads/')">
                <el-button v-for="(item, uindex) in JSON.parse(row[column.property])" type="text" size="mini" @click="imgOpenClick(item?.url)">{{ item.name }}</el-button>
              </template>
              <template v-else>
                <template v-if="row[column.property]">
                  <a
                    v-for="(fzItem, fzIndex) in row[column.property].split(';')"
                    :key="fzIndex"
                    style="color: #1890ff; display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis"
                    :href="'http://60.190.98.244:9175/system/systemfile/' + fzItem"
                    target="_blank"
                    ><i class="el-icon-document"></i> {{ fzItem }}</a
                  >
                </template>
              </template>
            </template>
            <template #relationDefault="{ row, column }">
              <div v-for="(item, index) in row[column.property] ? row[column.property].toString().split(';') : row[column.property]" :key="item">
                <template v-if="column.params.compoentConfig.relationData.isText">
                  <div class="el-button--text pointer">
                    <template v-if="index > 0">,</template>
                    {{ formatAssociationData(row, column, item) }}
                  </div>
                </template>
                <template v-else-if="column.params.compoentConfig.isUrl">
                  <div class="el-button--text pointer">
                    <template v-if="index > 0">,</template>
                    {{ formatAssociationData(row, column, item) }}
                  </div>
                </template>
                <template v-else>
                  {{ formatAssociationData(row, column, item) }}
                </template>
              </div>
            </template>
            <template #columnAnotherName="{ row, column }">
              {{ formatColumnAnotherName(row, column) ? formatColumnAnotherName(row, column) : row[column.property] }}
            </template>
            <template #startTime="scope">
              {{ scope.row.startTime | formatDate }}
            </template>
            <template #thisStep="scope">
              {{ scope.row.thisStep }}
            </template>
            <template #status="scope">
              <el-tag type="primary" v-if="scope.row.status == 1">等待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.status == 2">审核通过</el-tag>
              <el-tag type="danger" v-else-if="scope.row.status == 3">审核驳回</el-tag>
              <el-tag type="warning" v-else-if="scope.row.status == 4">流程撤回</el-tag>
              <el-tag v-else-if="scope.row.status == 5" type="info">审核终止</el-tag>
              <el-tag v-else type="info">等待提交</el-tag>
            </template>
            <template v-slot:pager>
              <vxe-pager
                v-if="columnData.hasPage"
                background
                border
                :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                :current-page.sync="listQuery.currentPage"
                :page-size.sync="listQuery.pageSize"
                :total="total"
                :page-sizes="[5, 10, 20, 50, 100, 500]"
                @page-change="refreshTableLayout()"
              >
              </vxe-pager>
              <div style="text-align: right">
                <el-button type="primary" size="mini" @click="relationTableData"> 提 交 </el-button>
              </div>
            </template>
          </vxe-grid>
        </div>
      </div>
    </div>
  </vxe-modal>
</template>
<script>
import Search from '@/views/basic/dynamicModel/list/Search.vue'
import AmisSdk from '@/components/AmisSdk.vue'
import { deepClone, formatDate, getSeachPrimaryAndForeignTable } from '@/utils'
import { getBrowserData, getChildrenConfigData, getConfigData, getPrecondition, queryProcessBasedOnProcessInstanceId } from '@/api/onlineDev/visualDev'
import { dictDetail } from '@/api/newbi/dict'
import { getAPIData, getTreeAPIData } from '@/components/Dataset-filter/util'
import { getFileById } from '@/api/common'
import {comUrl} from "@/utils/define";

export default {
  name: 'index',
  components: { AmisSdk, Search },
  data() {
    return {
      title: '请选择',
      visible: false,
      relationWidth: '60%',
      treeBoxSearch: '',
      columnData: {
        searchList: [],
        columnBtnsList: []
      },
      total: 0,
      tableSpacing: 1,
      listQuery: {
        currentPage: 1,
        pageSize: 5,
        sort: 'descs',
        sidx: '',
        json: ''
      },
      formData: {},
      list: [],
      columnList: [],
      listLoading: false,
      // 新版表格
      toolbarConfig: {
        print: false,
        zoom: false,
        custom: false
      },
      mergeCells: [],
      imgList: {},
      fileList: {},
      comUrlImage:comUrl,
      // 表头筛选数组
      filterList: {},
      getPreconditionObj: {},
      idKey: '',
      columnDict: {},
      multipleSelection: [],
      multipleSelectionDelectData: []
    }
  },
  filters: {
    // 时间格式自定义 只需把字符串里面的改成自己所需的格式
    formatDate(time) {
      if (!time) return '/'
      let date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  created() {},
  methods: {
    async init(v) {
      await getConfigData(v).then((res) => {
        this.config = res.data.data
        this.idKey = this.config.idKey
        this.refreshTable = false
        if (!this.config.columnData || !this.config.formData) return
        this.columnData = JSON.parse(this.config.columnData)
        this.relationData = JSON.parse(this.config.relationData)
        if (this.columnData.type === 3) {
          this.columnData.columnList = this.columnData.columnList.filter((o) => o.prop != this.columnData.groupField)
        }
        this.formData = JSON.parse(this.config.formData)
        this.getColumnList()
        if (this.isPreview) return
        this.listQuery.pageSize = this.columnData.pageSize
        this.listQuery.sort = this.columnData.sort
        this.listQuery.sidx = this.columnData.defaultSidx
        this.$refs.Search.searchList = deepClone(this.columnData.searchList)
        this.$refs.Search.buildOptions(deepClone(this.columnData.searchList))
        if (this.columnData.type === 3 || !this.columnData.hasPage) this.listQuery.pageSize = 10000
        if (this.columnData.type === 2) {
          this.getTreeView()
          // this.initData()
        } else {
          //请求权限 列表 直接看这一条 从搜索组件调用
          // this.initData()
        }
        this.$refs.Search.search()
      })
    },
    async getTreeView() {
      const treeList = this.columnData.treeList
      for (const key in treeList) {
        const item = treeList[key]
        if (item.treeDataSource === 'dictionary') {
          if (!item.treeDictionary) return
          await dictDetail({ id: item.treeDictionary }).then((res) => {
            let content = JSON.parse(res.data.data.content || '[]')
            this.treeData = content.map((i) => ({ fullName: i.value, id: i.key }))
            this.columnData.treeList[key].treeData = this.treeData
            this.$set(this.columnData.treeList, key, this.columnData.treeList[key])
          })
        }
        if (item.treeDataSource === 'organize') {
          this.$store.dispatch('generator/getCompanyTree').then((res) => {
            this.treeData = res
          })
        }
        if (item.treeDataSource === 'department') {
          this.$store.dispatch('generator/getDepTree').then((res) => {
            this.treeData = res
          })
        }
        if (item.treeDataSource === 'api') {
          if (!item.treePropsUrl) return
          await getTreeAPIData(item.treePropsUrl, item).then((res) => {
            this.columnData.treeList[key].treeData = res
            this.$set(this.columnData.treeList, key, this.columnData.treeList[key])
          })
        }
      }
    },
    getColumnList() {
      if (this.isPreview || !this.columnData.useColumnPermission) {
        this.columnList = this.columnData.columnList
      } else {
        const permissionList = this.$store.getters.permissionList
        const modelId = this.$route.meta.modelId
        const list = permissionList.filter((o) => o.modelId === modelId)
        const columnList = list[0] && list[0].column ? list[0].column : []
        let realList = []
        for (let i = 0; i < columnList.length; i++) {
          inner: for (let j = 0; j < this.columnData.columnList.length; j++) {
            if (columnList[i].enCode === this.columnData.columnList[j].prop) {
              realList.push(this.columnData.columnList[j])
              break inner
            }
          }
        }
        this.columnList = realList
      }
    },
    reset() {
      this.listQuery.sort = 'descs'
      this.listQuery.sidx = ''
      this.treeFilter = ''
      this.filterListSearch = ''
      this.treeBoxList = this.$refs.treeBox
      this.treeBoxList?.forEach((i) => {
        i.setCurrentKey(null)
      })
    },
    search(json) {
      if (this.isPreview) return
      if (!json) this.$refs.treeBox && this.$refs.treeBox.setCurrentKey(null)
      this.listQuery.json = json && json.length ? JSON.parse(json) : []
      this.listQuery.currentPage = 1
      this.refreshTableLayout()
    },
    // 关联数据格式化
    formatAssociationData(row, column, item) {
      let cellValue = row[column.property]
      const field = column.field
      if (column.params.compoentConfig.isUrl) {
        const newUrl = g.replaceAll(cellValue, '@', '&')
        const unserialize = XEUtils.unserialize(newUrl)
        return unserialize.sname
      }
      if (column.params.compoentConfig.relationData && column.params.compoentConfig.relationData.showTitle.length) {
        if (column.params.compoentConfig.relationData.isCheck) {
          try {
            const data = this.associationData[field][row[field]]
            const primaryId = column.params.compoentConfig.relationData.itemRelationList.find((i) => i.drawId === column.params.propId)
            const relationField = this.associationColumnDict[field][primaryId.columnId]
            cellValue = data ? data[relationField] : cellValue
          } catch (e) {
            cellValue = row[field]
          }
        } else {
          // 逗号隔开
          try {
            const data = this.associationData[field][item]
            const primaryId = column.params.compoentConfig.relationData.itemRelationList.find((i) => i.drawId === column.params.propId)
            const relationField = this.associationColumnDict[field][primaryId.columnId]
            cellValue = data[relationField] ? data[relationField] : item
          } catch (e) {
            cellValue = row[field]
          }
        }
      }
      return cellValue === 'null' ? '' : cellValue
    },
    handleSelectionChange({ records }) {
      this.multipleSelectionDelectData = g.removeRepeatAttr(records, this.columnDict[this.idKey])
    },
    // 别名数据处理
    formatColumnAnotherName(row, column) {
      if (column?.params?.compoentConfig?.anotherNameList && column?.params?.compoentConfig?.anotherNameList.length) {
        let anotherNameList = column.params.compoentConfig.anotherNameList
        let anotherNameRow = anotherNameList.find((i) => i.realValue == row[column.property])
        if (anotherNameRow) {
          return anotherNameRow.anotherName
        } else {
          return row[column.property]
        }
      } else {
        return row[column.property]
      }
    },
    // 别名单元自定义样式处理
    formatColumnCellStyle({ row, column }) {
      if (!column?.params?.compoentConfig?.anotherName) return
      if (column?.params?.compoentConfig?.anotherNameList && column?.params?.compoentConfig?.anotherNameList.length) {
        let anotherNameList = column.params.compoentConfig.anotherNameList
        let anotherNameRow = anotherNameList.find((i) => i.realValue == row[column.property])
        if (anotherNameRow) {
          return {
            backgroundColor: anotherNameRow.columnBackgroundColor,
            color: anotherNameRow.columnBackgroundColor ? '#ffffff' : ''
          }
        }
      }
    },
    rowStyle() {
      return {
        fontSize: this.columnData?.gridStyle?.bodyFontSize + 'px'
      }
    },
    headerStyle() {
      const bgColor = this.columnData?.gridStyle?.headerBackgroundColor || '#f8f8f9'
      return {
        backgroundColor: `${bgColor}`,
        fontSize: this.columnData?.gridStyle?.headerFontSize + 'px',
        color: this.columnData?.gridStyle?.headerFontColor || '#606266'
      }
    },
    // 重新渲染表格
    async refreshTableLayout(foreignTableId = [], isRefresh = false) {
      await this.initData((foreignTableId = []), (isRefresh = false))
    },
    // 新版表格开始
    async initData(foreignTableId = [], isRefresh = false) {
      if (this.isPreview) return
      this.listLoading = true
      //获取列表数据
      function NewObj(key, vlaue) {
        this[key] = vlaue
      }
      let obj = new NewObj(this.listQuery.sort, this.listQuery.sidx)
      if (foreignTableId.length === 0 && !isRefresh) {
        foreignTableId = this.formData.fields
          .map((o) => {
            if (o.__config__.jnpfKey === 'table') {
              return o.__vModel__
            }
          })
          .filter((l) => l !== undefined)
      }
      if (this.listQuery.json && this.listQuery.json.length) {
        if (this.tabSearch) this.listQuery.json.push(this.tabSearch)
      } else {
        this.listQuery.json = this.tabSearch ? new Array(this.tabSearch) : ''
      }
      let listQuery = []
      if (this.treeFilter?.length) {
        listQuery = [...this.listQuery.json, ...this.treeFilter, ...(this.filterListSearch || [])]
      } else {
        listQuery = [...this.listQuery.json, ...(this.filterListSearch || [])]
      }
      let subTableQueryParams = []
      if (listQuery.length > 0) {
        listQuery.forEach((item) => {
          const oldItem = g.Copy(item)
          const findIndex = this.columnData.columnList.findIndex((i) => i.field === item.cubeColumnId)
          const find = this.columnData.columnList.find((i) => i.field === item.cubeColumnId)
          // 子表筛选
          if (findIndex && find?.config?.isJoin) {
            const subParamsObj = {
              tableName: find.config.tableName,
              columnName: find.config.columnName,
              function: find.config.jnpfKey === 'numInput' ? 'between' : 'like',
              values: oldItem.values
            }
            if (this.treeFilter.find((i) => i.cubeColumnId === item.cubeColumnId)) {
              subParamsObj.function = item.function
            }
            subTableQueryParams.push(subParamsObj)
            // 干掉主筛选里的子表条件
            listQuery = listQuery.splice(findIndex, 1)
          }
        })
      }
      const visualdevEntityDto = getSeachPrimaryAndForeignTable(this.config)
      this.parmes = {
        pageQuery: {
          currentPage: this.listQuery.currentPage,
          pageSize: this.listQuery.pageSize
        },
        primaryTableId: this.config.dbLinkId,
        foreignTableId: foreignTableId,
        modelId: this.modelId,
        browserRequest: listQuery ? JSON.stringify(listQuery) : JSON.stringify([]),
        subTableQueryParams: subTableQueryParams ? JSON.stringify(subTableQueryParams) : JSON.stringify([]),
        visualdevEntityDto
      }
      if (this.listQuery.sidx) {
        this.parmes.pageQuery[[this.listQuery.sort]] = this.listQuery.sidx
      }
      Object.assign(this.parmes.pageQuery, obj)
      const $grid = this.$refs.xGrid
      $grid.reloadData([])
      this.listLoading = true
      //获取数据权限过滤列表
      getBrowserData(this.config.dbLinkId, this.parmes).then(async (res) => {
        this.oldList = g.Copy(res.data.data.pageData.records)
        this.total = res.data.data.pageData.total
        if (!res.data.data.pageData.records) {
          this.listLoading = false
          return
        }
        this.associationData = res.data.data.associationData
        this.associationColumnDict = res.data.data.associationColumnDict
        //可显示的列
        let formDataFields = g.Copy(this.formData.fields)
        const itemRelationList = {}
        formDataFields.forEach((i) => {
          if (i.relationData && i.relationData.showTitle && i.relationData.showTitle.length) {
            i.relationData.itemRelationList.forEach((v) => {
              itemRelationList[v.drawId] = i.relationData
            })
          }
        })
        this.columnDict = res.data.data.columnDict
        formDataFields.forEach((i) => {
          if (i.__config__.jnpfKey === 'tab') {
            formDataFields = [
              ...formDataFields,
              ...g.T.toTable(
                i['__config__'].children.map((v) => v['__config__']),
                'children'
              ).filter((v) => v['__config__'])
            ]
          }
          if (i.__config__.jnpfKey === 'table') {
            formDataFields = [...formDataFields, ...g.T.toTable(i['__config__'].children, 'children').filter((v) => v['__config__'])]
          }
        })
        let columnList = []
        //过滤掉不可显示的列
        const apiList = {}
        const columnHeader = async (data, dbLinkId) => {
          let comName = {}
          let compoentConfig = {}
          comName = formDataFields.find((item) => item['__vModel__'] === data.propId)
          if (comName) {
            data.field = this.columnDict[data.propId]
            data.title = data.label
            data.showOverflow = true
            data.slots = {}
            // 自适应列宽度
            if (data.widthAuto) {
              // 85包含padding和筛选 排序的所占宽度 默认宽度 获取title的长度计算所占的px值 得出总宽度
              data.width = 60 + (g.getLen(data.title) || 0) * 6
            }
            compoentConfig = comName ? JSON.parse(JSON.stringify(comName)) : {}
            if (comName && comName['__config__']) {
              compoentConfig = { ...compoentConfig, ...comName['__config__'] }
            }
            if (comName && comName['__slot__']) {
              compoentConfig = { ...compoentConfig, ...comName['__slot__'] }
            }
            if (comName.relationData && comName.relationData.PrimaryId) {
              compoentConfig.relationData.isText = true
            } else if (itemRelationList[data.propId]) {
              compoentConfig.relationData = itemRelationList[data.propId]
              compoentConfig.relationData.isText = !!comName.relationData?.PrimaryId
            }
            if (compoentConfig.tag === 'el-cascader') {
              compoentConfig.props = compoentConfig.props.props
              if (compoentConfig.propsUrl && compoentConfig.dataType !== 'static') {
                apiList[data.field] = await getAPIData(compoentConfig, compoentConfig.propsUrl, compoentConfig.ApiParams, this.formData.fields, '', compoentConfig.apiProps)
                const treeList = apiList[data.field].filter((i) => i[compoentConfig.apiProps.idKey] || i[compoentConfig.apiProps.pidKey])
                compoentConfig.options = g.T.toTree(treeList, compoentConfig.props.children, compoentConfig.apiProps.idKey, compoentConfig.apiProps.pidKey)
              }
            }
            if (compoentConfig.tag === 'el-select') {
              if (compoentConfig.dataType === 'dictionary') {
                await dictDetail({ id: compoentConfig.dictionaryType }).then((res) => {
                  // this.activeData.__slot__.options = res.data.data.list
                  let content = JSON.parse(res.data.data.content || '[]')
                  compoentConfig.options = content.map((i) => ({ fullName: i.value, id: i.key }))
                })
              } else if (compoentConfig.propsUrl && compoentConfig.dataType !== 'static') {
                apiList[data.field] = await getAPIData(compoentConfig, compoentConfig.propsUrl, compoentConfig.ApiParams, this.formData.fields, '', compoentConfig.apiProps)
                compoentConfig.options = apiList[data.field]
              }
            }
            if (compoentConfig.tag === 'JNPF-UploadImg' || compoentConfig.jnpfKey === 'radio') {
              compoentConfig.readonly = true
            }
            if (compoentConfig.relationData && compoentConfig.relationData.showTitle.length) {
              compoentConfig.readonly = true
              // data.slots.default = 'relationDefault'
            }
            // 别名展示
            if (compoentConfig.anotherName) {
              data.slots.default = 'columnAnotherName'
            }
            if (compoentConfig.isUrl) {
              compoentConfig.readonly = true
              // data.slots.default = 'relationDefault'
            }
            data.editRender = {
              enabled: !compoentConfig.readonly,
              autoselect: true
            }
            if (!this.columnData.editable) {
              data.editRender.enabled = false
            }
            // console.log(compoentConfig.jnpfKey)
            if (compoentConfig.jnpfKey === 'uploadImg') {
              data.slots.default = 'default_images'
              data.showOverflow = false
              data.width = 300
            }
            if (compoentConfig.jnpfKey === 'uploadFz') {
              data.slots.default = 'default_file'
              data.showOverflow = false
            }
            if (['select', 'comInput', 'numInput'].includes(compoentConfig.jnpfKey)) {
              if (!this.columnData.showHeaderFilter) {
                data.filters = []
                this.filterList[compoentConfig.__vModelName__] = {
                  function: 'eq'
                }
              }
            }
            data.params = comName ? { ...comName['__config__'], ...{ propId: data.propId, cPropId: dbLinkId, field: data.field }, ...{ compoentConfig: compoentConfig } } : {}
            data.formatter = ({ cellValue, row, column }) => {
              if (column.params.jnpfKey === 'comInput') {
                cellValue = `${column.params.compoentConfig.prepend || ''}${cellValue}${column.params.compoentConfig.append || ''}`
              }
              if (column.params.tag === 'el-date-picker') {
                cellValue = cellValue
                  ? XEUtils.toDateString(cellValue, column.params.compoentConfig.format) !== 'Invalid Date'
                    ? XEUtils.toDateString(cellValue, column.params.compoentConfig.format)
                    : cellValue
                  : ''
              }
              if (column.params.tag === 'el-time-picker') {
                try {
                  cellValue = cellValue
                    ? XEUtils.toDateString(cellValue, column.params.compoentConfig.format) !== 'Invalid Date'
                      ? XEUtils.toDateString(cellValue, column.params.compoentConfig.format)
                      : cellValue
                    : ''
                } catch (e) {}
              }
              if (column.params.tag === 'el-input-number') {
                // 数字
                if (column?.params?.compoentConfig?.precision > -1) {
                  cellValue = cellValue ? XEUtils.toNumber(cellValue).toFixed(column.params.compoentConfig.precision) : ''
                }
                // cellValue = cellValue ? XEUtils.toNumber(cellValue) : ''
              }
              if (column.params.tag === 'el-select') {
                if (['dynamic', 'dictionary'].includes(data.params.dataType)) {
                  const find = column.params.compoentConfig.options.find((v) => v.id == cellValue)
                  cellValue = find && find.fullName ? find.fullName : cellValue
                } else if (data.params.dataType !== 'static') {
                  const find = apiList[data.field].find((v) => v[data.params.apiProps.value] == cellValue)
                  cellValue = find && find.fullName ? find.fullName : cellValue
                } else {
                  const find = column.params.compoentConfig.options.find((v) => v.id == cellValue)
                  cellValue = find && find.fullName ? find.fullName : cellValue
                }
              }
              if (column.params.tag === 'el-cascader') {
                if (data.params.dataType === 'dictionary') {
                  const find = column.params.compoentConfig.options.find((v) => v.id === cellValue)
                  cellValue = find && find.fullName ? find.fullName : cellValue
                } else if (data.params.dataType !== 'static') {
                  // 开启多选后，cellValue为多个数据 进行转换处理
                  if (data.params && data.params.compoentConfig && data.params.compoentConfig.props && data.params.compoentConfig.props.multiple) {
                    if (cellValue) {
                      cellValue = cellValue
                        .split(data.params.compoentConfig.props.separator || ';')
                        .map((v) => {
                          const find = apiList[data.field].find((i) => i[data.params.apiProps.idKey] === v)
                          return find && find.fullName ? find.fullName : v
                        })
                        .join(data.params.compoentConfig.props.separator || ';')
                    }
                  } else {
                    const find = apiList[data.field].find((v) => v[data.params.apiProps.idKey] === cellValue)
                    cellValue = find && find.fullName ? find.fullName : cellValue
                  }
                } else {
                  const find = g.T.toTable(column.params.compoentConfig.options, 'children').find((v) => v.id === cellValue)
                  cellValue = find && find.fullName ? find.fullName : cellValue
                }
              }
              if (column.params.tag === 'el-switch') {
                if (cellValue == column.params.compoentConfig['active-value']) {
                  cellValue = column.params.compoentConfig['active-text'] || '是'
                } else {
                  cellValue = column.params.compoentConfig['inactive-text'] || '否'
                }
              }
              if (column.params.jnpfKey === 'radio') {
                const find = column.params.compoentConfig.options.find((v) => v.id === cellValue)
                cellValue = find ? find.fullName : cellValue
              }
              if (cellValue == 'null' || cellValue == 'undefined') {
                return ''
              } else {
                return cellValue || null
              }
            }
          }
          return data
        }
        for (const item of this.columnList.filter((l) => l !== undefined)) {
          if (item.children && item.children.length > 0) {
            const list = []
            for (const v of item.children) {
              const data = await columnHeader(v, item.propId)
              list.push(data)
            }
            columnList.push({
              ...item,
              ...{
                sortable: false
              },
              children: list
            })
          } else {
            if (item.config && item.config.isJoin) {
              item.slots = {}
              if (item.jnpfKey === 'uploadImg') {
                item.slots.default = 'default_images'
                item.showOverflow = false
              }
              columnList.push(item)
            } else {
              const data = await columnHeader(item)
              columnList.push(data)
            }
          }
        }
        if (this.columnData.type !== 3 && this.columnData.hasPage) this.total = res.data.data.pageData.total
        if (this.columnData.type !== 3 && this.columnData.hasPage) this.listQuery.pageSize = res.data.data.pageData.size
        if (this.columnData.type !== 3 && this.columnData.hasPage) this.listQuery.currentPage = res.data.data.pageData.current

        this.childrenForm = {}
        formDataFields.forEach((item) => {
          if (item['__config__'].jnpfKey === 'table' && item['__config__'].children.length > 0) {
            getChildrenConfigData(this.modelId, item.dbLinkId).then((res) => {
              const data = res.data.data
              this.childrenForm[data.dbLinkId] = data
            })
          }
        })
        let width = this.columnData.columnBtnsList.length * 55
        // processDefinitions 查询有流程的数据 并返回流程编号
        let processDefinitionsIds = res.data.data.processDefinitions && res.data.data.processDefinitions.map((i) => i.processInstanceId)
        let processData = {}
        if (processDefinitionsIds && processDefinitionsIds.length) {
          await queryProcessBasedOnProcessInstanceId(this.config.flowId, processDefinitionsIds).then((processRes) => {
            processData = processRes.data.data
          })
        }
        if (this.config.webType == 3) {
          if (!columnList.find((i) => i.title === '发起时间')) {
            columnList.push({ title: '发起时间', fixed: 'right', align: 'center', slots: { default: 'startTime' } })
            columnList.push({ title: '当前节点', fixed: 'right', align: 'center', slots: { default: 'thisStep' } })
            columnList.push({ title: '流程状态', fixed: 'right', align: 'center', slots: { default: 'status' } })
            // columnList.push({ title: '流程进度',fixed: 'right', align: 'center',slots: { default: 'completion' }})
            // 如不过滤掉操作列 上面四个列会排到操作后面
            columnList = columnList.filter((i) => i.title !== '操作')
          }
        }
        if (!columnList.find((i) => i.title === '操作')) {
          columnList.unshift({ title: '序号', width: 50, field: 'seq', align: 'center' })
          columnList.unshift({ width: 50, type: 'checkbox', title: ' ' })
        }
        this.columnList = columnList.filter((i) => i.title)
        this.listLoading = false
        this.getDataList(res.data.data.pageData.records, processData)
      })
    },
    // 组装数据
    async getDataList(data, processData) {
      if (!data) {
        this.listLoading = false
        return
      }
      data.forEach((item, index) => {
        item.seq = index + 1
      })
      const $grid = this.$refs.xGrid
      this.mergeCells = []
      let list = []
      let columnListTable = []
      if (this.isColumn) {
        columnListTable = $grid.getColumns()
      } else {
        columnListTable = g.T.toTable(this.columnList, 'children').filter((i) => i.jnpfKey !== 'table')
      }
      const dataMap = (data) => {
        return data.map((v, index) => {
          // 当前数据是否存在流程
          if (v.processInstanceId) {
            let processRow = processData[v.processInstanceId]
            if (!processRow) return
            let flowData = {
              completion: processRow.completion,
              status: processRow.status,
              thisStep: processRow.thisStep,
              startTime: processRow.startTime
            }
            Object.assign(v, flowData)
          }
          const foreignKeys = Object.keys(v).filter((key) => key.startsWith('FOREIGN_KEY_'))
          const mergedPageData = []
          if (foreignKeys.length > 0) {
            const foreignKeysLength = []
            for (let foreignKey of foreignKeys) {
              if (v[foreignKey] && v[foreignKey].pageData) {
                foreignKeysLength.push(v[foreignKey].pageData.length)
              }
            }
            if (foreignKeysLength.length === 0) {
              mergedPageData.push(v)
            } else {
              const numItems = Math.max(...foreignKeysLength)
              for (let i = 0; i < numItems; i++) {
                let mergedItem = {}
                // 循环合并在此索引位置的所有FOREIGN_KEY的pageData对象
                for (let foreignKey of foreignKeys) {
                  if (v[foreignKey] && v[foreignKey].pageData && v[foreignKey].pageData[i]) {
                    mergedItem = { ...mergedItem, ...v[foreignKey].pageData[i] }
                  }
                }
                // 添加合并后的对象到结果数组
                mergedPageData.push({ ...v, ...mergedItem, ...{ mergeRow: numItems, row: index } })
              }
            }
          } else {
            mergedPageData.push(v)
          }
          return mergedPageData
        })
      }
      list = dataMap(data)
      this.oldList = dataMap(this.oldList).flat()
      let num = 0
      const newList = list.flat()
      let fields = {}

      for (const i of this.columnList) {
        if (i?.jnpfKey === 'uploadImg') {
          this.imgList[i.field] = newList.map((o) => o[i.field])
        }
        if (i?.jnpfKey === 'uploadFz') {
          let newListArray = newList
            .map((o) => o[i.field])
            .map((o) => (o?.url ? '' : o))
            .filter((o) => o && o !== 'null')
          // console.log(newList)
          const res = await getFileById(newListArray.map((v) => v.split(';')).flat())
          let obj = {}
          Object.keys(res.data.data).forEach((o) => {
            obj[o] = res.data.data[o]
          })
          // console.log(obj, i.field, this.fileList)
          this.fileList[i.field] = obj || []
        }
        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]) {
                this.mergeCells.push({
                  row: num,
                  col: fields[iKey],
                  rowspan: i.mergeRow,
                  colspan: 1
                })
              }
            }
            if (this.hasBatchBtn) {
              this.mergeCells.push({
                row: num,
                col: columnListTable.findIndex((o) => o.type === 'checkbox'),
                rowspan: i.mergeRow,
                colspan: 1
              })
            }
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.title === '序号'),
              rowspan: i.mergeRow,
              colspan: 1
            })
            if (processData) {
              this.mergeCells.push({
                row: num,
                col: columnListTable.findIndex((o) => o.title === '发起时间'),
                rowspan: i.mergeRow,
                colspan: 1
              })
              this.mergeCells.push({
                row: num,
                col: columnListTable.findIndex((o) => o.title === '当前节点'),
                rowspan: i.mergeRow,
                colspan: 1
              })
              this.mergeCells.push({
                row: num,
                col: columnListTable.findIndex((o) => o.title === '流程状态'),
                rowspan: i.mergeRow,
                colspan: 1
              })
            }
          })
          num += item.length
        })
      // 数组拍平
      const getPreconditionParam = {
        buttonIdList: [],
        idList: newList
          .map((i) => {
            return i[this.columnDict[this.idKey]]
          })
          .filter((l) => l !== undefined)
      }
      const getPreconditionObj = {}
      if (getPreconditionParam.buttonIdList.length > 0) {
        getPrecondition(this.modelId, getPreconditionParam).then((res) => {
          res.data.data.forEach((i) => {
            getPreconditionObj[i.authId] = i?.buttonList || []
            if (getPreconditionObj[i.authId].length > 0) {
              getPreconditionObj[i.authId].forEach((j) => {
                j.label = j.buttonName
                j.buttonId = j.id
              })
            }
          })
          this.getPreconditionObj = getPreconditionObj
        })
      }
      this.list = newList
    },
    relationTableData() {
      let data = this.multipleSelectionDelectData.map((o) => this.getFlowJsonData(o))
      this.$emit('relationTableData', data)
    },
    //整合数据 配合流程进行存储回显数据
    getFlowJsonData(row) {
      let rows = Object.assign({}, row)
      let jsonData = deepClone(this.columnDict)
      let returnData = {}
      for (let key in jsonData) {
        for (let index in rows) {
          if (index.includes('_TEXT') && jsonData[key] === index.replace('_TEXT', '') && !index.includes('foreign_')) {
            returnData[key + '_TEXT'] = rows[index]
          }
          if (jsonData[key] === index && !index.includes('foreign_')) {
            returnData[key] = rows[index]
          }
        }
      }
      return returnData
    }
  }
}
</script>

<style scoped lang="scss"></style>
