<!--
 * @Author: wlo_o
 * @Date: 2022-02-08 14:47:32
 * @LastEditors: Jone
 * @LastEditTime: 2022-07-06 09:37:03
 * @FilePath: /frontend/lib/components/MdElementList.vue
 * @Description: 元素（数据元、值域、统计指标)列表,数据集列表
 *
 * Copyright (c) 2022 by 青岛百洋智能科技股份有限公司, All Rights Reserved.
-->
<template>
  <div class="oecp-md-element-list">
    <el-row class="pos-style1 title-style-box">
      <el-col
        :span="24"
        style="display:flex"
      >
        <template v-if="showGoBack">
          <el-page-header
            @back="goBack"
            title=''
          >
            <div slot="content">
              <template v-if="!!$slots.title">
                <slot name="title"></slot>
              </template>

              <div
                v-else-if="!!title"
                class="title-style"
              >{{title}}</div>
            </div>
          </el-page-header>
        </template>
        <template v-else>
          <template v-if="!!$slots.title">
            <slot name="title"></slot>
          </template>
          <div
            v-else-if="!!title"
            class="title-style"
          >
            <img
              v-if="$attrs.icon && $attrs.icon == '../common/img/source.png'"
              src="../common/img/source.png"
            />
            <img
              v-else-if="$attrs.icon && $attrs.icon == '../common/img/add.png'"
              src="../common/img/add.png"
            />
            <img
              v-else-if="$attrs.icon && $attrs.icon == '../common/img/edit.png'"
              src="../common/img/edit.png"
            />
            <img
              v-else-if="$attrs.icon && $attrs.icon == '../common/img/metaData.png'"
              src="../common/img/metaData.png"
            />
            {{title}}
          </div>
        </template>
        <template>
          <el-input
            v-model="form.name"
            @clear="getList"
            placeholder="请输入内容"
            @keyup.enter.native="getList"
            clearable
          >
            <el-button
              slot="append"
              @click="getList"
              icon="el-icon-search"
            />
          </el-input>
        </template>
      </el-col>
    </el-row>
    <!-- <el-row class="mb5 pos-style2">
      <el-col :span="18">
        <el-input
          v-model="form.name"
          @clear="getList"
          placeholder="请输入内容"
          @keyup.enter.native="getList"
          clearable
        >
          <el-button
            slot="append"
            @click="getList"
            icon="el-icon-search"
          />
        </el-input>
      </el-col>
    </el-row> -->

    <!-- 如果 types是数组的话，需要左右分栏 如果不是的话上下分栏 -->
    <!-- 数组 types == Array   start -->
    <el-row
      v-if="type == 5 || type == 6 || type == 7 || type == 8"
      class="flex1"
    >
      <el-col
        :span="9"
        style="height: 100%;overflow:auto;padding: 10px 0"
      >
        <md-category
          :type="stateType"
          :types="types"
          :showTabs="stateShowTabs"
          :showSelectAllTag="showSelectAllTag"
          @change="(v,g)=>tags=g"
          @update:type="handleTagRootChange"
        />
      </el-col>
      <el-col
        :span="15"
        style="height: 100%;overflow:auto;padding: 10px 0"
      >
        <!-- <div style="height:46px;width:100%;background:#EBEFF2;"></div> -->
        <el-row
          v-if="showRowSelection||showAdd"
          style="margin: 0 30px 10px;padding-top: 10px"
          type="flex"
          justify="space-between"
        >
          <el-col :span="10">
            <el-row v-if="showRowSelection">
              <el-tag type="info">
                共筛选 <el-link
                  :underline="false"
                  type="primary"
                  class="mt-2"
                >{{pagination.total}}</el-link> 条数据，已选中 <el-link
                  :underline="false"
                  type="primary"
                  class="mt-2"
                >{{selected.length}}</el-link> 条数据
              </el-tag>
            </el-row>
          </el-col>
          <el-col :span="14">
            <el-row
              type="flex"
              justify="end"
            >
              <el-button
                v-if="showImport"
                v-oecp-auth:[{type:stateType}]="'elementList.import'"
                :disabled="importButtonDisabled"
                @click="importDialogVisible=true"
                type="primary"
                class="addBtn"
                size="medium"
                icon="el-icon-circle-plus"
              >导入至数据集</el-button>
              <el-button
                v-if="showAdd"
                v-oecp-auth:[{type:stateType}]="'elementList.add'"
                @click="handleAddClick()"
                type="primary"
                size="medium"
                class="ml5 addBtn"
                icon="el-icon-plus"
              >
                {{addBtnTitle||`添加${typeName}`}}
              </el-button>
            </el-row>
          </el-col>
        </el-row>
        <el-row style="margin: 0 20px 0 10px">
          <el-table
            :header-cell-style="{background:'#F2F7FF',color:'#323232',height:'46px'}"
            v-loading="loading"
            :data="tableData"
            size="mini"
            @select="handleRowChange"
            @select-all="handleRowChangeAll"
            ref="table"
            stripe
          >
            <el-table-column
              v-if="showRowSelection"
              type="selection"
              :align="center"
              width="70"
            />
            <el-table-column
              v-for="(column,idx) in columns"
              :key="`column_${idx}`"
              v-bind="column"
            >
              <template
                v-for="(render,key) in column.slots"
                v-slot:[key]="scope"
              >
                <md-slot-shim
                  :key="`slot_${key}`"
                  :render="render"
                  :data="scope"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="showRowAction"
              v-bind="actionColumn"
              width="200"
              align="center"
              fixed="right"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.view'"
                  :key="`elementList.row.view.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                  @click="handleRowClick(scope.row)"
                  title="详情"
                  size="mini"
                  icon="el-icon-view"
                  round
                >
                  <span
                    v-if="showRowBtnText"
                    style="color:#777"
                  >详情</span>
                </el-button>
                <el-button
                  v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.edit'"
                  :key="`elementList.row.edit.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                  :disabled="scope.row.isSys==1"
                  @click="handleRowClick(scope.row, true)"
                  title="编辑"
                  size="mini"
                  icon="el-icon-edit-outline"
                  round
                >
                  <span
                    v-if="showRowBtnText"
                    style="color:#777"
                  >编辑</span>
                </el-button>
                <!-- <el-button
              v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.del'"
              :key="`elementList.row.del.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
              :disabled="scope.row.isSys==1"
              @click="handleRowDel(scope.row)"
              title="删除"
              size="mini"
              round
            >
              <i
                style="color:#F56C6C"
                class="el-icon-close"
              ></i>
              <span v-if="showRowBtnText">删除</span>
            </el-button> -->
                <el-button
                  v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.del'"
                  :key="`elementList.row.del.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                  :disabled="scope.row.isSys==1"
                  @click="handleRowDel(scope.row)"
                  type="text"
                  size="small"
                  circle
                >
                  <i
                    style="color: #FF432E;background: #FFEEEB;border-radius: 100%;font-size:13px;padding:2px;font-weight:600;"
                    class="el-icon-close"
                  ></i>
                </el-button>
                <template v-if="actionColumn.slots&&actionColumn.slots.default">
                  <md-slot-shim
                    :render="actionColumn.slots.default"
                    :data="scope"
                    :key="`elementList.row.other.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                  />
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row
          type="flex"
          justify="end"
          style="margin: 0 20px 0 10px;padding: 10px 0;"
        >
          <el-pagination
            :loading="loading"
            :total="pagination.total"
            :page-sizes="pagination.pageSizes"
            :page-size.sync="pagination.pageSize"
            :current-page.sync="pagination.page"
            :hide-on-single-page="false"
            layout="prev,pager,next,sizes,jumper"
            background
          />
        </el-row>
      </el-col>
    </el-row>
    <!-- 数组 types == Array   end -->
    <div
      v-else
      class="flex1"
      style="background: #fff"
    >
      <el-row>
        <md-category
          :type="stateType"
          :types="types"
          :showTabs="stateShowTabs"
          :showSelectAllTag="showSelectAllTag"
          @change="(v,g)=>tags=g"
          @update:type="handleTagRootChange"
        />
      </el-row>
      <el-row
        v-if="showRowSelection||showAdd"
        style="margin: 0 30px 10px;padding-top: 10px"
        type="flex"
        justify="space-between"
      >
        <el-col :span="12">
          <el-row v-if="showRowSelection">
            <el-tag type="info">
              共筛选 <el-link
                :underline="false"
                type="primary"
                class="mt-2"
              >{{pagination.total}}</el-link> 条数据，已选中 <el-link
                :underline="false"
                type="primary"
                class="mt-2"
              >{{selected.length}}</el-link> 条数据
            </el-tag>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-row
            type="flex"
            justify="end"
          >
            <el-button
              v-if="showImport"
              v-oecp-auth:[{type:stateType}]="'elementList.import'"
              :disabled="importButtonDisabled"
              @click="importDialogVisible=true"
              type="primary"
              size="small"
              class="addBtn"
              icon="el-icon-circle-plus"
            >导入至数据集</el-button>
            <el-button
              v-if="showAdd"
              v-oecp-auth:[{type:stateType}]="'elementList.add'"
              @click="handleAddClick()"
              type="primary"
              size="small"
              class="ml5 addBtn"
              icon="el-icon-plus"
            >
              {{addBtnTitle||`添加${typeName}`}}
            </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row style="margin: 0 30px">
        <el-table
          :header-cell-style="{background:'#F2F7FF',color:'#323232',height:'46px'}"
          v-loading="loading"
          :data="tableData"
          size="mini"
          @select="handleRowChange"
          @select-all="handleRowChangeAll"
          ref="table"
          stripe
        >
          <el-table-column
            v-if="showRowSelection"
            type="selection"
            width="110"
          />
          <el-table-column
            v-for="(column,idx) in columns"
            :key="`column_${idx}`"
            v-bind="column"
          >
            <template
              v-for="(render,key) in column.slots"
              v-slot:[key]="scope"
            >
              <md-slot-shim
                :key="`slot_${key}`"
                :render="render"
                :data="scope"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="showRowAction"
            v-bind="actionColumn"
            width="300"
            align="center"
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.view'"
                :key="`elementList.row.view.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                @click="handleRowClick(scope.row)"
                title="详情"
                size="mini"
                icon="el-icon-view"
                round
              >
                <span
                  v-if="showRowBtnText"
                  style="color:#777"
                >详情</span>
              </el-button>
              <el-button
                v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.edit'"
                :key="`elementList.row.edit.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                :disabled="scope.row.isSys==1"
                @click="handleRowClick(scope.row, true)"
                title="编辑"
                size="mini"
                icon="el-icon-edit"
                round
              >
                <span
                  v-if="showRowBtnText"
                  style="color:#777"
                >编辑</span>
              </el-button>
              <!-- <el-button
              v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.del'"
              :key="`elementList.row.del.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
              :disabled="scope.row.isSys==1"
              @click="handleRowDel(scope.row)"
              title="删除"
              size="mini"
              round
            >
              <i
                style="color:#F56C6C"
                class="el-icon-close"
              ></i>
              <span v-if="showRowBtnText">删除</span>
            </el-button> -->
              <el-button
                v-oecp-auth:[{...scope,type:stateType}]="'elementList.row.del'"
                :key="`elementList.row.del.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                :disabled="scope.row.isSys==1"
                @click="handleRowDel(scope.row)"
                type="text"
                size="small"
                circle
              >
                <i
                  style="color: #FF432E;background: #FFEEEB;border-radius: 100%;font-size:13px;padding:2px;font-weight:600;"
                  class="el-icon-close"
                ></i>
              </el-button>
              <template v-if="actionColumn.slots&&actionColumn.slots.default">
                <md-slot-shim
                  :render="actionColumn.slots.default"
                  :data="scope"
                  :key="`elementList.row.other.${stateType}.${pagination.page}.${scope.$index}.${new Date().getTime()}`"
                />
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row
        type="flex"
        justify="end"
        style="margin: 0 30px;padding: 10px 0;"
      >
        <el-pagination
          :loading="loading"
          :total="pagination.total"
          :page-sizes="pagination.pageSizes"
          :page-size.sync="pagination.pageSize"
          :current-page.sync="pagination.page"
          :hide-on-single-page="false"
          layout="prev,pager,next,sizes,jumper"
          background
        />
      </el-row>
    </div>

    <md-import-to-set-dialog
      v-if="showImport"
      :visible="importDialogVisible"
      :data="selected"
      @close="importDialogVisible=false"
      @success="importDialogVisible=false"
    />
  </div>
