<template>
  <div class="choose-markers">
    <el-button type="primary" :disabled="!subjectCode || !mainNumber" @click="openDialog"
      >选择评卷员{{ confirmResult?.length ? `(已选${confirmResult.length}人)` : '' }}</el-button
    >
    <base-dialog v-model="modalVisible" title="选择评卷员" :width="450" class="marker-dialog">
      <div class="m-b-base">
        <el-input
          v-model.trim="filterText"
          placeholder="输入评卷员登录名或姓名查询"
          clearable
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-button type="primary" @click="filterSearch">查询</el-button>
      </div>
      <vxe-table
        :key="tableKey"
        size="small"
        show-overflow
        :max-height="tableMaxHeight"
        :tree-config="{ childrenField: 'markers', rowField: 'id', expandAll: true, transform: true }"
        :data="tableData"
        :checkbox-config="{ highlight: false }"
        :scroll-y="{ enabled: true, gt: 40 }"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <vxe-column type="checkbox" title="" width="80" tree-node></vxe-column>
        <vxe-column field="showName" title="姓名">
          <template #default="{ row }">
            <span :style="{ fontWeight: !row.parentId ? 'bold' : 'normal' }">{{ row.showName }}</span>
          </template>
        </vxe-column>
      </vxe-table>
      <template #footer>
        <div class="flex justify-end">
          <confirm-button
            :disabled="!chooseResult.length"
            @confirm="confirm"
            @cancel="modalVisible = false"
          ></confirm-button>
        </div>
      </template>
    </base-dialog>
  </div>
</template>

<script name="ChooseMarkers" lang="ts" setup>
import { watch, ref, computed } from 'vue'
import useFetch from '@/hooks/useFetch'
import { ElButton, ElInput } from 'element-plus'
import BaseDialog from '../element/BaseDialog.vue'
import { VxeTableEvents } from 'vxe-table'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import { cloneDeep } from 'lodash-es'

const tableKey = ref(Date.now() + '')
const emits = defineEmits(['user-list'])
const tableMaxHeight = window.innerHeight - 150 + 'px'
const modalVisible = ref(false)
const { fetch: fetchMarkers, result } = useFetch('adminGetMarkers')
const filterText = ref('')
const computedFilterText = ref('')
const filterSearch = () => {
  computedFilterText.value = filterText.value
  chooseResult.value = []
  tableKey.value = Date.now() + ''
}
const tableData = computed(() => {
  let arr = []
  let res = result.value || []
  for (let i = 0; i < res.length; i++) {
    let item = res[i]
    item.id = '_' + item.markingGroupNumber
    item.showName = `第${item.markingGroupNumber}组`
    item.parentId = null
    item.loginName = ''
    let children = item.markers || []

    if (
      !(
        computedFilterText.value &&
        !children.find((item: any) => {
          return item.loginName.includes(computedFilterText.value) || item.name.includes(computedFilterText.value)
        })
      )
    ) {
      arr.push({ ...item })
    }
    for (let j = 0; j < children.length; j++) {
      let child = children[j]
      let v = {
        id: child.id + '',
        parentId: item.id,
        showName: child.loginName + '-' + child.name,
        loginName: child.loginName,
      }
      if (
        !(
          computedFilterText.value &&
          !(child.loginName.includes(computedFilterText.value) || child.name.includes(computedFilterText.value))
        )
      ) {
        arr.push({ ...v })
      }
    }
  }
  return arr
  //以下为大数据量下的测试代码，经验证不卡顿
  // let arr = result.value || []
  // let arr2 = []
  // for (let i = 0; i < 10000; i++) {
  //   let item = JSON.parse(JSON.stringify(arr[0]))
  //   item.id = Math.random() + ''
  //   item.parentId = null
  //   item.showName = '组组组'
  //   arr2.push({ ...item })
  //   for (let j = 0; j < item.markers.length; j++) {
  //     let v = { id: Math.random(), parentId: item.id, showName: item.markers[j].loginName + '-' + item.markers[j].name }
  //     arr2.push({ ...v })
  //   }
  // }
  // return arr2
})
const props = defineProps<{
  subjectCode: string | number | undefined
  mainNumber: string | number | undefined
}>()
watch([() => props.subjectCode, () => props.mainNumber], (valArr) => {
  if (valArr[0] && valArr[1]) {
    fetchMarkers({ subjectCode: valArr[0], mainNumber: valArr[1] })
  }
})
const chooseResult = ref<any>([])
const confirmResult = ref<any>([])
const selectChangeEvent: VxeTableEvents.CheckboxChange<any> = ({ $table }) => {
  const records = $table.getCheckboxRecords()
  // console.info(`勾选${records.length}个树形节点`, records)
  chooseResult.value = records.filter((item) => !!item.loginName)
}

const confirm = () => {
  confirmResult.value = cloneDeep(chooseResult.value)
  emits('user-list', [...confirmResult.value])
  modalVisible.value = false
}

const openDialog = () => {
  tableKey.value = Date.now() + ''
  modalVisible.value = true
}
</script>

<style lang="scss" scoped>
.choose-markers {
  max-height: 100vh;
}
</style>
