<!--
 * @Author: wlo_o
 * @Date: 2022-02-14 14:45:31
 * @LastEditors: Jone
 * @LastEditTime: 2022-06-29 09:09:37
 * @FilePath: /frontend/lib/components/MdImportToSetDialog.vue
 * @Description: 导入至数据集
 * 注意： 导入只能选择自定义的数据集，默认筛选条件 isSys = 0
 *
 * Copyright (c) 2022 by 青岛百洋智能科技股份有限公司, All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :width="'90%'"
    :visible="stateVisible"
    :before-close="handleDialogClose"
    :modal="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="oecp-md-import-to-set-dialog"
  >
    <el-row>
      <el-col :span="8">
        <el-input
          v-model="form.name"
          @clear="handleSearchClick"
          @keyup.enter.native="handleSearchClick"
          placeholder="请输入集合名称"
          clearable
        >
          <el-button
            slot="append"
            @click="handleSearchClick"
            icon="el-icon-search"
          />
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-row>
          <el-table
            :header-cell-style="{background:'#F2F7FF',color:'#323232',height:'46px'}"
            v-loading="mainLoading"
            :data="mainTableData"
            @current-change="handleMainTableRowChange"
            ref="mainTable"
            highlight-current-row
          >
            <el-table-column width="50">
              <template slot-scope="scope">
                <i
                  v-show="selectedMainRow&&scope.row.id===selectedMainRow.id"
                  class="el-icon-circle-check"
                  style="color:#409EFF"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-for="(column,idx) in mainColumns"
              :key="`main_column_${idx}`"
              v-bind="column"
            />
          </el-table>
        </el-row>
        <el-row
          type="flex"
          justify="center"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="mainPagination.total"
            :current-page.sync="mainPagination.page"
            hide-on-single-page
            small
          >
          </el-pagination>
        </el-row>
      </el-col>
      <el-col :span="8">
        <el-row>
          <el-table
            v-loading="subsetLoading"
            :data="subsetTableData"
            @current-change="handleSubsetTableRowChange"
            ref="subsetTable"
            highlight-current-row
          >
            <el-table-column width="50">
              <template slot-scope="scope">
                <i
                  v-show="selectedSubsetRow&&scope.row.id===selectedSubsetRow.id"
                  @click="selectedSubsetRow=null;moduleTableData=[];selectedModuleRow=null"
                  class="el-icon-circle-check"
                  style="color:#409EFF"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-for="(column,idx) in subsetColumns"
              :key="`subset_column_${idx}`"
              v-bind="column"
            />
            <template slot="empty">
              {{selectedMainRow?(!subsetLoading&&subsetTableData.length===0?'无数据':'&nbsp;'):'请选数据集'}}
            </template>
          </el-table>
        </el-row>
        <el-row
          type="flex"
          justify="center"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="subsetPagination.total"
            :current-page.sync="subsetPagination.page"
            hide-on-single-page
            small
          >
          </el-pagination>
        </el-row>
      </el-col>
      <el-col :span="8">
        <el-row>
          <el-table
            :header-cell-style="{background:'#F2F7FF',color:'#323232',height:'46px'}"
            v-loading="moduleLoading"
            :data="moduleTableData"
            @current-change="handleLeafTableRowChange"
            ref="leafTable"
            highlight-current-row
          >
            <el-table-column width="50">
              <template slot-scope="scope">
                <i
                  v-show="selectedModuleRow&&scope.row.id===selectedModuleRow.id"
                  @click="selectedModuleRow=null"
                  class="el-icon-circle-check"
                  style="color:#409EFF"
                />
              </template>
            </el-table-column>
            <el-table-column
              v-for="(column,idx) in moduleColumns"
              :key="`leaf_column_${idx}`"
              v-bind="column"
            />
            <template slot="empty">
              {{selectedSubsetRow?(!moduleLoading&&moduleTableData.length===0?'无数据':'&nbsp;'):'请选数子集'}}
            </template>
          </el-table>
        </el-row>
      </el-col>
    </el-row>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="handleDialogClose">取 消</el-button>
      <el-button
        :disabled="!selectedMainRow"
        :loading="loading"
        type="primary"
        @click="handleDialogOk"
      >导 入</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { fetchApi } from '../common/apis'
import OptionsMixin from '../mixins/OptionsMixin'
import get from 'lodash/get'

