<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-left" v-if="columnData.type === 2">
      <div class="JNPF-common-title" v-if="columnData.treeTitle">
        <h2>{{ columnData.treeTitle }}</h2>
      </div>
      <el-tree
        :data="treeData"
        :props="treeProps"
        default-expand-all
        highlight-current
        ref="treeBox"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        class="JNPF-common-el-tree"
        :node-key="treeProps.value"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.icon"></i>
          <span class="text">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <div class="JNPF-common-layout-center">
      <topForm ref="topForm" v-if="columnData.type === 4" />
      <Search ref="Search" :list="columnData.searchList" @reset="reset" @search="search" />
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <!--          v-if="isPreview || !columnData.useBtnPermission"-->
          <div>
            <!--            <el-button type="text" @click="headBtnsHandel('batchUpdate')">批量编辑</el-button>-->
            <template v-for="(item, i) in columnData.btnsList">
              <el-button size="mini" v-if="item.value !== 'journal'" :type="i === 0 ? 'primary' : 'text'" :icon="item.icon" @click="headBtnsHandel(item.value)" :key="i">{{ item.label }}</el-button>
              <el-dropdown v-else @command="handleCommand">
                <span class="el-dropdown-link">操作日志<i class="el-icon-arrow-down el-icon--right"></i></span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="uploadList">批量导入日志</el-dropdown-item>
                  <el-dropdown-item command="exportList">批量导出日志</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <el-popover placement="bottom" width="200" trigger="click">
              <ul class="el-select-dropdown__list">
                <li class="el-select-group__title">冻结列</li>
                <li :class="[isFreeze === 1 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="isFreeze = 1">
                  <span style="float: left">第1列</span><span v-if="isFreeze === 1" style="float: right"><i class="el-icon-check"></i></span>
                </li>
                <li :class="[isFreeze === 2 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="isFreeze = 2">
                  <span style="float: left">前2列</span><span v-if="isFreeze === 2" style="float: right"><i class="el-icon-check"></i></span>
                </li>
                <li :class="[isFreeze === 3 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="isFreeze = 3">
                  <span style="float: left">前3列</span><span v-if="isFreeze === 3" style="float: right"><i class="el-icon-check"></i></span>
                </li>
                <li :class="[isFreeze === 4 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="isFreeze = 4">
                  <span style="float: left">前4列</span><span v-if="isFreeze === 4" style="float: right"><i class="el-icon-check"></i></span>
                </li>
                <li :class="[isFreeze === 5 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="isFreeze = 5">
                  <span style="float: left">前5列</span><span v-if="isFreeze === 5" style="float: right"><i class="el-icon-check"></i></span>
                </li>
              </ul>
              <el-button slot="reference" type="primary" icon="el-icon-connection" plain size="mini" style="margin: 0 10px">冻结</el-button>
            </el-popover>
            <el-popover placement="bottom" width="260" trigger="click">
              <p class="clearfix">
                <span class="el-select-group__title" style="padding: 0; float: left">字段设置</span>
                <span v-if="isShowFalg === 2" class="el-select-group__title setAllTitle" style="float: right" @click="checkAllChangeFn(true)">全部显示</span>
                <span v-if="isShowFalg === 1" class="el-select-group__title setAllTitle" style="float: right" @click="checkAllChangeFn(false)">全部隐藏</span>
              </p>
              <ul class="el-select-dropdown__list" style="max-height: 240px; position: relative; overflow-y: auto">
                <li class="el-select-dropdown__item" v-for="(item, k) in columnList" :key="k" style="padding: 0">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right"
                    ><el-switch
                      v-model="item.isShow"
                      @change="refreshTableLayout()"
                      :disabled="isShowDisFalg && item.isShow === true"
                      :active-value="true"
                      :inactive-value="false"
                      :width="30"
                    ></el-switch
                  ></span>
                </li>
              </ul>
              <el-button slot="reference" type="primary" icon="el-icon-s-tools" plain size="mini">字段设置</el-button>
            </el-popover>
            <el-popover placement="bottom" width="60" trigger="click">
              <ul class="el-select-dropdown__list">
                <li :class="[tableSpacing === 1 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="tableSpacingChange(1)">
                  <span style="float: left">紧凑</span><span v-if="tableSpacing === 1" style="float: right"><i class="el-icon-check"></i></span>
                </li>
                <li :class="[tableSpacing === 2 ? 'freezeClass' : '', 'el-select-dropdown__item']" @click="tableSpacingChange(2)">
                  <span style="float: left">宽松</span><span v-if="tableSpacing === 2" style="float: right"><i class="el-icon-check"></i></span>
                </li>
              </ul>
              <el-button slot="reference" type="primary" icon="el-icon-set-up" plain size="mini" style="margin: 0 10px"> {{ tableSpacing === 1 ? '紧凑' : '宽松' }}</el-button>
            </el-popover>
          </div>
          <!--          <div v-else>-->
          <!--            <el-button :type="i == 0 ? 'primary' : 'text'" :icon="item.icon" v-has="'btn_' + item.value" @click="headBtnsHandel(item.value)" v-for="(item, i) in columnData.btnsList" :key="i">-->
          <!--              {{ item.label }}-->
          <!--            </el-button>-->
          <!--          </div>-->
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">
              <!--              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset()" />-->
            </el-tooltip>
            <screenfull />
          </div>
        </div>
        <!--        @row-dblclick="dbclick"-->
        <JNPF-table
          ref="PcListTable"
          :show-summary="columnData.showSummary"
          :summary-method="getSummaries"
          :cell-class-name="tableCellClassName"
          v-loading="listLoading"
          :data="list"
          row-key="id"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: '' }"
          @sort-change="sortChange"
          :has-c="hasBatchBtn"
          @selection-change="handleSelectionChange"
          v-if="refreshTable"
        >
          <!--          :prop="item.prop"-->
          <template v-for="(item, i) in columnList">
            <el-table-column
              v-if="showColumn(item.propId)"
              :label="item.label"
              :show-overflow-tooltip="tableSpacing === 1"
              :align="item.align"
              :min-width="100"
              :width="tableSpacing === 1 ? flexColumnWidth(String(item.propId), list) : 'auto'"
              :prop="String(item.propId)"
              :key="i"
              :sortable="item.sortable ? 'custom' : item.sortable"
              :fixed="i + 1 <= isFreeze ? 'left' : false"
            >
              <template slot-scope="scope">
                <!--              选中此行-->
                <div v-if="scope.row.inputShow == true && valueIndex == scope.$index && itemLabel == scope.column.label">
                  <template v-if="item.label == itemLabel && (item.jnpfKey == 'date' || item.jnpfKey == 'datetime')">
                    <!--                  show-overflow-tooltip设置的显示tooltip内容只作用到下一级的div内容。这样就无法作用到文字上 在插槽中加入文字，并将其隐藏，气泡功能就恢复正常了-->
                    <span style="display: block; overflow: hidden; height: 0">{{ getSetData(scope.row[columnDict[item.propId]], item.propId, 'format') }}</span>
                    <el-date-picker
                      style="width: 120px"
                      size="small"
                      v-model="scope.row[columnDict[item.propId]]"
                      :type="item.jnpfKey"
                      :format="getFormat(item.propId, 'format')"
                      :value-format="getvalueFormat(item.propId, 'value-format')"
                      placeholder="选择日期时间"
                      :disabled="getDisabled(item.propId)"
                      :key="scope.row[columnDict[idKey]]"
                    ></el-date-picker>
                  </template>
                  <template v-if="item.label == itemLabel && (item.jnpfKey == 'comInput' || item.jnpfKey == 'numInput' || item.jnpfKey == 'textarea')">
                    <span style="display: block; overflow: hidden; height: 0">{{ scope.row[columnDict[item.propId]] }}</span>
                    <el-input
                      v-model="scope.row[columnDict[item.propId]]"
                      :key="scope.row[columnDict[idKey]]"
                      :type="item.jnpfKey == 'comInput' || item.jnpfKey == 'textarea' ? 'text' : 'number'"
                      :disabled="getDisabled(item.propId)"
                    ></el-input>
                  </template>
                  <!-- <el-input v-if="item.label == itemLabel && item.jnpfKey == 'numInput'" v-model="scope.row[columnDict[item.propId]]" type="number"></el-input> -->
                  <template v-if="item.label == itemLabel && (item.jnpfKey == 'radio' || item.jnpfKey == 'select')">
                    <span style="display: block; overflow: hidden; height: 0">{{ scope.row[columnDict[item.propId]] }}</span>
                    <el-select :multiple="item.jnpfKey == 'checkbox'" v-model="scope.row[columnDict[item.propId]]" :disabled="getDisabled(item.propId)" :key="scope.row[columnDict[idKey]]">
                      <el-option v-for="item in getOption(item.jnpfKey, item.propId)" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
                    </el-select>
                  </template>
                  <template v-if="item.label == itemLabel && item.jnpfKey == 'checkbox'">
                    <span style="display: block; overflow: hidden; height: 0">{{ scope.row[columnDict[item.propId]] }}</span>
                    <el-select
                      :multiple="item.jnpfKey == 'checkbox'"
                      :key="scope.row[columnDict[idKey]]"
                      @change="scope.row[columnDict[item.propId]] = JSON.stringify($event)"
                      v-model="scope.row[columnDict[item.propId]]"
                      :disabled="getDisabled(item.propId)"
                    >
                      <el-option v-for="item in getOption(item.jnpfKey, item.propId)" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
                    </el-select>
                  </template>
                  <template v-if="item.label == itemLabel && item.jnpfKey == 'switch'">
                    <span style="display: block; overflow: hidden; height: 0">{{ scope.row[columnDict[item.propId]] }}</span>
                    <el-switch :disabled="getDisabled(item.propId)" :key="scope.row[columnDict[idKey]]" v-model="scope.row[columnDict[item.propId]]" active-value="1" inactive-value="0"></el-switch>
                  </template>
                  <template v-if="item.label == itemLabel && item.jnpfKey == 'cascader'">
                    <span style="display: block; overflow: hidden; height: 0">{{ scope.row[columnDict[item.propId]] }}</span>
                    <el-cascader
                      v-model="scope.row[columnDict[item.propId]]"
                      :key="scope.row[columnDict[idKey]]"
                      :props="{ value: 'id', label: 'fullName', children: 'children' }"
                      :options="getOption(item.jnpfKey, item.propId)"
                      @change="scope.row[columnDict[item.propId]] = JSON.stringify($event)"
                      :disabled="getDisabled(item.propId)"
                    >
                    </el-cascader>
                  </template>
                  <span v-show="relationFlag" title="选择关联数据" @click="relationBoxclick(item.propId, scope.row[columnDict[idKey]])">
                    <i class="el-icon-copy-document" />
                  </span>
                </div>
                <!--              未选中-->
                <div v-else class="templateVal" @mouseover="mouseOver(scope.row[columnDict[item.propId]], scope, item.label, item.propId)">
                  <!--                如果有值-->
                  <div v-if="scope.row[columnDict[item.propId]] || scope.row[columnDict[item.propId]] === 0">
                    <!--                  判断类型-->
                    <div v-if="item.jnpfKey === 'numInput'">
                      {{ scope.row[columnDict[item.propId]] === 0 ? '0' : scope.row[columnDict[item.propId]] }}
                    </div>
                    <div v-else-if="item.jnpfKey === 'uploadImg' || item.jnpfKey === 'uploadFz'">
                      <template v-if="item.jnpfKey === 'uploadFz'">
                        <span style="color: #1890ff" v-for="(i, k) in getImgFun(scope.row[columnDict[item.propId]])" :key="k">{{ i.name }}</span>
                      </template>
                      <!--                    {{ getImgFun(scope.row[columnDict[item.propId]],item.jnpfKey) }}-->
                      <template v-else-if="getImgFun(scope.row[columnDict[item.propId]])[0].url">
                        <template v-for="(imgEle, imgKey) in getImgFun(scope.row[columnDict[item.propId]])">
                          <el-image
                            v-if="imgKey < 3"
                            :key="imgKey"
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="getImgUrl() + imgEle.url"
                            @click="imgShowClick(getImgFunList(scope.row[columnDict[item.propId]]))"
                          >
                          </el-image>
                        </template>
                        <el-tag style="vertical-align: text-bottom" v-if="getImgFun(scope.row[columnDict[item.propId]]).length > 3" type="info">
                          + {{ getImgFun(scope.row[columnDict[item.propId]]).length - 3 }}</el-tag
                        >
                      </template>
                      <span v-else>{{ scope.row[columnDict[item.propId]] }}</span>
                    </div>
                    <div v-else-if="item.jnpfKey === 'switch'">
                      <el-switch disabled v-model="scope.row[columnDict[item.propId]]" active-value="1" inactive-value="0"></el-switch>
                    </div>
                    <div :class="[tableSpacing === 1 ? 'table_cell_clamp' : '']" v-else-if="item.jnpfKey === 'radio' || item.jnpfKey === 'select' || item.jnpfKey === 'checkbox'">
                      {{ getOptionData(scope.row[columnDict[item.propId]], item.propId) }}
                    </div>
                    <div v-else-if="item.jnpfKey === 'date' || item.jnpfKey === 'datetime'">
                      {{ getSetData(scope.row[columnDict[item.propId]], item.propId, 'format') }}
                    </div>
                    <div :class="[tableSpacing === 1 ? 'table_cell_clamp' : '']" v-else>
                      {{ scope.row[columnDict[item.propId]] }}
                    </div>
                    <!--                  <div class="iconEdit" v-if="value === scope.row[columnDict[item.propId]] && valueIndex === scope.$index && itemLabel === scope.column.label && !getDisabled(item.propId)">-->
                    <!--                    <i class="el-icon-edit" @click="inputClick(scope.row[columnDict[item.propId]],scope)"></i>-->
                    <!--                  </div>-->
                  </div>
                  <div v-else>
                    <div v-if="item.jnpfKey === 'numInput'">
                      {{ scope.row[columnDict[item.propId]] === 0 ? '0' : scope.row[columnDict[item.propId]] }}
                    </div>
                    <!--                  <div class="iconEdit" v-if="columnData.columnBtnsList.length>0">-->
                    <!--                    <i class="el-icon-edit" @click="inputClick(scope.row[columnDict[item.propId]],scope)"></i>-->
                    <!--                  </div>-->
                  </div>
                </div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="flowState" label="状态" width="100" v-if="config.webType == 3">
            <template slot-scope="scope" v-if="!scope.row.top">
              <el-tag v-if="scope.row.flowState == 1">等待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.flowState == 2">审核通过</el-tag>
              <el-tag type="danger" v-else-if="scope.row.flowState == 3">审核驳回</el-tag>
              <el-tag type="danger" v-else-if="scope.row.flowState == 4">流程撤回</el-tag>
              <el-tag type="warning" v-else-if="scope.row.flowState == 5">审核终止</el-tag>
              <el-tag type="info" v-else>等待提交</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            :width="columnData.columnBtnsList.length > 1 ? columnData.columnBtnsList.length * 50 : columnData.columnBtnsList.length * 100"
            v-if="columnData.columnBtnsList.length"
          >
            <template slot-scope="scope" v-if="!scope.row.top">
              <template v-if="isPreview || !columnData.useBtnPermission">
                <div v-if="scope.row.inputShow == true">
                  <el-button
                    type="primary"
                    :disabled="config.webType == 3 && [1, 2, 5].indexOf(scope.row.flowState) > -1"
                    size="mini"
                    circle
                    plain
                    icon="el-icon-check"
                    @click="successClick(scope)"
                  ></el-button>
                  <el-button type="danger" size="mini" circle plain icon="el-icon-delete" @click="closeInput(scope)"></el-button>
                </div>
                <div v-else style="display: flex">
                  <template v-for="(item, i) in columnData.columnBtnsList">
                    <template v-if="item.value == 'edit'">
                      <el-button size="mini" type="text" :key="i" :disabled="config.webType == 3 && [1, 2, 5].indexOf(scope.row.flowState) > -1" @click="columnBtnsHandel(item.value, scope.row)">{{
                        item.label
                      }}</el-button>
                    </template>
                    <template v-if="item.value == 'remove'">
                      <el-button
                        size="mini"
                        type="text"
                        :key="i"
                        class="JNPF-table-delBtn"
                        :disabled="config.webType == 3 && [1, 2, 3, 5].indexOf(scope.row.flowState) > -1"
                        @click="columnBtnsHandel(item.value, scope.row)"
                        >{{ item.label }}</el-button
                      >
                    </template>
                    <template v-if="item.value == 'detail'">
                      <el-button size="mini" type="text" :key="i" :disabled="config.webType == 3 && !scope.row.flowState" @click="columnBtnsHandel(item.value, scope.row)">{{ item.label }}</el-button>
                    </template>
                    <template v-if="item.value == 'rowJournal'">
                      <el-button size="mini" type="text" :key="i" :disabled="config.webType == 3 && !scope.row.flowState" @click="columnBtnsHandel(item.value, scope.row)">{{ item.label }}</el-button>
                    </template>
                  </template>
                </div>
              </template>
              <template v-else>
                <template v-for="(item, i) in columnData.columnBtnsList">
                  <template v-if="item.value == 'edit'">
                    <el-button
                      size="mini"
                      type="text"
                      :key="i"
                      :disabled="config.webType == 3 && [1, 2, 5].indexOf(scope.row.flowState) > -1"
                      @click="columnBtnsHandel(item.value, scope.row)"
                      v-has="'btn_' + item.value"
                      >{{ item.label }}
                    </el-button>
                  </template>
                  <template v-if="item.value == 'remove'">
                    <el-button
                      size="mini"
                      type="text"
                      :key="i"
                      class="JNPF-table-delBtn"
                      :disabled="config.webType == 3 && [1, 2, 3, 5].indexOf(scope.row.flowState) > -1"
                      @click="columnBtnsHandel(item.value, scope.row)"
                      v-has="'btn_' + item.value"
                      >{{ item.label }}
                    </el-button>
                  </template>
                  <template v-if="item.value == 'detail'">
                    <el-button size="mini" type="text" :key="i" :disabled="config.webType == 3 && !scope.row.flowState" @click="columnBtnsHandel(item.value, scope.row)" v-has="'btn_' + item.value">
                      {{ item.label }}
                    </el-button>
                  </template>
                </template>
              </template>
            </template>
          </el-table-column>
        </JNPF-table>
        <template v-if="columnData.type !== 3 && columnData.hasPage">
          <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
        </template>
      </div>
    </div>
    <!--    轮播图-->
    <swiperWrapper v-if="imgShowVisible" @swiperclose="thumbsclose" ref="imgShowView" />

    <!--    流程-->
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />

    <!--    新增/删除-->
    <Form v-show="formVisible" :relation-data="relationData" ref="Form" @refreshDataList="refresh" />

    <!--    详情-->
    <Detail v-show="detailVisible" ref="Detail" @close="detailVisible = false" />

    <!--    导出-->
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />

    <!--    导入-->
    <UploadBox v-if="uploadBoxVisible" ref="UploadBox" @UploadChange="UploadChange" />

    <!--    修改记录-->
    <journal :config="columnData.columnList" :modelId="this.modelId" v-show="journalBoxVisible" ref="journalBox" @close="journalBoxVisible = false" />

    <!--   导出日志 -->
    <exportListBox :modelId="this.modelId" v-show="exportListBoxVisible" ref="exportListBox" @close="exportListBoxVisible = false" />

    <!--   导入日志 -->
    <uploadListBox :modelId="this.modelId" :assemblyOptions="this.assemblyOptions" v-show="uploadListBoxVisible" ref="uploadListBox" @close="uploadListBoxVisible = false" />

    <!--    回收站-->
    <recycleList
      :formData="formData"
      :config="columnData.columnList"
      :modelId="this.modelId"
      :assemblyOptions="this.assemblyOptions"
      v-show="recycleListBoxVisible"
      ref="recycleListBox"
      @recycleDataList="initData()"
      @editCurrent="recycleDetail"
      @close="recycleListBoxVisible = false"
    />

    <!--    批量编辑-->
    <batchEdit :modelId="this.modelId" v-show="batchEditBoxVisible" ref="batchEditListBox" @close="batchEditBoxVisible = false" @batchEditDataList="initData()" @refreshDataList="refresh" />

    <!--    关联组件-->
    <RelationForm v-show="RelationBoxVisible" :relationConf="relationData" @changeRow="changeElRowClick" ref="relationBox" @close="RelationBoxVisible = false" />
  </div>
