<style lang="less" scoped>
.view-div {
  width: 100%;
  height: 100%;
  padding: 10px 0 0 10px;

  .selected-view {
    width: 150px;
    height: 100%;
    float: left;
    font-size: .75rem;
  }

  .selected-view-content {
    width: 100%;
    height: calc(~'100% - 38px');
  }

  .table-view {
    width: calc(~'100% - 160px');
    margin-left: 10px;
    height: 100%;
    float: left;
  }
  .table-view-noselected{
    width: calc(~'100% - 10px')
  }
}
</style>
<template>
  <div class="view-div">
    <div v-show="!hideSelected" class="selected-view" >
      <div style="margin-bottom: 20px; width: 100%;">
        <Checkbox
          :value="selection.length > 0"
          :disabled="selection.length == 0"
          @on-change="allCancel"
        />
        {{"已选（" + selection.length + ")条"}}
      </div>
      <div class="selected-view-content">
        <SelectedView
          :data="selection"
          @on-change="onCancelSelected"
        />
      </div>
    </div>
    <div class="table-view " :class="{'table-view-noselected': hideSelected}">
      <TableView
        ref="_tableView"
        :primaryKey="primaryKey"
        :columns="tableColumns"
        :data="tableDatas"
        :pageTotal="pageTotal"
        :pageSize="pageSize"
        :selection="selection"
        :multiple="multiple"
        :loading="loading"
        :isLeaf="isLeaf"
        :treeDataMap="treeDataMap"
        :structtype="structtype"
        :canSwitchMode="false"
        :searchPlaceholder="searchPlaceholder"
        @on-page-change="onPageChange"
        @on-select="onSelect"
        @on-select-cancel="onSelectCancel"
        @on-select-all="onSelectAll"
        @on-select-all-cancel="onSelectAllCancel"
        @on-search-enter="onSearchEnter"
      />
    </div>
  </div>
