<template>
  <c-table ref="tableRef" :option="userOption" :params="{ deptId: deptId }">
    <template #headerLeft>
      <c-button @click="handleClick" type="primary">添加</c-button>
    </template>
    <template #menuLeft="{ record }">
      <c-pop-confirm
        @ok="(done:any) => handleRemove(record, done)"
        :ok-button-props="{ status: 'danger' }"
      >
        <template #content>
          <div style="max-width: 180px">
            <a-typography-text>
              {{ `请确认是否将 "${record.fullName}" 从该部门中移除` }}</a-typography-text
            >
          </div>
        </template>
        <a-button type="text" status="danger"> 移除 </a-button>
      </c-pop-confirm>
    </template>
  </c-table>
  <f-user-select-modal
    v-model:visible="modalVisible"
    ref="userSelectModalRef"
    :select-ids="selectIds"
    :auto-close="false"
    @change="handleChange"
  ></f-user-select-modal>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import userOption from './user-option'
import FUserSelectModal from '@/components/f-user-select-modal/index.vue'
import { removeDeptUser, resetDeptUser, userIdsByDeptId } from '@/api/upms/dept'

const props = defineProps<{
  deptId: string
}>()

// 部门变更重新加载成员表格
const tableRef = ref<any>()
const userSelectModalRef = ref<any>()
const reload = () => {
  nextTick(() => {
    tableRef.value.load(true)
    userSelectModalRef.value.load()
  })
}
watch(
  () => props.deptId,
  () => {
    reload()
  },
  { immediate: true }
)

// 添加成员逻辑
const modalVisible = ref(false)
const selectIds = ref([])
const handleClick = (done: Function) => {
  userIdsByDeptId(props.deptId)
    .then((res) => {
      selectIds.value = res
    })
    .finally(() => {
      done()
      modalVisible.value = true
    })
}
const handleChange = (checkedIds: string[], nodes: any, done: Function) => {
  resetDeptUser(props.deptId, checkedIds)
    .then(() => {
      done()
      nextTick(() => {
        tableRef.value.load(true)
      })
    })
    .catch(() => {
      done(false)
    })
}

const handleRemove = (record: any, done: Function) => {
  removeDeptUser(props.deptId, record.id)
    .then(() => {
      done()
      Message.success('移除成功')
      reload()
    })
    .catch(() => {
      done(false)
    })
}
</script>

<style scoped></style>
