<template>
  <PmDialog
    v-model="dialoagVisible"
    :title="'选择' + title"
    width="1200px"
    style="max-height: 50vh"
  >
    <div class="container">
<!--      <div class="left">-->
<!--        <el-input-->
<!--          style="width: 80%; margin-bottom: 0.625rem"-->
<!--          placeholder="请输入部门名称"-->
<!--          v-model="deptName"-->
<!--        />-->
<!--        <el-scrollbar height="31.25rem">-->
<!--          <el-tree-->
<!--            ref="deptTreeRef"-->
<!--            :data="deptTree"-->
<!--            :props="defaultProps"-->
<!--            :filter-node-method="filterNode"-->
<!--            @node-click="handleNodeClick"-->
<!--            value-key="id"-->
<!--            placeholder="请选择归属部门"-->
<!--          />-->
<!--        </el-scrollbar>-->
<!--      </div>-->
      <div class="right">
        <ColumnItem class="content">
          <el-form inline >
            <el-form-item :label="title + '名称'">
              <el-input placeholder="请输入" v-model="queryParams.nickName" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchData">查询</el-button>
              <el-button @click="resaltData">重置</el-button>
            </el-form-item>
          </el-form>
        </ColumnItem>
        <ColumnItem class="content">
          <el-table
            ref="treeRef"
            style="height: 50vh; overflow: auto"
            :data="tabList"
            v-loading="loading"
            :highlight-current-row="!props.multiple"
            @current-change="nodeClick"
            @selection-change="handleSelectionChange"
            row-key="ID"
          >
            <el-table-column v-if="props.multiple" type="selection" width="55" />
            <el-table-column type="index" width="50" />
            <el-table-column prop="nick_name" label="用户名称" />
            <el-table-column prop="phone" label="手机号" />
          </el-table>
        </ColumnItem>
        <el-pagination
          class="pagination"
          v-model:current-page="queryParams.page"
          background
          v-model:page-size="queryParams.pageSize"
          :total="total"
          @size-change="getStaffList"
          @current-change="getStaffList"
        />
      </div>
    </div>
    <div style="padding: 10px; display: flex; justify-content: center">
      <el-button
        @click="requireDiolag"
        type="primary"
        :disabled="props.multiple ? choosedTableRows.length < 1 : !selectDept"
      >确定</el-button
      >
      <el-button @click="dialoagVisible = false">取消</el-button>
    </div>
  </PmDialog>
</template>

<script setup>
  import {onMounted, ref, watch, nextTick } from 'vue'
  import PmDialog from '@/components/PmDialog/pm-dialog.vue'
  import ColumnItem from '@/components/columnItem/ColumnItem.vue'
  import { getTechers } from '@/api/goods/index.js'
  // import { listUser } from '@/api/system/user'
  const treeRef = ref()
  const props = defineProps({
    multiple: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '收款人'
    }
  })
  const emit = defineEmits(['getRecipientInfo'])
  const loading = ref(false)
  const dialoagVisible = ref(false)
  const deptName = ref(null)
  const selectDept = ref(null),
    choosedTableRows = ref([]),
    unChoosed = ref([])
  // 使用Set存储选中ID（更高效的存储方式）
  const selectedIds = ref(new Set())
  // const deptTree = ref([])
  const tabList = ref([])
  const total = ref(0)
  // const defaultProps = ref({ value: 'value', label: 'label', children: 'children' })
  const queryParams = ref({
    pageSize: 10,
    page: 1,
    deptId: null,
    nickName: ''
  })

  onMounted(() => {
    // getDeptList()
    getStaffList()
  })
  const deptTreeRef = ref()
  watch(
    () => deptName.value,
    (val) => {
      deptTreeRef.value.filter(val)
    }
  )

  function open() {
    dialoagVisible.value = true
  }
  // async function getDeptList() {
  //   deptTree.value = await getDeptTree()
  // }
  let depClick = ref(false)
  function getStaffList() {
    loading.value = true
    getTechers(queryParams.value)
      .then(async (res) => {
        tabList.value = res.data.list
        total.value = res.data.total
        if(props.multiple) {
          // 下一Tick执行确保DOM更新完成
          depClick.value = true
          await nextTick(() => {
            // 根据存储的ID恢复选中状态
            tabList.value.forEach((row) => {
              if (selectedIds.value.has(row.ID)) {
                treeRef.value.toggleRowSelection(row, true)
              }
            })
          })
          depClick.value = false
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
  function searchData() {
    getStaffList()
  }
  function resaltData() {
    queryParams.value.pageSize = 10
    queryParams.value.page = 1
    queryParams.value.nickName = ''
    getStaffList()
  }

  // function handleNodeClick(node) {
  //   queryParams.value.deptId = node.id
  //   getStaffList()
  // }
  function nodeClick(e) {
    if(!props.multiple) {
      selectDept.value = e
    }
  }
  function handleSelectionChange(selection) {
    if (props.multiple) {
      if (!depClick.value) {
          // This is a user interaction on the current page.
          const selectedOnPageIds = new Set(selection.map(row => row.ID));

          // Iterate over all items on the current page to see what was selected or unselected.
          tabList.value.forEach(rowOnPage => {
              if (selectedOnPageIds.has(rowOnPage.ID)) {
                  selectedIds.value.add(rowOnPage.ID);
              } else {
                  selectedIds.value.delete(rowOnPage.ID);
              }
          });
      }
      choosedTableRows.value = Array.from(selectedIds.value)
        .map((id) => [...tabList.value, ...choosedTableRows.value].find((r) => r.ID === id))
        .filter(Boolean)
    }
  }
  // function filterNode(value, data) {
  //   if (!value) return true
  //   return data.label.includes(value)
  // }
  function requireDiolag() {
    const dataToEmit = props.multiple ? choosedTableRows.value : selectDept.value;
    if ((props.multiple && dataToEmit.length === 0) || (!props.multiple && !dataToEmit)) {
      // Optional: show a message to the user
      return;
    }
    emit('getRecipientInfo', dataToEmit)
    dialoagVisible.value = false
  }
  defineExpose({
    open
  })
</script>

<style scoped lang="scss">
  .container {
    display: flex;
    .left {
      width: 17.5rem;
      flex-shrink: 0;
    }
    .right {
      flex: 1;
      :deep(.content:first-child) {
        margin-bottom: 0;
      }
      :deep(.cont) {
        padding: 0;
      }
    }
  }
</style>
