<template>
  <div class="copy-group-com">
    <dee-search-server
      v-model="searchForm"
      :form-data="searchFormData"
      label-width="80px"
      @search="handleSearch('SEARCH')"
    />
    <dee-table
      ref="multipleTable"
      :columns="tableColums"
      :data="tableData"
      :selection-row="selectionRow"
      :pagination="pagination"
      :options="{rowKey: 'id'}"
      @pagination-current-change="onPageIndexChange"
      @pagination-size-change="onPageSizeChange"
      @selection-change="selectionChange"
    />
    <span style="display:flex;justify-content: center;padding-top:10px;">
      <el-button
        type="primary"
        class="searchBtn"
        @click="handleSubmit"
      >确定</el-button>

      <el-button
        class="searchBtn"
        @click="handleClose"
      >取消</el-button>
    </span>
  </div>
</template>
<script>
import { copyGroup } from '@/api/userSystem/user.js'
export default {
  name: 'CopyGroup',
  components: { },
  props: {
    groupTree: {
      type: Array,
      default: () => []
    },
    copyGroupItem: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100, 200],
        total: 0
      },
      // 记录分页上选中的数据
      pageSelectGroup: [],
      groupOptions: [],
      searchForm: {
        keywords: ''
      },
      keywords: '',
      // form 表单展示方式配置
      searchFormData: [
        {
          key: 'keywords',
          title: '群组名称',
          component: {
            name: 'el-input',
            placeholder: '支持模糊匹配',
            clearable: true
          }
        }
      ],
      tableColums: [
        { title: '群组名称', key: 'target.name', align: 'center' }
      ],
      tableData: [],
      selectionRow: [],
      orginalData: []
    }
  },
  computed: {

  },
  watch: {
    copyGroupItem: {
      deep: true,
      immediate: true,
      handler: function(val) {
        val && this.getGroupData()
      }
    }
  },
  created() {
  },
  mounted() {
    // this.getGroupData()
  },
  methods: {
    handleSearch() {
      this.keywords = this.searchForm.keywords
      // if (this.searchForm.keywords) {
      //   const reg = this.searchForm.keywords
      //     .replace(/\(/g, '\\(')
      //     .replace(/\)/g, '\\)')
      //     .replace(/\./g, '\\.')
      //   this.tableData = []
      //   this.orginalData.forEach(item => {
      //     const allVal = item.orgName.match(new RegExp(reg, 'ig'))
      //     allVal && this.tableData.push(item)
      //   })
      // } else {
      //   this.tableData = this.orginalData
      // }
      this.tableReset()
      this.getGroupData()
    },
    selectionChange(val) {
      this.selectionRow = val
      this.pageSelectGroup[this.pagination.currentPage] = val
    },
    handleSubmit() {
      const items = this.pageSelectGroup.flat()
      const selectedItems = []
      // 去重
      items.forEach(m => {
        if (!selectedItems.find(d => d.id === m.id)) {
          selectedItems.push(m)
        }
      })
      if (!selectedItems.length) {
        return this.$utils.showMessageError('请先选择数据')
      }
      const params = []
      selectedItems.forEach(n => {
        params.push({
          operator: 'ADD',
          source: {
            operator: 'NO_CHANGE',
            idType: 'DxGroup',
            id: this.copyGroupItem.id
          },
          target: {
            operator: 'NO_CHANGE',
            idType: 'DxGroup',
            id: n.targetId
          }
        })
      })
      copyGroup(params).then(res => {
        this.selectionRow = []
        this.$utils.showMessageSuccess(res.message)
        this.$emit('getGroups')
        this.$emit('handleClose')
      })
    },
    handleClose() {
      this.$emit('handleClose')
    },
    getGroupData() {
      let searchItems = {}
      if (this.keywords) {
        searchItems = {
          'operator': 'AND',
          'items': [
            {
              'fieldName': 'target.name',
              'operator': 'LIKE',
              'value': this.keywords
            }
          ]
        }
      }
      const params = {
        'indices': [
          'DxOrganizationGroupLink'
        ],
        'pageFrom': this.pagination.currentPage,
        'pageSize': this.pagination.pageSize,
        'openProps': [
          {
            'name': 'target',
            'pageFrom': 1,
            'pageSize': 9999
          }
        ],
        'searchItems': {
          'operator': 'AND',
          'items': [

          ],
          'children': ([
            {
              'operator': 'AND',
              'items': [
                {
                  'fieldName': 'id',
                  'operator': 'NEQ',
                  'value': 0
                }
              ]
            },
            {
              'operator': 'AND',
              'items': [
                {
                  'fieldName': 'sourceId',
                  'operator': this.copyGroupItem.orgIdScope ? 'EQ' : 'ISNULL',
                  'value': this.copyGroupItem.orgIdScope || null
                }
              ]
            }
          ]).concat(searchItems)
        }
      }
      this.$api.searchApi('DxOrganizationGroupLink', params).then(res => {
        const items = res.items.content || []
        this.tableData = items.filter(el => {
          return el.target.id !== this.copyGroupItem.id
        })
        this.pagination.total = res.items.totalElements
        this.tableDefaultSelect(items)
      })
    },
    // 页码改变的监听函数
    onPageIndexChange() {
      this.getGroupData()
    },
    // 分页大小改变
    onPageSizeChange() {
      this.tableReset()
    },
    tableReset() {
      // 重置到首页
      Object.assign(this.pagination, {
        total: 0,
        currentPage: 1
      })
      // 分页记录置空
      this.pageSelectGroup = []
      // 当前页选中记录置空
      this.selectionRow = []
    },
    tableDefaultSelect(dataSource) {
      const selectedItems = this.pageSelectGroup.flat()
      if (selectedItems.length > 0) {
        const selectedItemsIdxs = []
        selectedItems.forEach(m => {
          const idx = dataSource.findIndex(d => d.id === m.id)
          if (idx > -1) {
            selectedItemsIdxs.push(idx)
          }
        })
        if (selectedItemsIdxs.length > 0) {
          this.$nextTick(() => {
            const deeTable = this.$refs.multipleTable.$refs.deeTable
            selectedItemsIdxs.forEach(idx => {
              // 这里一定要是 el-table 中的表格数据源
              deeTable.toggleRowSelection(deeTable.tableData[idx])
            })
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" >
.copy-group-com{
  padding-bottom: 10px;
  .dee-table{
    margin-bottom: 10px;
    .dee-table-body{
      height: 100%;
      .el-table{
        height: 100%;
        .el-table__body-wrapper{
          height: calc(100% - 50px);
          overflow-y: scroll;
        }
      }
    }
  }
}
</style>