<!-- 配置人员 组件 -->

<script setup lang="tsx">
import { ContentWrap } from '../components/ContentWrap'
import { useI18n } from '../hooks/web/useI18n'
import { Table } from '../components/Table'
import { ref, unref, nextTick, watch, reactive, toRaw, PropType } from 'vue'
import { ElTree, ElInput, ElDivider, ElMessage } from 'element-plus'
import type { DepartmentItem } from '../api/types/custom'
import { useTable } from '../hooks/web/useTable'
import { Search } from '../components/Search'
import { CrudSchema, useCrudSchemas } from '../hooks/web/useCrudSchemas'
import { getUserList, getDeptTree } from '../api'

const { t } = useI18n()

const props = defineProps({
  // 原先已选择的人员
  selectUsers: {
    type: Array as PropType<any>,
    default: () => []
  }
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getUserList({
      userName: unref(searchParams)?.userName,
      deptId: unref(currentNodeKey),
      current: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: Number(res.data.totalCount) || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'userName',
    label: t('userDemo.username')
  },
  {
    field: 'userNo',
    label: t('userDemo.account'),
    search: {
      hidden: true
    }
  },
  {
    field: 'phone',
    label: '手机号',
    search: {
      hidden: true
    }
  },
  {
    field: 'email',
    label: '邮箱',
    search: {
      hidden: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const selectedUsers = ref<any>([])

const tableRef = ref()

const searchParams = ref<any>({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])
const fetchDepartment = async () => {
  const res = await getDeptTree({})
  departmentList.value = res.data
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: DepartmentItem) => {
  currentNodeKey.value = toRaw(data).id
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data?.name.includes(value)
}

// 已选择的从外面传进来
watch(
  () => props.selectUsers,
  (val) => {
    selectedUsers.value = val
  },
  {
    immediate: true
  }
)

const handleSelect = (selection, row) => {
  const dataIndex = selection.findIndex((item) => item.userId === row.userId)
  // 如果当前操作行不在选中selection里，则对containerList数据进行删除相应行数据
  if (dataIndex === -1) {
    const index = selectedUsers.value.findIndex((item) => item.userId === row.userId)
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(row)
  }
}

const submit = async () => {
  const arr: any[] = []
  toRaw(selectedUsers.value).forEach((item) => {
    arr.push(item?.userId)
  })
  if (arr?.length === 0) {
    ElMessage.warning('请选择人员')
    return null
  }
  return {
    userIds: arr
  }
}

const editTableSelect = async () => {
  await nextTick()
  toRaw(selectedUsers?.value)?.forEach((item) => {
    // 如果表格中数据和containerList中数据userId有相同，则勾选对应行的checkbox
    const index = toRaw(dataList.value)?.findIndex((dataItem) => {
      return dataItem?.userId === item?.userId
    })
    index !== -1 &&
      toRaw(tableRef.value?.elTableRef).toggleRowSelection(toRaw(dataList.value[index]), true)
  })
}

const del = (item) => {
  const index = selectedUsers?.value.findIndex((it) => it.userId === item.userId)
  selectedUsers.value.splice(index, 1)
  const editIndex = toRaw(dataList.value)?.findIndex((dataItem) => {
    return dataItem?.userId === item?.userId
  })
  editIndex !== -1 &&
    toRaw(tableRef.value?.elTableRef).toggleRowSelection(toRaw(dataList.value[editIndex]), false)
}

defineExpose({
  submit
})

watch(
  () => dataList.value,
  async () => {
    editTableSelect()
  },
  {
    deep: true
    // immediate: true
  }
)
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px !overflow-y-auto">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          clearable
        />
      </div>
      <ElDivider />
      <div class="treeContainer">
        <ElTree
          ref="treeEl"
          :data="departmentList"
          default-expand-all
          :expand-on-click-node="false"
          node-key="id"
          :current-node-key="currentNodeKey"
          :props="{
            label: 'name'
          }"
          :filter-node-method="filterNode"
          @current-change="currentChange"
        >
          <template #default="{ data }">
            <div :title="data.name" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
              {{ data.name }}
            </div>
          </template>
        </ElTree>
      </div>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px !overflow-y-auto">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        @select="handleSelect"
        ref="tableRef"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <ContentWrap class="w-250px ml-20px !overflow-y-auto">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ '已选人员' }}</div>
      </div>
      <ElDivider />
      <div class="selected">
        <div v-for="(item, i) in selectedUsers" :key="i" class="selectedList">
          <div class="name">{{ item.userName }}</div>
          <img @click="del(item)" class="del" src="../assets/imgs/del.png" alt="" />
        </div>
      </div>
    </ContentWrap>
  </div>
</template>

<style scoped lang="less">
.selectedList {
  display: flex;
  padding: 2px 8px;
  margin-bottom: 10px;
  cursor: pointer;
  justify-content: space-between;
  align-items: center;

  &:hover {
    background: rgb(102 177 255 / 25%);

    .del {
      display: block;
      width: 16px;
      height: 16px;
    }
  }
}

.del {
  display: none;
  width: 16px;
  height: 16px;
}

:deep(.el-table) {
  thead .el-table-column--selection .el-checkbox {
    display: none;
  }
}
</style>