</template>
<script>
import TableView from './table-view'
import SelectedView from './option-group'
import baseDataMixin from './baseDataMixin'
export default {
  mixins: [baseDataMixin],
  data() {
    return {
      pageTotal: 0,
      pageSize: 20,
      pageNo: 1,
      total: 0,
      tableDatas: [],
      selection: [],
      searchInfo: '', // 模糊搜索信息
      justSelected: false, // 查看模式
      loading: false,
    }
  },
  props: {
    treeDataMap: {
      type: Object
    },
    groupFieldName: {
      type: String
    },
    treeNode: {
      type: Object,
      required: false,
    },
    value: {
      type: Array,
      required: false,
    },
    primaryKey: {
      type: String,
      required: true,
    },
    tableColumns: {
      type: Array,
      require: true,
    },
  },
  watch: {
    treeNode: {
      handler: function (newVal, oldVal) {
        if (newVal && oldVal && newVal[this.treeKey] == oldVal[this.treeKey]) {
          return
        }
        this.pageNo = 1
        this.refresh(newVal)
      },
      deep: true,
    },
    value: {
      handler: function (newVal) {
        this.selection = JSON.parse(JSON.stringify(newVal))
        this.selection.map((item) => {
          item._checked = true
        })
        this.refreshRowsCheckStatus(newVal, this.tableDatas)
      },
      deep: true,
    },
  },
  components: {
    TableView,
    SelectedView,
  },
  mounted() {
    this.selection = this.value ? JSON.parse(JSON.stringify(this.value)) : []
    this.selection.map((item) => {
      item._checked = true
    })
    this.loading = true
    this.resize()
  },
  methods: {
    save() {
      let _selection = JSON.parse(JSON.stringify(this.selection))
      return _selection
    },
    resize() {
      this.$refs._tableView &&
        this.$refs._tableView.resize &&
        this.$refs._tableView.resize()
    },
    refresh(treeNode) {
      if (!treeNode) {
        this.tableDatas = []
        return
      }
      this.refreshWhenAll(treeNode)
    },
    async refreshWhenAll(treeNode) {
      if (this.isOrg) {
        let param = {
          pagination: true,
          parentcode: treeNode.code,
          searchKey: this.searchInfo,
          queryDataStructure: 'ALL',
          limit: this.pageSize,
          offset: (this.pageNo - 1) * this.pageSize,
        }
        GMS.$http
          .post('/org/data/list', param)
          .then((res) => {
            const { rows, rs, total } = res.data
            this.pageTotal = total
            let _tabledatas = rows
            this.refreshRowsCheckStatus(this.selection, _tabledatas)
            this.tableDatas = _tabledatas
            this.loading = false
          })
          .catch((err) => {
            console.error('获取组织机构失败：' + JSON.stringify(err))
            console.log('error', err)
          })
      } else {
        let that = this
        this.loading = true
        // 更新右侧table
        let postData = {}
        if (this.structtype === 1) {
          const treeData = JSON.parse(JSON.stringify(this.treeNode))
          treeData.children = this.treeDataMap[this.treeNode.code]
          let objectCodes = []
          const getGroupNames = (nodes) => {
            nodes.forEach(item => {
              if (item && item.attributes && item.attributes.objectcode) {
                objectCodes.push(item.attributes.objectcode)
              }
              if (item.children && item.children.length > 0) {
                getGroupNames(item.children)
              }
            })
          }
          getGroupNames([treeData])
          postData = {
            groupFieldName: this.groupFieldName,
            groupname: this.treeNode.attributes.objectcode,
            groupNames: objectCodes,
            tableName: this.tableName,
            pagination: true,
            offset: (this.pageNo - 1) * this.pageSize,
            limit: this.pageSize,
            searchKey: this.searchInfo,
            stopflag: -1,
            queryDataStructure: "ALL",
            authType: this.authType,
            versionDate: this.versionDate,
            expression: this.filterFormular,
            'BI-SYNTAX': null 
          }
        } else {
          postData = {
            pagination: true,
            limit: this.pageSize,
            offset: (this.pageNo - 1) * this.pageSize,
            tableName: this.tableName,
            searchKey: this.searchInfo,
            queryDataStructure: 'ALL',
            queryChildrenType: 'ALL_CHILDREN_WITH_SELF',
            lazyload: false,
            code: treeNode.code === '-'? '': treeNode.code,
            authType: this.authType,
            versionDate: this.versionDate,
            expression: this.filterFormular,
            'BI-SYNTAX': null 
          }
        }
        this.getBaseData(postData)
          .then((response) => {
            if (!(response || response.data)) {
              this.tableDatas = []
              return
            }
            const { rows, rs, total } = response.data

            this.pageTotal = total
            let _tabledatas = rows
            this.refreshRowsCheckStatus(this.selection, _tabledatas)
            this.tableDatas = _tabledatas
            this.$emit('init-list', _tabledatas)
            this.loading = false
          })
          .catch((err) => {
            this.loading = false
            console.error('获取表格信息失败：' + JSON.stringify(XMLHttpRequest))
            console.log('error', err)
          })
      }
    },

    /**
     * 刷新表格每行的勾选状态
     * @param {Array} selected 已经选中的数据集合
     * @param {Array} rows 表格行数据集合
     */
    refreshRowsCheckStatus(selected, rows) {
      let that = this
      rows.map((value) => {
        value._checked = that.isSelected(selected, value)
      })
    },
    /**
     * 判断指定行是否已经被选中
     * @param {Object} row table表格行数据
     */
    isSelected(selected, row) {
      let result = false
      selected.map((value) => {
        if (value[this.primaryKey] == row[this.primaryKey]) {
          result = true
          return
        }
      })
      return result
    },
    onPageChange(pageNo) {
      this.pageNo = pageNo
      this.refresh(this.treeNode)
    },
    onSelect(selection) {
      this.selection = selection
    },
    onSelectCancel(selection, row) {
      this.selection = selection
    },
    onSelectAll(selection) {
      this.selection = selection
    },
    onSelectAllCancel(selection) {
      this.selection = selection
    },
    onSearchEnter(searchInfo) {
      this.searchInfo = searchInfo
      this.pageNo = 1
      this.refresh(this.treeNode)
    },
    onCancelSelected(item) {
      for (let i = this.selection.length - 1; i >= 0; i--) {
        if (this.selection[i].name == item.name) {
          this.selection._checked = false
          this.selection.splice(i, 1)
          break
        }
      }
    },
    allCancel() {
      this.selection.map((item) => {
        item._checked = false
      })
      this.selection = []
    },
  },
}
</script>