</template>
<script>
import OptionsMixin from '../mixins/OptionsMixin'
import RouterMixin from '../mixins/RouterMixin'
import EventMixin from '../mixins/EventMixin'
import get from 'lodash/get'
import isEmpty from 'lodash/isEmpty'
import { fetchApi } from '../common/apis.js'
import { clone, parsePromise } from '../common/utils.js'
import debounce from 'lodash/debounce'
import isFunction from 'lodash/isFunction'
import isString from 'lodash/isString'
import isArray from 'lodash/isArray'
import isObject from 'lodash/isObject'

let extQuery = { ids: [], extNameList: [] } // 查询条件,放在外面规避内部使用循环报错

export default {
  mixins: [OptionsMixin, RouterMixin, EventMixin],
  props: {
    title: { type: [String, null], default: '' },
    type: { type: [String, Number, null], default: '2' },
    setId: { type: [String, null], default: null },
    showTabs: { type: Boolean, default: false },
    showImport: { type: Boolean, default: false },
    showSelection: { type: Boolean, default: false },
    showAdd: { type: Boolean, default: false },
    addBtnTitle: { type: [String, null], default: null },
    showSelectAllTag: { type: Boolean, default: false },
    showGoBack: { type: Boolean, default: false }, // 显示返回
    types: { type: [Array, null], default: null }, // 显示的所有类型
    showRowAction: { type: Boolean, default: true },
    includeSys: { type: [String, null], default: '' }, // 集合包含数据集标示；用于配合业务使用时权限处理
  },
  computed: {
    importButtonDisabled: function () {
      let list = get(this.getMbOptionVar('typeConfig'), 'list') || []
      let { stateType: type } = this
      let cfg = list.find(o => o.type === type) || {}
      return this.selected.length === 0 || !cfg.showImport
    },
    showRowSelection: function () {
      return this.showImport || this.showSelection
    },
  },
  watch: {
    type(val) {
      this.stateType = val
    },
    showTabs(val) {
      this.stateShowTabs = val
    },
    stateType() {
      this.initAndLoad()
    },
    tags: {
      handler: function (val) {
        this.getList()
      },
      deep: true,
    },
    'pagination.page': function () {
      this.getList()
    },
    'pagination.pageSize': function () {
      this.getList()
    },
  },
  data() {
    return {
      loading: false,
      importDialogVisible: false,
      stateType: '',
      stateShowTabs: this.showTabs,
      tags: [], // 选中的分类标签
      showRowBtnText: true,
      form: { name: '' },
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
      },
      selected: [],
      tableData: [],
      defaultColumns: [
        {
          prop: 'name',
          label: '名称',
          width: '260',
          slots: {
            default: function (h, data) {
              return h(
                'span',
                {
                  class: 'wordDouble2',
                  attrs: {
                    title: data.row.name,
                  },
                },
                data.row.name,
              )
            },
          },
        },
        { prop: 'code', label: '编码' },
        {
          prop: 'sourceFileCode',
          label: '来源文件编码',
          slots: {
            default: function (h, data) {
              return h(
                'span',
                {
                  class: 'wordDouble2',
                  attrs: {
                    title: data.row.sourceFileCode,
                  },
                },
                data.row.sourceFileCode,
              )
            },
          },
        },
        {
          prop: 'sourceCode',
          label: '来源标识符',
          slots: {
            default: function (h, data) {
              return h(
                'span',
                {
                  class: 'wordDouble2',
                  attrs: {
                    title: data.row.sourceCode,
                  },
                },
                data.row.sourceCode,
              )
            },
          },
        },
      ],
      columns: [],
      actionColumn: { label: '操作', width: 150 },
      elementTypeKv: {}, // key:类型 value: 名称
      extData: {}, // 扩展信息
      debounceGetExtData: debounce(this.getExtData, 250),
      extLoading: false,
    }
  },
  methods: {
    getExtData() {
      let that = this
      let { ids, extNameList } = extQuery
      let { component = 'set' } = this.getTypeConfig()
      let url = component === 'element' ? '/element/extList' : '/set/extList'
      this.extLoading = true
      fetchApi.call(that, url, { ids, extNameList }).then(function (res = []) {
        let extData = {}
        res.forEach(function (item) {
          let { extName, parentId, extValue } = item
          extData[`${parentId}_${extName}`] = extValue
        })
        that.extData = { ...that.extData, ...extData }
        that.extLoading = false
      })
    },
    pushQuery(id = '', extName = '') {
      if (!id && !extName) return
      let key = `${id}_${extName}`
      // 会出现循环调用，添加判断规避死循环
      if (this.extData.hasOwnProperty(key)) return
      this.extData[key] = ''
      extQuery = {
        ids: [...new Set([...extQuery.ids, id])],
        extNameList: [...new Set([...extQuery.extNameList, extName])],
      }
      this.debounceGetExtData()
    },
    extFileColumnRender(h, data, extName = '') {
      let { _self: self, row = {} } = data
      if (isEmpty(row) || !extName || !row.id) return h('div')
      this.pushQuery(row.id, extName)
      let obj = self.extData[`${row.id}_${extName}`]
      if (obj) {
        obj = isString(obj) ? JSON.parse(obj) : obj
        obj = isArray(obj) ? obj : [obj]
        return h(
          'div',
          null,
          obj.map(function (item) {
            return h(
              'el-link',
              {
                class: 'wordDouble2',
                domProps: { target: '_blank', title: item.name },
                attrs: { type: 'primary', href: item.url },
              },
              item.name,
            )
          }),
        )
      } else {
        return h('div', { domProps: { innerHTML: self.extData[`${row.id}_${extName}`] } })
      }
    },
    extColumnRender(h, data, extName = '', customRender) {
      this.loadExtData(h, data, extName, customRender)
    },
    loadExtData(h, data, extName = '', customRender) {
      let { _self: self, row = {} } = data
      if (isEmpty(row) || !extName || !row.id) return h('div')
      this.pushQuery(row.id, extName)
      if (customRender && isFunction(customRender)) {
        return customRender(h, data, extName)
      } else {
        return h('div', { domProps: { innerHTML: self.extData[`${row.id}_${extName}`] } })
      }
    },
    getTypeConfigList() {
      return get(this.getMbOptionVar('typeConfig'), 'list') || []
    },
    getTypeConfig() {
      let { stateType: type } = this
      return this.getTypeConfigList().find(o => o.type === type)
    },
    handleTagRootChange(type) {
      this.stateType = type
    },
    handleAddClick() {
      this.handleRowClick({}, true)
    },
    handleRowChange(selection, row) {
      if (selection.length && selection.findIndex(o => o.id === row.id) !== -1) {
        // 新增
        this.selected.push(row)
      } else {
        // 反选
        let idx = this.selected.findIndex(o => o.id === row.id)
        idx !== -1 && this.selected.splice(idx, 1)
      }
      this.$emit('change', this.selected)
    },
    handleRowChangeAll(selection) {
      let that = this
      if (selection.length === 0) {
        // 反选
        that.selected.length &&
          this.tableData.forEach(row => {
            let idx = that.selected.findIndex(o => o.id === row.id)
            idx !== -1 && that.selected.splice(idx, 1)
          })
      } else {
        // 全选
        this.tableData.forEach(row => {
          that.selected.findIndex(o => o.id === row.id) === -1 && that.selected.push(row)
        })
      }
      this.$emit('change', this.selected)
    },
    checkElementUsed(extValue, extName, component) {
      let that = this
      let alreadyUsedErr = '数据已被引用，无法删除'
      if (component === 'element') {
        return new Promise(function (resolve, reject) {
          let query = { extName, extValue }
          fetchApi.call(that, '/element/findExtCount', query).then(function (rs) {
            if (rs.count === 0) return resolve()
            that.$message.error(alreadyUsedErr)
            reject(new Error(alreadyUsedErr))
          })
        })
      } else {
      }
    },
    handleRowDel(data) {
      let that = this
      let cfg = this.getTypeConfig()
      let { id } = data
      let { component = 'set' } = cfg
      let url = component === 'element' ? '/element/delete' : '/set/delete'
      this.$confirm(`此操作将永久删除该${cfg.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(function () {
        let beforeElementDelete = get(that, '$OecpMetaDataConfig.beforeElementDelete')
        let dfd = null
        if (isFunction(beforeElementDelete)) {
          let res = beforeElementDelete.call(that, data, that.stateType)
          dfd = parsePromise(res)
        } else if (isString(beforeElementDelete)) {
          dfd = that.checkElementUsed(id, beforeElementDelete, 'element')
        } else if (isObject(beforeElementDelete) || isArray(beforeElementDelete)) {
          let typeList = []
          let { stateType: type } = that
          if (isObject) {
            for (const key in beforeElementDelete) {
              typeList.push({ type: key, extName: beforeElementDelete[key] })
            }
          } else {
            typeList = beforeElementDelete
          }
          let item = beforeElementDelete.find(item => item.type === type)
          if (item) {
            let { component = 'element', extName } = item
            if (item.component === 'set') {
            } else {
              dfd = that.checkElementUsed(id, extName, component)
            }
          } else {
            dfd = Promise.resolve()
          }
        } else {
          dfd = Promise.resolve()
        }
        dfd.then(function (rs) {
          fetchApi
            .call(that, url, { id })
            .then(function () {
              that.$message({ type: 'success', message: '删除成功!' })
              let { page } = that.pagination
              if (that.tableData.length === 1 && page > 1) {
                that.pagination = { ...that.pagination, page: page - 1 }
              } else {
                that.getList()
              }
            })
            .catch(() => {
              // 统一 使用 defaultFail 做信息提示。这里只能做回滚等业务
              // that.$message({ type: 'error', message: '删除失败!' })
            })
        })
      })
    },
    initAndLoad() {
      this.tags = []
      this.selected = []
      let { stateType: type } = this
      let cfg = this.getTypeConfig()
      let { component = 'set' } = cfg
      let tableCfg = this.getMbOptionVar(`${component}TableConfig${type}`)
      let allColumns = [...this.defaultColumns, ...(get(tableCfg, 'ext') || [])]
      let columns = []
      let actionColumn = { label: '操作', width: 100 }
      allColumns.forEach(item => {
        if (item.prop !== 'action') {
          columns.push(item)
        } else {
          actionColumn = { ...item }
        }
      })
      this.columns = columns
      this.actionColumn = actionColumn
      this.pagination.page = 1
      this.getList()
    },
    getList() {
      let that = this
      if (this.loading) return false
      this.loading = true
      let { tags: categoryIds, stateType: type, includeSys = '' } = this
      let { name } = this.form
      let { pageSize, page } = this.pagination
      let cfg = this.getTypeConfig()
      let { component = 'set' } = cfg
      let url = component === 'element' ? '/element/pageList' : '/set/pageList'
      let query = {
        ...(name && { name }),
        ...(!isEmpty(categoryIds) && { categoryIds }),
        ...(component === 'set' && { parentId: '0', includeSys }), // 集合只查顶级集合
        type,
        pageSize,
        page,
      }
      that.extData = {}
      extQuery = { ids: [], extNameList: [] }
      fetchApi
        .call(this, url, query)
        .then(function (res) {
          that.tableData = get(res, 'records')
          that.pagination = { ...that.pagination, total: get(res, 'total') }
        })
        .catch(() => {
          that.pagination = { ...that.pagination, total: 0 }
          that.tableData = []
        })
        .finally(() => {
          that.backfillSelectedRow()
          that.loading = false
        })
    },
    backfillSelectedRow() {
      // 勾选数据回填
      if (this.selected.length === 0 || this.tableData.length === 0 || !this.setId) return false
      let that = this
      this.tableData.forEach(function (row) {
        if (that.selected.findIndex(o => o.id === row.id) !== -1) {
          that.$refs.table.toggleRowSelection(row, true)
        }
      })
    },
    getCurrentRouteCfg() {
      let current = clone(this.$OecpMetaDataEventBus.component)
      return { ...current, attrs: { ...current.attrs, page: this.pagination.page, type: this.stateType } }
    },
    handleRowClick(data, editable) {
      let { stateType: type } = this
      let cfg = this.getTypeConfig()
      let { component = 'set' } = cfg
      let { id } = data
      let title = (id ? (editable ? '修改' : '查看') : '添加') + cfg.name
      console.log(component)
      if (component === 'set') {
        this.goto(
          {
            componentName: 'md-set-form',
            attrs: {
              id,
              title,
              type,
              editable: !!editable,
              showSubset: true,
              showElement: true,
              showCategory: true,
              showGoBack: true,
            },
            history: this.getCurrentRouteCfg(),
          },
          true,
          true,
        )
      } else if (component === 'element') {
        this.goto(
          {
            componentName: 'md-element-form',
            attrs: {
              id,
              title,
              type,
              editable: !!editable,
              showSubset: true,
              showCategory: true,
              showGoBack: true,
            },
            history: this.getCurrentRouteCfg(),
          },
          true,
          true,
        )
      }
    },
  },
  created() {
    let list = this.getTypeConfigList()
    this.stateType = this.type || get(list, '[0].type')
    this.elementTypeKv = list.reduce(function (obj, current) {
      return { ...obj, [current.type]: current.name }
    }, {})
  },
}
</script>
<style scoped>
.mb5 {
  margin-bottom: 5px;
}
.ml5 {
  margin-left: 5px;
}
.mt-2 {
  margin-top: -2px;
}
.title-style {
  /* padding-top: 6px; */
  display: flex;
  align-items: center;
  font-size: 18px;
}

/* title start */
.el-input-group {
  border-radius: 30px;
  overflow: hidden;
  border: 1px solid #ddd;
}
/deep/.cell {
  /* padding: 0 20px !important; */
}
/deep/.el-input-group--append .el-input__inner,
/deep/.el-input-group__prepend {
  border-top-left-radius: 30px !important;
  border-bottom-left-radius: 30px !important;
  height: 36px !important;
  border: none;
}
/deep/.el-input-group--prepend .el-input__inner,
/deep/.el-input-group__append {
  border-top-right-radius: 30px !important;
  border-bottom-right-radius: 30px !important;
  background-color: #fff;
  border: none;
}
/deep/.el-icon-search {
  color: #2468f2 !important;
  font-size: 20px;
}
/* title end */
/deep/.el-icon-close {
  font-size: 18px;
}
/deep/.el-button--mini i {
  color: #2468f2 !important;
  font-size: 14px;
}
/deep/.el-link--inner {
  color: #2468f2 !important;
}
/deep/.el-table__body-wrapper {
  font-size: 14px;
}
/deep/.el-button--small {
  padding: 9px 0 !important;
  font-size: 16px;
  font-weight: 600;
}
/deep/.el-button--mini {
  padding: 4px 7px !important;
}

/* checkbox start*/
/deep/.el-table .cell .el-checkbox .el-checkbox__input .el-checkbox__inner {
  border-radius: 100% !important;
  height: 16px;
  width: 16px;
}
/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  border-radius: 100% !important;
  background-color: #fff !important;
  border: 1px solid #979797 !important;
}
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  border-radius: 100% !important;
  background-color: #fff !important;
  border: 1px solid #979797 !important;
}
/deep/.el-checkbox__inner {
  border: 1px solid #979797 !important;
}
/deep/.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #1a63eb !important;
  border-color: #1a63eb !important;
}
/deep/.el-table {
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
  overflow: hidden;
}

/deep/.el-checkbox__inner::after {
  transform: rotate(0) !important;
  background-color: #979797 !important;
  border: none;
  border-radius: 100%;
  width: 9px;
  height: 9px;
  top: 17%;
  left: 17.85%;
}

/deep/.el-checkbox__input.is-checked .el-checkbox__inner::after {
  transform: rotate(0) !important;
  background-color: #1a63eb !important;
  border: none;
  border-radius: 100%;
  width: 9px;
  height: 9px;
  top: 17%;
  left: 17.85%;
}

/* checkbox end*/
.title-style img {
  height: 23px;
  width: 23px;
  margin-right: 10px;
}

.title-style {
  padding-bottom: 0;
  display: flex;
  align-items: center;
  font-size: 18px;
}

.el-input-group {
  border-radius: 30px;
  overflow: hidden;
  /* border: 1px solid #ddd; */
  width: 300px;
  margin-left: 15px;
}

/deep/.el-input-group--append .el-input__inner,
/deep/.el-input-group__prepend {
  border-top-left-radius: 30px !important;
  border-bottom-left-radius: 30px !important;
  height: 36px !important;
  background-color: #fff;
  border: none;
}

/deep/.el-input-group--prepend .el-input__inner,
/deep/.el-input-group__append {
  border-top-right-radius: 30px !important;
  border-bottom-right-radius: 30px !important;
  background-color: #fff;
  border: none;
}

/deep/.el-icon-search {
  color: #2468f2 !important;
  font-size: 20px;
}

/deep/.el-input-group--append .el-input__inner {
  border-top-left-radius: 30px !important;
  border-bottom-left-radius: 30px !important;
  height: 36px !important;
}

/deep/.el-input-group__append {
  padding-right: 8px;
  border-top-right-radius: 30px !important;
  border-bottom-right-radius: 30px !important;
}
/* 顶部 title start */
.title-style-box {
  background: #ebeff2;
  padding: 10px 12px;
}

/* 顶部 title end */
.oecp-md-element-list {
  background-color: #ebeff2;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.flex1 {
  flex: 1;
  overflow: auto;
  border-radius: 6px;
  background: #fff;
}
/* 超出两行省略号 start */
.wordDouble,
.el-link--inner {
  white-space: nowrap;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  display: flow-root;
}
/* 超出两行省略号 end */
.addBtn {
  background: #2468f2;
  border-color: #2468f2;
  height: 36px !important;
  line-height: 36px !important;
  padding: 0 20px !important;
  font-size: 14px;
}
.addBtn:hover {
  background: #2469f2d6;
  border-color: #2469f2d6;
}
.el-button--primary.is-disabled,
.el-button--primary.is-disabled:active,
.el-button--primary.is-disabled:focus,
.el-button--primary.is-disabled:hover {
  background: #2469f268;
  border: none;
}
.wordDouble2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  /* text-align: left; */
}
/deep/.el-table__row .el-table__cell:first-of-type .wordDouble2 {
  padding-left: 35px !important;
}
/deep/.el-table td.el-table__cell,
/deep/.el-table th.el-table__cell.is-leaf {
  border-bottom: 1px solid #ddd !important;
}
/deep/.has-gutter .el-table__cell .cell {
  text-align: center;
}
/deep/.el-table-column--selection .cell {
  text-align: center;
}
/deep/.el-table th.el-table__cell.is-leaf {
  border-bottom: none !important;
}
/* 分页 */
.el-pagination.is-background .el-pager li:not(.disabled).active {
  background: #2468f2 !important;
}
</style>
