<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">
      <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>
            <template v-for="(item, i) in columnData.btnsList">
              <el-button v-if="item.value !== 'journal'" :type="i === 0 ? 'primary' : 'text'" :icon="item.icon" @click="headBtnsHandel(item.value)" :key="i">{{ item.label }}</el-button>
            </template>
            <!--            <el-button type="primary" @click="headBtnsHandel('adda')">新增</el-button>-->
          </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>
        <JNPF-table
          v-loading="listLoading"
          :data="list"
          row-key="id"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: '' }"
          @sort-change="sortChange"
          :has-c="false"
          @selection-change="handleSelectionChange"
          v-if="refreshTable"
        >
          <!--          :prop="item.prop"-->
          <el-table-column
            :label="item.label"
            :align="item.align"
            :width="item.width"
            v-for="(item, i) in columnList"
            :prop="String(item.propId)"
            :key="i"
            :sortable="item.sortable ? 'custom' : item.sortable"
          >
            <template slot-scope="scope">
              <div class="templateVal">
                <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) }}-->
                    <el-image
                      v-else-if="getImgFun(scope.row[columnDict[item.propId]])[0].url"
                      style="width: 50px; height: 50px"
                      :src="define.comUrl + getImgFun(scope.row[columnDict[item.propId]])[0].url"
                      :preview-src-list="getImgFunList(scope.row[columnDict[item.propId]])"
                    >
                    </el-image>
                    <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 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 v-else>
                    {{ scope.row[columnDict[item.propId]] }}
                  </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>
              </div>
            </template>
          </el-table-column>
          <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="80" v-if="columnData.columnBtnsList.length">
            <template slot-scope="scope" v-if="!scope.row.top">
              <template>
                <div style="display: flex">
                  <el-dropdown @command="columnBtnsHandel($event, scope.row)">
                    <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"></i></span>
                    <el-dropdown-menu slot="dropdown">
                      <template v-for="(item, i) in columnData.columnBtnsList">
                        <template v-if="item.value == 'edit'">
                          <el-dropdown-item :disabled="config.webType == 3 && [1, 2, 5].indexOf(scope.row.flowState) > -1" command="edit">{{ item.label }}</el-dropdown-item>
                        </template>
                        <template v-if="item.value == 'remove'">
                          <el-dropdown-item :disabled="config.webType == 3 && [1, 2, 3, 5].indexOf(scope.row.flowState) > -1" command="remove">{{ item.label }}</el-dropdown-item>
                        </template>
                        <template v-if="item.value == 'detail'">
                          <el-dropdown-item :disabled="config.webType == 3 && !scope.row.flowState" command="detail">{{ item.label }}</el-dropdown-item>
                        </template>
                        <template v-if="item.value == 'rowJournal'">
                          <el-dropdown-item :disabled="config.webType == 3 && !scope.row.flowState" command="rowJournal">{{ item.label }}</el-dropdown-item>
                        </template>
                      </template>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <!--                  <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>
          </el-table-column>
        </JNPF-table>
        <template v-if="columnData.type !== 3 && columnData.hasPage">
          <pagination :total="total" :small="true" layout="total,prev, pager,next" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
        </template>
      </div>
    </div>
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
    <Form v-show="formVisible" 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" v-show="uploadListBoxVisible" ref="uploadListBox" @close="uploadListBoxVisible = false" />
    <recycleList :modelId="this.modelId" v-show="recycleListBoxVisible" ref="recycleListBox" @recycleDataList="initData()" @editCurrent="recycleDetail" @close="recycleListBoxVisible = 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 moment from 'moment'
import { dictDetail } from '@/api/newbi/dict'
import { getToken } from '@/utils/auth'