</template>

<script>
import { batchDelete, deteleModel, exportModel, getBrowserData, getModePerm, updateModel, uploadModel } from '@/api/onlineDev/visualDev'
import { deepClone } from '@/utils'
import { previewDataInterface } from '@/api/systemData/dataInterface'
import Form from './Form'
import FlowBox from '@/views/workFlow/components/FlowBox'
import Detail from './detail'
import ExportBox from './ExportBox'
import UploadBox from './UploadBox'
import Search from './Search'
import journal from './journal'
import exportListBox from './exportList'
import uploadListBox from './uploadList'
import recycleList from './recycleList'
import batchEdit from './batchEdit'
import topForm from './topForm'
import moment from 'moment'
import { dictDetail } from '@/api/newbi/dict'
import RelationForm from '@/components/Generator/components/RelationForm'
import swiperWrapper from './../components/swiperWrapper'
export default {
  name: 'dynamicModel',
  components: {
    Form,
    ExportBox,
    Search,
    Detail,
    FlowBox,
    UploadBox,
    journal,
    exportListBox,
    uploadListBox,
    recycleList,
    batchEdit,
    RelationForm,
    swiperWrapper,
    topForm
  },
  props: ['config', 'modelId'],
  data() {
    return {
      btnsOption: [
        { value: 'add', icon: 'el-icon-plus', label: '新增' },
        { value: 'download', icon: 'el-icon-download', label: '导出' },
        { value: 'batchUpload', icon: 'el-icon-upload2', label: '批量导入' },
        { value: 'batchUpdate', icon: 'el-icon-edit-outline', label: '批量编辑' },
        { value: 'batchRemove', icon: 'el-icon-delete', label: '批量删除' },
        { value: 'recycle', icon: 'el-icon-delete', label: '回收站' },
        { value: 'journal', icon: 'el-icon-date', label: '操作日志' }
      ],
      columnBtnsOption: [
        { value: 'edit', icon: 'el-icon-edit', label: '编辑' },
        { value: 'remove', icon: 'el-icon-delete', label: '删除' },
        { value: 'detail', icon: 'el-icon-tickets', label: '详情' },
        { value: 'rowJournal', icon: 'el-icon-date', label: '操作记录' }
      ],
      functionBtnsOption: [
        { value: 'uploadRevoke', icon: 'el-icon-refresh-left', label: '导入撤销' },
        { value: 'comDelete', icon: 'el-icon-delete', label: '彻底删除' }
      ],
      assemblyOptions: [],
      isPreview: false,
      keyword: '',
      treeProps: {
        children: 'children',
        label: 'fullName',
        value: 'enCode'
      },
      list: [],
      columnDict: {},
      idKey: this.config.idKey,
      total: 0,
      listLoading: false,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'descs',
        sidx: this.config.idKey,
        json: ''
      },
      imgShowVisible: false,
      flowVisible: false,
      formVisible: false,
      detailVisible: false,
      importBoxVisible: false,
      exportBoxVisible: false,
      uploadBoxVisible: false,
      journalBoxVisible: false,
      exportListBoxVisible: false,
      uploadListBoxVisible: false,
      recycleListBoxVisible: false,
      batchEditBoxVisible: false,
      RelationBoxVisible: false,
      treeData: [],
      treeActiveId: '',
      columnData: {
        columnBtnsList: []
      },
      formData: {},
      columnList: [],
      relationData: [],
      relationConfCopy: [],
      relationFlag: false,
      hasBatchBtn: false,
      refreshTable: true,
      multipleSelection: [],
      multipleSelectionDelectData: [],
      value: '',
      valueIndex: -1,
      itemLabel: '',
      oldList: [],
      oldData: null,
      btnArr: [],
      optionList: [],
      checkboxVal: null,
      cascaderVal: null,
      isFreeze: 1,
      isShowFalg: 1,
      isShowDisFalg: false,
      tableSpacing: 1
    }
  },
  created() {
    this.init()
  },
  methods: {
    //触发关联按钮
    relationBoxclick(id, keyId) {
      this.relationConfCopy = deepClone(this.relationData)
      this.relationConfCopy.forEach((i, k) => {
        i.relationList.forEach((v, x) => {
          if (v.drawId === id) {
            this.RelationBoxVisible = true
            this.$refs.relationBox.getData(i.relationName, i.fieldName, i.fieldList, keyId)
          }
        })
      })
    },
    //关联回调
    changeElRowClick(row) {
      let { id, keyId, jsonData } = row
      this.relationConfCopy = deepClone(this.relationData)
      //过滤出当前修改row
      let editRow = this.list.filter((cur) => cur[this.columnDict[this.idKey]] === keyId)
      if (!editRow && !editRow.length) return
      this.relationConfCopy.forEach((i, k) => {
        if (i.relationName === id) {
          i.relationList.forEach((v, o) => {
            //时间类型特殊转换
            this.formData.fields.forEach((c, b) => {
              if (v.fieldId && v.drawId === c.__vModel__) {
                if (c.__config__.viewDataType === 'DATETIME') {
                  jsonData[v.fieldId] = moment(jsonData[v.fieldId]).valueOf()
                }
              }
            })
            editRow[0][this.columnDict[v.drawId]] = jsonData[v.fieldId]
          })
        }
      })
      this.$refs.relationBox.visible = false
      this.RelationBoxVisible = false
    },
    //自适应列宽度
    flexColumnWidth(str, tableData, flag = 'max') {
      // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
      // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
      // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
      let DelectData = deepClone(tableData)
      let jsonData = DelectData.map((i) => {
        return this.getBatchEditJsonData(i)
      })
      str = str + ''
      let columnContent = ''
      if (!jsonData || !jsonData.length || jsonData.length === 0) {
        return
      }
      if (!str || !str.length || str.length === 0) {
        return
      }
      if (flag === 'equal') {
        // 获取该列中第一个不为空的数据(内容)
        for (let i = 0; i < jsonData.length; i++) {
          if (jsonData[i][str].length > 0) {
            // console.log('该列数据[0]:', tableData[0][str])
            columnContent = jsonData[i][str]
            break
          }
        }
      } else {
        // 获取该列中最长的数据(内容)
        let index = 0
        for (let i = 0; i < jsonData.length; i++) {
          if (jsonData[i][str] !== null) {
            const now_temp = jsonData[i][str] + ''
            const max_temp = jsonData[index][str] + ''
            if (now_temp.length > max_temp.length) {
              index = i
            }
          }
        }
        columnContent = jsonData[index][str]
      }
      // 以下分配的单位长度可根据实际需求进行调整
      let flexWidth = 0
      if (columnContent) {
        for (let char of JSON.stringify(columnContent)) {
          if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
            // 如果是英文字符，为字符分配10个单位宽度
            flexWidth += 10
          } else if (char >= '\u4e00' && char <= '\u9fa5') {
            // 如果是中文字符，为字符分配15个单位宽度
            flexWidth += 15
          } else {
            // 其他种类字符，为字符分配9个单位宽度
            flexWidth += 10
          }
        }
      }
      if (flexWidth < 80) {
        // 设置最小宽度
        flexWidth = 100
        return 'auto'
      }
      if (flexWidth > 160 && flexWidth < 250) {
        // 设置最大宽度
        flexWidth = 150
        return flexWidth + 'px'
      }
      if (flexWidth > 250) {
        // 设置最大宽度
        flexWidth = 250
        return flexWidth + 'px'
      }

      // }else {
      //   return 'auto'
      // }
    },
    successClick(scope) {
      let rows = Object.assign({}, scope.row)
      delete scope.row.inputShow
      let item = this.columnList
      let editList = deepClone(this.columnDict)
      delete editList[this.idKey]
      // item.forEach((val) => {
      //   if (val.jnpfKey == 'date' || val.jnpfKey == 'datetime') {
      //     scope.row[this.columnDict[val.propId]] = String(
      //       new Date(scope.row[this.columnDict[val.propId]]).getTime()
      //     )
      //   }
      // })
      let id = scope.row ? scope.row[this.columnDict[this.idKey]] : ''
      for (let key in editList) {
        for (let index in rows) {
          if (editList[key] === index) {
            editList[key] = rows[index]
          }
        }
      }
      Object.keys(editList).forEach((item) => {
        if (typeof editList[item] === 'undefined' || editList[item] === null) {
          delete editList[item]
        }
      })
      Object.keys(this.oldData).forEach((item) => {
        if (typeof this.oldData[item] === 'undefined' || this.oldData[item] === null) {
          delete this.oldData[item]
        }
      })
      let dataForm = {
        data: JSON.stringify(editList),
        oldData: this.oldData ? JSON.stringify(this.oldData) : '',
        id: id
      }
      updateModel(this.modelId, [dataForm], dataForm.id)
        .then((res) => {
          this.$message({
            message: res.data.msg,
            type: 'success',
            duration: 1500
          })
          this.initData()
        })
        .catch((err) => {
          this.initData()
        })
    },
    closeInput(scope) {
      let olds = Object.assign(this.oldList[scope.$index], {
        inputShow: false
      })
      this.oldData = null
      this.$set(this.list, scope.$index, olds)
      this.columnData.columnBtnsList = this.btnArr
      this.initData()
    },
    getdateMoment(list) {
      if (list && Object.prototype.toString.call(list)) {
        let arr = Object.keys(list)
        let arrs = []
        this.formData.fields.forEach((item, index) => {
          //查找表单设计时 哪些组件控件为时间类型 与编辑行匹配
          if (arr.includes(String(item.__vModel__)) && item.__config__.viewDataType === 'DATETIME') {
            //将时间类型的数据改为时间戳
            list[item.__vModel__] = moment(list[item.__vModel__]).valueOf()
            arrs = list
            //修改表格绑定list中时间选择控件需要的format类型
            this.columnList.forEach((val, key) => {
              if (val.propId === item.__vModel__) {
                val.format = item.format
                val['value-format'] = item['value-format']
              }
            })
          }
        })
        return arrs
      }
    },
    //下拉属性的组件  如果key和value值不相同 查询title
    getOptionData(v, id) {
      let list = []
      let str = v
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          list = item.__slot__.options
        }
      })
      if (list.length) {
        let obj = list.find((i) => i.id == v)
        if (obj) str = obj.fullName
      }
      return str
    },
    //获取下拉框值
    getOption(key, id) {
      let list = []
      if (key === 'radio' || key === 'select' || key === 'checkbox') {
        this.formData.fields.forEach((item) => {
          if (item.__vModel__ === id) {
            list = item.__slot__.options
          }
        })
      }
      if (key === 'cascader') {
        this.formData.fields.forEach((item) => {
          if (item.__vModel__ === id) {
            list = item.options
          }
        })
      }
      return list
    },
    //如有主键或计算字段之类 要禁用
    getDisabled(id) {
      let ItemDisabled = false
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          ItemDisabled = item.disabled
        }
      })
      return ItemDisabled
    },
    //获取时间值类型
    getFormat(id, type) {
      let str
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          if (type === 'format') {
            str = item.format
          }
        }
      })
      return str
    },
    getvalueFormat(id, type) {
      let str
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          if (type === 'value-format') {
            str = item['value-format']
          }
        }
      })
      return str
    },
    getSetData(val, propId, type) {
      let str = this.getFormat(propId, type)
      if (str === 'yyyy-MM-dd') {
        str = 'yyyy-MM-DD'
      } else if (str === 'yyyy-MM-dd HH:mm:ss') {
        str = 'yyyy-MM-DD HH:mm:ss'
      }
      return moment(val).format(str)
    },
    // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex
      column.index = columnIndex
    },
    //双击行内修改 获得当前双击的单元格的值
    dbclick(row, column, event) {
      this.columnInFun(this.columnDict[column.property], row)
      this.oldList[row.index] = JSON.parse(JSON.stringify(row))
    },
    //按钮点击行内修改
    inputClick(value, scope) {
      this.columnInFun(value, scope.row)
      this.oldList[scope.$index] = JSON.parse(JSON.stringify(scope.row))
      // this.formData.fields.forEach(val => {
      //   if (val.__config__.jnpfKey == 'cascader') {
      //     this.optionList = val.options
      //   } else if (val.__config__.jnpfKey == 'switch') {
      //     this.optionList = []
      //   } else {
      //     if (val.__slot__) {
      //       if (val.__config__.label == scope.column.label) {
      //         this.optionList = val.__slot__.options
      //       }
      //     }
      //   }
      // })
      // this.columnList.forEach(item => {
      //   if (item.label == scope.column.label && item.jnpfKey == 'checkbox') {
      //     if (value.indexOf('[') != -1) {
      //       this.checkboxVal = JSON.parse(value)
      //     } else {
      //       this.checkboxVal = null
      //     }
      //   } else if (item.label == scope.column.label && item.jnpfKey == 'cascader') {
      //     if (value.indexOf('[') != -1) {
      //       this.cascaderVal = JSON.parse(value)
      //     } else {
      //       this.cascaderVal = null
      //     }
      //
      //   }
      // })
    },
    //行内编辑时  数据整理
    columnInFun(value, row) {
      let rows = Object.assign({}, row)
      let editList = deepClone(this.columnDict)
      let editrowList = deepClone(this.columnDict)
      delete editList[this.idKey]
      //整理提交旧数据
      for (let key in editList) {
        for (let index in rows) {
          if (editList[key] === index) {
            editList[key] = rows[index]
          }
        }
      }
      this.oldData = this.getdateMoment(editList)
      row.inputShow = true
      let arr = Object.keys(editrowList)
      this.formData.fields.forEach((item, index) => {
        //查找表单设计时 哪些组件控件为时间类型 与编辑行匹配
        if (arr.includes(String(item.__vModel__)) && item.__config__.viewDataType === 'DATETIME') {
          //将时间类型的数据改为时间戳
          row[this.columnDict[item.__vModel__]] = moment(row[this.columnDict[item.__vModel__]]).valueOf()
        }
      })
    },
    mouseOver(val, scope, itemLabel, propId) {
      this.value = val
      this.valueIndex = scope.$index
      this.itemLabel = itemLabel
      this.relationConfCopy = deepClone(this.relationData)
      let str = this.relationConfCopy
        .map((item) => item.relationList)
        .flat()
        .find((item) => item.drawId === propId)
      this.relationFlag = !!(str && str.drawId === propId)
      // if (scope.row.inputShow == true) {
      //   this.formData.fields.forEach(item => {
      //     if (item.__config__.jnpfKey == 'cascader') {
      //       this.optionList = item.options
      //     } else if (item.__config__.jnpfKey == 'switch') {
      //       this.optionList = []
      //     } else {
      //       if (item.__slot__) {
      //         if (item.__config__.label == scope.column.label) {
      //           this.optionList = item.__slot__.options
      //         }
      //       }
      //     }
      //   })
      //   this.columnList.forEach(item => {
      //     if (item.label == scope.column.label && item.jnpfKey == 'checkbox') {
      //       if (val.indexOf('[') != -1) {
      //         this.checkboxVal = JSON.parse(val)
      //       } else {
      //         this.checkboxVal = null
      //       }
      //     } else if (item.label == scope.column.label && item.jnpfKey == 'cascader') {
      //       // this.cascaderVal = JSON.parse(val)
      //       if (val.indexOf('[') != -1) {
      //         this.cascaderVal = JSON.parse(val)
      //       } else {
      //         this.cascaderVal = null
      //       }
      //     }
      //   })
      // }
    },
    init() {
      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)
      // console.log(this.formData.fields[0].__slot__.options)
      this.getColumnList()
      if (this.isPreview) return
      this.listQuery.pageSize = this.columnData.pageSize
      this.listQuery.sort = this.columnData.sort
      this.listQuery.sidx = this.columnData.defaultSidx
      if (this.columnData.type === 3 || !this.columnData.hasPage) this.listQuery.pageSize = 10000
      if (this.columnData.type === 2) {
        this.treeProps.value = this.columnData.treePropsValue || 'id'
        this.treeProps.label = this.columnData.treePropsLabel || 'fullName'
        this.treeProps.children = this.columnData.treePropsChildren || 'children'
        this.getTreeView()
      } else {
        //请求权限 列表 直接看这一条 从搜索组件调用
        // this.initData()
      }
      // console.log(this.columnData)
    },
    initData() {
      if (this.isPreview) return
      this.listLoading = true
      //获取按钮权限
      getModePerm(this.modelId).then((res) => {
        let newArr = res.data.data.filter(function (item, index) {
          return res.data.data.indexOf(item) === index // 去重
        })
        this.columnData.btnsList = this.btnsOption
          .map((i, k) => {
            if (newArr.includes(i.value)) {
              return i
            }
          })
          .filter((l) => l !== undefined)
        this.hasBatchBtn = this.columnData.btnsList.some((o) => o.value == 'batchRemove')
        this.$nextTick(() => {
          this.refreshTable = true
        })
        this.columnData.columnBtnsList = this.columnBtnsOption
          .map((i, k) => {
            if (newArr.includes(i.value)) {
              return i
            }
          })
          .filter((l) => l !== undefined)
        // console.log(this.columnData);
        this.btnArr = this.columnData.columnBtnsList.concat()
        this.assemblyOptions = this.functionBtnsOption
          .map((i, k) => {
            if (newArr.includes(i.value)) {
              return i.value
            }
          })
          .filter((l) => l !== undefined)
      })
      //获取列表数据
      function NewObj(key, vlaue) {
        this[key] = vlaue
      }
      let obj = new NewObj(this.listQuery.sort, this.listQuery.sidx)
      let parmes = {
        pageQuery: {
          current: this.listQuery.currentPage,
          size: this.listQuery.pageSize
        },
        paramList: this.listQuery.json ? this.listQuery.json : []
      }
      Object.assign(parmes.pageQuery, obj)
      //获取数据权限过滤列表
      getBrowserData(this.config.dbLinkId, parmes).then((res) => {
        //可显示的列
        this.columnDict = res.data.data.columnDict
        let columnDict = Object.keys(res.data.data.columnDict)
        //过滤掉不可显示的列
        this.columnList = this.columnList
          .map((i) => {
            if (columnDict.includes(String(i.propId))) {
              return i
            }
          })
          .filter((l) => l !== undefined)
        this.columnList.forEach((item, k) => {
          this.$set(this.columnList[k], 'isShow', true)
        })
        this.list = res.data.data.pageData.records.map((v, i, a) => {
          v.inputShow = false
          return v
        })
        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
        if (this.columnData.type === 4) {
          this.$nextTick(() => {
            this.$refs.topForm.init(this.formData, this.modelId, this.isPreview, this.idKey)
          })
        }
        this.listLoading = false
      })
      // getModelList(this.modelId, this.listQuery).then(res => {
      // this.list = res.data.data.records.map((v, i, a) => {
      //   v.inputShow = false
      //   return v
      // })
      // this.idKey = res.data.ext.idKey
      // })
    },
    //合并排序对象组合
    // getNewObj(key,vlaue){
    //   return this[key] = vlaue
    // },
    // 表格列是否显示的方法
    showColumn(currentColumn) {
      return this.columnList.find((item) => item.propId === currentColumn).isShow
    },
    // 重新渲染表格
    refreshTableLayout(id) {
      if (this.columnList.every((target) => target.isShow === true)) {
        this.isShowFalg = 1
      } else {
        this.isShowFalg = 2
      }
      if (this.columnList.every((target) => target.isShow === false)) {
        this.isShowDisFalg = true
        this.columnList.forEach((item) => {
          if (item.propId === id) {
            item.isShow = true
          }
        })
      } else {
        this.isShowDisFalg = false
      }
      let trueData = this.getEleNums(this.columnList)
      this.isShowDisFalg = trueData.true <= 1
      this.$nextTick(() => {
        this.$refs.PcListTable.doLayout()
      })
    },
    //获取当前展示和未展示的表头次数
    getEleNums(data) {
      let map = {}
      for (let i = 0; i < data.length; i++) {
        let key = data[i].isShow
        if (map[key]) {
          map[key] += 1
        } else {
          map[key] = 1
        }
      }
      return map
    },
    //全选或非全选
    checkAllChangeFn(val) {
      if (val) {
        this.resetTableTitle(true)
      } else {
        const user = this.columnList.find((item) => {
          return item.isShow === true
        })
        this.resetTableTitle(false, user.propId)
      }
    },
    resetTableTitle(flag, id) {
      this.columnList.forEach((item) => {
        item.isShow = flag
      })
      this.refreshTableLayout(id)
    },
    tableSpacingChange(value) {
      this.tableSpacing = value
      this.listLoading = true
      this.$nextTick(() => {
        this.$refs.PcListTable.doLayout()
        setTimeout(() => {
          this.listLoading = false
        }, 2000)
      })
    },
    //图片类型处理
    getImgFun(value) {
      try {
        const toObj = JSON.parse(value)
        if (Array.isArray(toObj) && toObj[0].url) {
          return toObj
        }
      } catch {}
      return value
    },
    getImgUrl() {
      let ImgUrl
      if (process.env.NODE_ENV === 'development') {
        ImgUrl = this.define.comUrl
      } else {
        ImgUrl = document.location.origin
      }
      return ImgUrl + '/'
    },
    getImgFunList(val) {
      const list = this.getImgFun(val)
      if (Array.isArray(list) && list.length)
        return list.map((i) => {
          let ImgUrl
          if (process.env.NODE_ENV === 'development') {
            ImgUrl = this.define.comUrl
          } else {
            ImgUrl = document.location.origin
          }
          return ImgUrl + '/' + i.url
        })
    },
    imgShowClick(list) {
      this.imgShowVisible = true
      this.$nextTick(() => {
        this.$refs.imgShowView.init(list)
      })
    },
    thumbsclose() {
      this.imgShowVisible = false
    },
    //查询对应的key值
    getListPropId(id) {
      if (this.list && this.list.length) {
        let arr = Object.keys(this.list[0])
        let PropId = arr.filter((o) => {
          if (Number(o) === id) {
            return o
          }
        })
        return PropId.toString()
      }
    },
    getTreeView() {
      if (this.columnData.treeDataSource === 'dictionary') {
        if (!this.columnData.treeDictionary) return
        dictDetail({ id: this.columnData.treeDictionary }).then((res) => {
          let content = JSON.parse(res.data.data.content || '[]')
          this.treeData = content.map((i) => ({ fullName: i.key, id: i.value }))
          // this.treeData = res.data.data.list
          this.initData()
        })
      }
      if (this.columnData.treeDataSource === 'organize') {
        this.$store.dispatch('generator/getCompanyTree').then((res) => {
          this.treeData = res
          this.initData()
        })
      }
      if (this.columnData.treeDataSource === 'department') {
        this.$store.dispatch('generator/getDepTree').then((res) => {
          this.treeData = res
          this.initData()
        })
      }
      if (this.columnData.treeDataSource === 'api') {
        if (!this.columnData.treePropsUrl) return
        previewDataInterface(this.columnData.treePropsUrl).then((res) => {
          if (Array.isArray(res.data)) {
            this.treeData = res.data
          } else {
            this.treeData = []
          }
          this.initData()
        })
      }
    },
    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
      }
    },
    handleNodeClick(data) {
      if (this.treeActiveId == data[this.treeProps.value]) return
      this.treeActiveId = data[this.treeProps.value]
      this.$refs.Search.treeReset()
      let obj = {}
      let arr = []
      this.columnData.cubeList.forEach((i, k) => {
        if (i.id === this.columnData.treeRelation) {
          obj.cubeColumnId = this.columnData.treeRelation
          obj.function = i.viewDataType === 'STRING' ? (i.function = 'eq') : i.viewDataType === 'NUMBER' ? (i.function = 'eq') : 'between'
          obj.values = [data[this.treeProps.value]]
          arr.push(obj)
        }
      })
      let json = JSON.stringify(arr) === '[]' ? [] : JSON.stringify(arr)
      this.search(json)
    },
    //整合数据 配合流程进行存储回显数据
    getFlowJsonData(row) {
      let rows = Object.assign({}, row)
      let jsonData = deepClone(this.columnDict)
      delete jsonData[this.idKey]
      for (let key in jsonData) {
        for (let index in rows) {
          if (jsonData[key] === index) {
            jsonData[key] = rows[index]
          }
        }
      }
      return jsonData
    },
    handleDel(row) {
      this.$confirm(this.$t('common.delTip'), this.$t('common.tipTitle'), {
        type: 'warning'
      })
        .then(async () => {
          let jsonData = this.getFlowJsonData(row)
          let dataJson = JSON.stringify(jsonData)
          const param = new URLSearchParams()
          param.append('dataJson', dataJson)
          const res = await deteleModel(this.modelId, row[this.columnDict[this.idKey]], param)
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1000,
              onClose: () => {
                this.initData()
              }
            })
          }
          // deteleModel(this.modelId, row[this.columnDict[this.idKey]],dataJson).then(
          //   (res) => {
          //
          //   }
          // )
        })
        .catch(() => {})
    },
    addOrUpdateHandle(row) {
      let id = row ? row[this.columnDict[this.idKey]] : ''
      if (this.config.webType == 3) {
        let data = {
          id: id || '',
          enCode: this.config.flowEnCode,
          flowId: this.config.flowId,
          formType: 2,
          type: 1,
          opType: '-1',
          modelId: this.modelId,
          isPreview: this.isPreview
        }
        this.flowVisible = true
        this.$nextTick(() => {
          this.$refs.FlowBox.init(data)
        })
      } else {
        this.formVisible = true
        this.$nextTick(() => {
          this.$refs.Form.init(this.formData, this.modelId, id, this.isPreview, row, this.idKey, this.columnDict)
        })
      }
    },
    headBtnsHandel(key) {
      if (key === 'add') {
        this.addOrUpdateHandle()
      }
      if (key === 'download') {
        this.exportBoxVisible = true
        this.$nextTick(() => {
          this.$refs.ExportBox.init(this.columnList)
        })
      }
      if (this.isPreview) return
      if (key === 'batchUpload') {
        this.uploadBoxVisible = true
        this.$nextTick(() => {
          let serialRow = this.formData.fields.find((o) => o.__config__.jnpfKey === 'serialNumber')
          this.$refs.UploadBox.init(this.columnList, this.config.dbLinkId, serialRow)
        })
      }
      if (key === 'batchRemove') {
        if (!this.idKey)
          return this.$message({
            message: '当前数据集暂无主键ID，不支持数据操作',
            type: 'warning'
          })
        this.batchRemove()
      }
      if (key === 'recycle') {
        this.recycleListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.recycleListBox.init(this.columnList, this.config.dbLinkId)
        })
      }
      if (key === 'batchUpdate') {
        if (!this.idKey)
          return this.$message({
            message: '当前数据集暂无主键ID，不支持数据操作',
            type: 'warning'
          })
        this.batchEdit()
      }
    },
    handleCommand(command) {
      if (command === 'exportList') {
        this.exportListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.exportListBox.init()
        })
      }
      if (command === 'uploadList') {
        this.uploadListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.uploadListBox.init()
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelectionDelectData = val
      this.multipleSelection = val.map((item) => item[this.columnDict[this.idKey]])
    },
    batchEdit() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请至少选择一条数据',
          duration: 1500
        })
        return
      }
      let DelectData = deepClone(this.multipleSelectionDelectData)
      let jsonData = DelectData.map((i) => {
        return this.getBatchEditJsonData(i)
      })
      let columnPropId = this.columnList.map((i) => {
        return i.propId
      })
      //将列表中不显示的数据过滤掉
      const filteredArr = jsonData.map((obj) => {
        const filteredObj = {}

        Object.keys(obj).forEach((key) => {
          if (Number(key) === this.idKey || columnPropId.includes(Number(key))) {
            filteredObj[key] = obj[key]
          }
        })

        return filteredObj
      })
      this.batchEditBoxVisible = true
      this.$nextTick(() => {
        this.$refs.batchEditListBox.init(this.formData, this.columnList, filteredArr, this.idKey)
      })
    },
    //整合数据 配合流程进行存储回显数据
    getBatchEditJsonData(row) {
      let rows = Object.assign({}, row)
      let jsonData = deepClone(this.columnDict)
      const obj_ = {}
      // delete jsonData[this.idKey]
      for (let key in jsonData) {
        for (let index in rows) {
          if (jsonData[key] === index) {
            // jsonData[key] = rows[index]
            obj_[key] = rows[index]
          }
        }
      }
      return obj_
    },
    batchRemove() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请至少选择一条数据',
          duration: 1500
        })
        return
      }
      let DelectData = deepClone(this.multipleSelectionDelectData)
      let jsonData = DelectData.map((i) => {
        return this.getFlowJsonData(i)
      })
      let dataJson = JSON.stringify(jsonData)
      this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
        type: 'warning'
      })
        .then(() => {
          batchDelete(this.modelId, this.multipleSelection, dataJson).then((res) => {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    download(data) {
      if (!this.idKey)
        return this.$message({
          message: '当前数据集暂无主键ID，不支持数据导出',
          type: 'warning'
        })
      if (!data.selectKey.length)
        return this.$message({
          message: '导出列字段不能为空',
          type: 'warning'
        })
      //all导出全部
      let all = data.dataType !== 0
      let columnIdList = data.selectKey
      //导出当前页
      let dataIdList = !all
        ? this.list.map((item) => {
            return item[this.columnDict[this.idKey]]
          })
        : null
      let downData = !all ? deepClone(this.list) : []
      let jsonData
      if (downData.length) {
        jsonData = downData.map((i) => {
          return this.getFlowJsonData(i)
        })
        //讲未勾选导出的数据过滤
        jsonData.forEach((i, k) => {
          jsonData[k] = Object.keys(i)
            .filter((key) => columnIdList.includes(Number(key)))
            .reduce((obj, key) => {
              obj[key] = i[key]
              return obj
            }, {})
        })
      }
      let dataJson = jsonData ? JSON.stringify(jsonData) : null
      let taskName = this.config.fullName + moment().format('YYYYMMDDHHmmss') + '导出列表数据'
      let modelId = this.modelId
      let query = {
        all,
        taskName,
        modelId,
        dataIdList,
        columnIdList,
        dataJson,
        currentPage: this.listQuery.currentPage,
        size: this.listQuery.pageSize,
        paramList: this.listQuery.json ? this.listQuery.json : []
      }
      exportModel(query).then((res) => {
        if (res.data.code === 200) {
          this.$message({ message: res.data.msg, type: 'success' })
          this.$refs.ExportBox.visible = false
          this.exportBoxVisible = false
          this.exportListBoxVisible = true
          this.$nextTick(() => {
            this.$refs.exportListBox.init()
          })
        }
      })
    },
    UploadChange(data) {
      if (this.isPreview)
        return this.$message({
          message: '功能预览不支持数据导出',
          type: 'warning'
        })
      let query = { modelId: this.modelId, ...data }
      uploadModel(query)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message({ message: res.data.msg, type: 'success' })
            this.$refs.UploadBox.visible = false
            this.$refs.UploadBox.btnLoading = false
            this.uploadBoxVisible = false
            this.$refs.Search.reset()
          } else {
            this.$refs.UploadBox.btnLoading = false
          }
        })
        .catch(() => {
          this.$refs.UploadBox.btnLoading = false
        })
    },
    //操作按钮
    columnBtnsHandel(key, row) {
      if (!this.idKey)
        return this.$message({
          message: '当前数据集暂无主键ID，不支持数据操作',
          type: 'warning'
        })
      if (key === 'edit') {
        this.addOrUpdateHandle(row)
      }
      if (key === 'detail') {
        this.goDetail(row)
      }
      if (key == 'remove') {
        this.handleDel(row)
      }
      if (key == 'rowJournal') {
        this.journalBoxVisible = true
        this.$nextTick(() => {
          this.$refs.journalBox.init(row[this.columnDict[this.idKey]])
        })
      }
    },
    //回收站点击行显示详情数据
    recycleDetail(columnData) {
      let key = Object.keys(columnData)
      this.goDetail(columnData[key[0]][0])
    },
    //详情
    goDetail(row, flowState) {
      if (this.config.webType == 3) {
        let data = {
          id: row[this.idKey],
          enCode: this.config.flowEnCode,
          flowId: this.config.flowId,
          formType: 2,
          type: 1,
          opType: 0,
          modelId: this.modelId,
          isPreview: this.isPreview,
          status: flowState
        }
        this.flowVisible = true
        this.$nextTick(() => {
          this.$refs.FlowBox.init(data)
        })
      } else {
        this.detailVisible = true
        this.$nextTick(() => {
          this.$refs.Detail.init(this.formData, this.modelId, row, row[this.columnDict[this.idKey]], this.columnDict)
        })
      }
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'ascs' : 'descs'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    refresh(isRefresh, data) {
      // if(data){
      //   let adddata = data
      //   let keys = Object.keys(adddata)
      //   let obj = {}
      //   keys.forEach((i,k)=>{
      //     obj[this.columnDict[i]] = adddata[i]
      //   })
      //   this.list.unshift(obj)
      // }
      this.formVisible = false
      this.initData()
    },
    colseFlow(isRefresh) {
      this.flowVisible = false
      if (isRefresh) this.initData()
    },
    reset() {
      this.listQuery.sort = 'descs'
      this.listQuery.sidx = ''
      this.$refs.Search.reset()
    },
    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.initData()
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const obj = this.columnList.find((i) => i.propId == column.property)
        if (obj && obj.showSummary) {
          const values = data.map((item) => Number(item[this.columnDict[column.property]]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = Math.round(sums[index] * 100) / 100
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    }
  }
}
</script>
<style lang="scss">
.iconEdit {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
}
.el-dropdown-link {
  cursor: pointer;
  color: var(--color-primary);
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.table_cell_clamp {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-tooltip__popper {
  max-width: 300px;
}
.el-tooltip__popper,
.el-tooltip__popper.is-dark {
  line-height: 24px;
}
.cell.el-tooltip {
  width: auto !important;
}
.freezeClass {
  background: #f1f1f1;
  border-radius: 7px;
}
.setAllTitle {
  padding: 0;
  cursor: pointer;
}
.setAllTitle:hover {
  color: #1890ff;
}
</style>