export default {
  mixins: [OptionsMixin],
  props: {
    title: { type: String, default: '选择数据集' },
    visible: { type: Boolean, default: false },
    data: { type: [Array, null], default: () => [] }, // 数据元素列表
  },
  watch: {
    visible(val) {
      this.stateVisible = val
      if (val) {
        this.handleSearchClick()
        if (!this.data || this.data.length === 0) {
          this.$message.error('请先选择数据')
          this.$emit('close')
        }
      }
    },
    'mainPagination.page': {
      handler: function (val) {
        this.getList()
      },
    },
    'subsetPagination.page': {
      handler: function (val) {
        this.getSubsetList()
      },
    },
  },
  computed: {
    selectedRow() {
      return this.selectedSubsetRow || this.selectedMainRow
    },
  },
  data() {
    return {
      loading: false,
      selectedMainRow: null,
      selectedSubsetRow: null,
      selectedModuleRow: null,
      stateVisible: this.visible,
      query: { isSys: '0' }, // 查询默认条件，只能查询自建集合;系统内置（1是 0否）
      form: { name: '' },
      mainLoading: false,
      mainTableData: [],
      mainPagination: { total: 0, page: 1, pageSize: 10 },
      mainColumns: [{ prop: 'name', label: '数据集名称' }],
      subsetLoading: false,
      subsetTableData: [],
      subsetPagination: { total: 0, page: 1, pageSize: 10 },
      subsetColumns: [{ prop: 'name', label: '子集名称' }],
      moduleLoading: false,
      moduleTableData: [],
      moduleColumns: [{ prop: 'name', label: '模块名称' }],
      showModule: true,
    }
  },
  methods: {
    handleSearchClick() {
      this.mainPagination = { ...this.mainPagination, total: 0, page: 1 }
      this.getList()
    },
    handleMainTableRowChange(row) {
      if (row) {
        if (this.selectedMainRow && this.selectedMainRow.id === get(row, 'id')) {
          this.selectedMainRow = null
          this.subsetTableData = []
          this.subsetPagination = { ...this.subsetPagination, total: 0, page: 1 }
          this.moduleTableData = []
          this.modulePagination = { ...this.modulePagination, total: 0, page: 1 }
        } else {
          this.selectedMainRow = row
          this.getSubsetList()
        }
      } else {
        this.selectedMainRow = null
      }
    },
    handleSubsetTableRowChange(row) {
      if (row) {
        if (this.selectedSubsetRow && this.selectedSubsetRow.id === get(row, 'id')) {
          this.selectedSubsetRow = null
          this.moduleTableData = []
          this.modulePagination = { ...this.modulePagination, total: 0, page: 1 }
        } else {
          this.selectedSubsetRow = row
          this.getModuleList()
        }
      } else {
        this.selectedSubsetRow = null
      }
    },
    handleLeafTableRowChange(row) {
      if (row) {
        if (this.selectedModuleRow && this.selectedModuleRow.id === get(row, 'id')) {
          this.selectedModuleRow = null
        } else {
          this.selectedModuleRow = row
        }
      } else {
        this.leafRow = null
      }
    },
    getList() {
      let that = this
      this.mainLoading = true
      this.subsetTableData = []
      this.subsetPagination = { ...this.subsetPagination, total: 0, page: 1 }
      this.selectedSubsetRow = null
      this.moduleTableData = []
      this.modulePagination = { ...this.modulePagination, total: 0, page: 1 }
      let { page, pageSize } = this.mainPagination
      let query = {
        ...this.query,
        ...(this.form.name && this.form),
        parentId: '0', // 只查顶级
        page,
        pageSize,
      }
      fetchApi
        .call(this, '/set/pageList', query)
        .then(res => {
          that.mainTableData = res.records
          that.mainPagination = { ...that.mainPagination, total: res.total }
        })
        .finally(() => {
          that.mainLoading = false
        })
    },
    getSubsetList() {
      let that = this
      if (!this.selectedMainRow) return
      this.moduleTableData = []
      this.modulePagination = { ...this.modulePagination, total: 0, page: 1 }
      this.subsetLoading = true
      let { page, pageSize } = this.subsetPagination
      let { id: parentId } = this.selectedMainRow
      fetchApi
        .call(this, '/set/pageList', { ...this.query, page, pageSize, parentId })
        .then(res => {
          that.subsetTableData = res.records
          that.subsetPagination = { ...that.subsetPagination, total: res.total }
        })
        .finally(() => {
          that.subsetLoading = false
        })
    },
    getModuleList() {
      let that = this
      if (!this.selectedSubsetRow) return
      this.moduleLoading = true
      let { id: setId } = this.selectedSubsetRow
      fetchApi
        .call(this, '/set/moduleList', { setId })
        .then(list => {
          that.moduleTableData = list
        })
        .finally(() => {
          that.moduleLoading = false
        })
    },
    clearData() {
      this.mainLoading = false
      this.subsetLoading = false
      this.moduleLoading = false
      this.selectedMainRow = null
      this.selectedSubsetRow = null
      this.selectedModuleRow = null
      this.mainTableData = []
      this.subsetTableData = []
      this.moduleTableData = []
      this.mainPagination = { ...this.mainPagination, total: 0, page: 1 }
      this.subsetPagination = { ...this.subsetPagination, total: 0, page: 1 }
      this.modulePagination = { ...this.modulePagination, total: 0, page: 1 }
    },
    handleDialogClose() {
      this.stateVisible = false
      this.clearData()
      this.loading = false
      this.$emit('close', false)
    },
    handleDialogOk() {
      let that = this
      let { id: setId } = this.selectedRow
      let elementIds = this.data.reduce((arr, o) => [...arr, o.id], [])
      let { id: moduleId } = this.selectedModuleRow || {}
      this.loading = true
      fetchApi.call(this, '/set/addChildren', { setId, elementIds, moduleId }).then(res => {
        let { success = 0, repetition = 0 } = res
        success && that.$message({ showClose: true, message: `${success} 条记录导入成功`, type: 'success', duration: 5000 })
        setTimeout(function () {
          repetition && that.$message({ showClose: true, message: `${repetition} 条重复记录跳过`, type: 'warning', duration: 5000 })
        }, 200)
        that.$emit('success')
        that.handleDialogClose()
      })
    },
  },
}
</script>
<style scoped>
/deep/.el-table th.el-table__cell.is-leaf {
  border-bottom: none !important;
}
.el-table .success-row /deep/ {
  background: #f0f9eb;
}
/* checkbox start*/
/deep/.el-table .cell .el-checkbox .el-checkbox__input .el-checkbox__inner {
  border-radius: 100% !important;
  height: 16px;
  width: 16px;
}

/deep/.cell .el-checkbox .el-checkbox__inner::after {
  border: none;
  background: #1a63eb;
  border-radius: 100%;
  width: 9px;
  height: 9px;
  top: 17%;
  left: 17.85%;
}

/* checkbox end*/

.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;
}
</style>