export default {
  name: 'dynamicModel',
  components: {
    Form,
    ExportBox,
    Search,
    Detail,
    FlowBox,
    UploadBox,
    journal,
    exportListBox,
    uploadListBox,
    recycleList
  },
  props: ['config', 'modelId'],
  data() {
    return {
      btnsOption: [
        { value: 'add', icon: 'el-icon-plus', label: '新增' }
        // { value: 'recycle', icon: 'el-icon-delete', label: '回收站' },
        // { value: 'download', icon: 'el-icon-download', label: '导出' },
        // { value: 'batchUpload', icon: 'el-icon-upload2', label: '批量导入' },
        // { value: 'batchRemove', 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: '操作记录' }
      ],
      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: ''
      },
      flowVisible: false,
      formVisible: false,
      detailVisible: false,
      importBoxVisible: false,
      exportBoxVisible: false,
      uploadBoxVisible: false,
      journalBoxVisible: false,
      exportListBoxVisible: false,
      uploadListBoxVisible: false,
      recycleListBoxVisible: false,
      treeData: [],
      treeActiveId: '',
      columnData: {
        columnBtnsList: []
      },
      formData: {},
      columnList: [],
      hasBatchBtn: false,
      refreshTable: true,
      multipleSelection: [],
      multipleSelectionDelectData: [],
      value: '',
      valueIndex: -1,
      itemLabel: '',
      oldList: [],
      oldData: null,
      btnArr: [],
      optionList: [],
      checkboxVal: null,
      cascaderVal: null
    }
  },
  created() {
    this.init()
  },
  methods: {
    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]
          }
        }
      }
      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
    },
    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
      }
    },
    inputClick(value, scope) {
      let rows = Object.assign({}, scope.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)
      scope.row.inputShow = true
      let arr = Object.keys(editrowList)
      this.formData.fields.forEach((item, index) => {
        //查找表单设计时 哪些组件控件为时间类型 与编辑行匹配
        if (arr.includes(String(item.__vModel__)) && item.__config__.viewDataType === 'DATETIME') {
          //将时间类型的数据改为时间戳
          scope.row[this.columnDict[item.__vModel__]] = moment(scope.row[this.columnDict[item.__vModel__]]).valueOf()
        }
      })
      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
          }
        }
      })
    },
    mouseOver(val, scope, itemLabel) {
      this.value = val
      this.valueIndex = scope.$index
      this.itemLabel = itemLabel
      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)
      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)
      if (window.innerWidth < 767) {
        this.formData.labelPosition = 'top'
        this.formData.generalWidth = '95%'
      }
      // 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()
      })
      //获取列表数据
      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.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
        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
    // },
    //图片类型处理
    getImgFun(value) {
      try {
        const toObj = JSON.parse(value)
        if (Array.isArray(toObj) && toObj[0].url) {
          return toObj
        }
      } catch {}
      return value
    },
    getImgFunList(val) {
      const list = this.getImgFun(val)
      if (Array.isArray(list) && list.length)
        return list.map((i) => {
          return this.define.comUrl + i.url
        })
    },
    //下拉属性的组件  如果key和value值不相同 查询title
    getOptionData(v, id) {
      let list = []
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          list = item.__slot__.options
        }
      })
      if (!list) return
      let str = list.find((i) => i.id == v)
      if (!str) return
      return str.fullName
    },
    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)
    },
    //查询对应的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 === 'adda') {
        let url = decodeURI(window.location.search || window.location.hash)
        //获取哈希地址信息
        function queryURLParams(url) {
          let result = {},
            reg1 = /([^?=&#]+)=([^?=&#]+)/g,
            reg2 = /#([^?=&#]+)/g
          url.replace(reg1, (n, x, y) => (result[x] = y))
          url.replace(reg2, (n, x) => (result['HASH'] = x))
          return result
        }
        let paramsObj = queryURLParams(url)
        this.$router.push(`/dataCreate?token=${process.env.NODE_ENV === 'development' ? getToken() : paramsObj.token}&id=${this.modelId}`)
      }
      if (key === 'add') {
        this.addOrUpdateHandle()
      }
      if (key === 'download') {
        this.exportBoxVisible = true
        this.$nextTick(() => {
          this.$refs.ExportBox.init(this.formData, this.columnList)
        })
      }
      if (this.isPreview) return
      if (key === 'batchUpload') {
        this.uploadBoxVisible = true
        this.$nextTick(() => {
          this.$refs.UploadBox.init(this.formData, this.columnList, this.config.dbLinkId)
        })
      }
      if (key === 'batchRemove') {
        this.batchRemove()
      }
      if (key === 'recycle') {
        this.recycleListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.recycleListBox.init(this.formData, this.columnList, this.config.dbLinkId)
        })
      }
    },
    handleCommand(command) {
      if (command === 'exportList') {
        this.exportListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.exportListBox.init(this.formData)
        })
      }
      if (command === 'uploadList') {
        this.uploadListBoxVisible = true
        this.$nextTick(() => {
          this.$refs.uploadListBox.init(this.formData)
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelectionDelectData = val
      this.multipleSelection = val.map((item) => item[this.columnDict[this.idKey]])
    },
    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.isPreview)
        return this.$message({
          message: '功能预览不支持数据导出',
          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.length ? 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
      }
      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
        }
      })
    },
    UploadChange(data) {
      if (this.isPreview)
        return this.$message({
          message: '功能预览不支持数据导出',
          type: 'warning'
        })
      let query = { modelId: this.modelId, withHeader: true, ...data }
      uploadModel(query).then((res) => {
        if (res.data.code === 200) {
          this.$message({ message: res.data.msg, type: 'success' })
          this.$refs.UploadBox.visible = false
          this.uploadBoxVisible = false
          this.$refs.Search.reset()
        }
      })
    },
    //操作按钮
    columnBtnsHandel(key, row) {
      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(this.formData, 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
      if (isRefresh) 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()
    }
  }
}
</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;
}
</style>
