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

<script setup lang="tsx">
import { ContentWrap } from '../../components/ContentWrap'
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'
import { ISelectUser } from './types'
import { Recordable } from 'vite-plugin-mock'

const props = defineProps({
  // 原先已选择的人员
  selectUsers: {
    type: Array as PropType<ISelectUser[]>,
    default: () => []
  },
  // 引用组件往外暴露的所使用的key值
  userKey: {
    type: String,
    default: 'userId'
  },
  // 额外的人员请求接口
  extraTableAxios: {
    type: [Function, null],
    default: null
  },
  // 额外的人员请求接口参数
  extraTableAxiosParams: {
    type: Object as PropType<Recordable>,
    default: () => ({})
  },
  // 额外的tree
  extraTree: {
    type: Array as PropType<DepartmentItem[]>,
    default: () => null
  },
  // 树的属性
  treeProps: {
    type: Object as PropType<Recordable>,
    default: () => ({})
  },
  //   树是否只支持勾选，不支持点选
  isCheckSelect: {
    type: Boolean,
    default: false
  }
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const promise = props.extraTableAxios || getUserList

    const res = await promise({
      userName: unref(searchParams)?.userName,
      deptId: unref(currentNodeKey),
      deptIdList: props.isCheckSelect ? unref(selectDeptIds) : undefined,
      current: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams),
      ...props.extraTableAxiosParams
    })
    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: '序号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'userName',
    label: '姓名'
  },
  {
    field: 'userNo',
    label: '账号',
    search: {
      hidden: true
    }
  },
  {
    field: 'phone',
    label: '手机号',
    search: {
      hidden: true
    }
  },
  {
    field: 'email',
    label: '邮箱',
    search: {
      hidden: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const selectedUsers = ref<ISelectUser[]>([])

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
}

if (props.extraTree) {
  departmentList.value = props.extraTree
} else fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data?.name.includes(value)
}

// 部门点击
const currentChange = (data: DepartmentItem) => {
  if (props.isCheckSelect) return

  currentNodeKey.value = toRaw(data).id
  currentPage.value = 1
  getList()
}

// 部门勾选 初始值为-1 为了不加载全部人员
const selectDeptIds = ref<(string | number)[]>([-1])
const checkChange = (_data, nodes) => {
  const { checkedNodes } = nodes
  if (checkedNodes.length) {
    selectDeptIds.value = checkedNodes.filter((i) => !i.disabled).map((j) => j.id)
  } else {
    selectDeptIds.value = [-1]
  }
  currentPage.value = 1
  getList()
}

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

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

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

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

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

defineExpose({
  submit
})

watch(
  () => dataList.value,
  async () => {
    await editTableSelect()
  },
  {
    deep: 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">部门列表</div>
        <ElInput v-model="currentDepartment" class="flex-[2]" placeholder="搜索部门" 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'
          }"
          v-bind="props.treeProps"
          :filter-node-method="filterNode"
          @current-change="currentChange"
          @check="checkChange"
        >
          <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
        }"
        row-key="userNo"
        height="440px"
      />
    </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 || `未知用户名${i + 1}` }}</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>
