<script lang="ts" setup>
/**
 * OA 群聊页「员工」面板
 * 左侧企微部门树自动分类，右侧员工列表；支持同步组织架构与关键词搜索
 */
import { onMounted, ref } from 'vue';

import {
  Button,
  Empty,
  InputSearch,
  message,
  Pagination,
  Spin,
  Table,
  Tag,
  Tree,
} from 'ant-design-vue';

import {
  getOaWwDeptTree,
  getOaWwUserList,
  syncOaWwOrg,
} from '../api/org';

const syncLoading = ref(false);
const treeLoading = ref(false);
const tableLoading = ref(false);
const treeData = ref<any[]>([]);
const selectedDeptId = ref<number | null>(null);
const keyword = ref('');
const users = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);

/**
 * 同步企微组织架构
 */
async function handleSync() {
  syncLoading.value = true;
  try {
    const res = await syncOaWwOrg({ platform_code: 'work_wechat_app' });
    const data = res?.data ?? res ?? {};
    message.success(
      `同步完成：部门 ${data.dept_count ?? 0}，成员 ${data.user_count ?? 0}`,
    );
    selectedDeptId.value = null;
    page.value = 1;
    await Promise.all([loadTree(), loadUsers()]);
  } catch (e: any) {
    message.error(e?.message || '同步失败，请确认平台凭证与通讯录权限');
  } finally {
    syncLoading.value = false;
  }
}

/**
 * 加载部门树
 */
async function loadTree() {
  treeLoading.value = true;
  try {
    const res = await getOaWwDeptTree({ platform_code: 'work_wechat_app' });
    const data = res?.data ?? res ?? [];
    treeData.value = Array.isArray(data) ? data : [];
  } catch (e) {
    console.error(e);
    treeData.value = [];
  } finally {
    treeLoading.value = false;
  }
}

/**
 * 加载员工列表
 */
async function loadUsers() {
  tableLoading.value = true;
  try {
    const res = await getOaWwUserList({
      platform_code: 'work_wechat_app',
      dept_id: selectedDeptId.value || 0,
      keyword: keyword.value.trim(),
      page: page.value,
      pageSize: pageSize.value,
    });
    const data = res?.data ?? res ?? {};
    users.value = Array.isArray(data.items) ? data.items : [];
    total.value = Number(data.total || 0);
  } catch (e) {
    console.error(e);
    users.value = [];
    total.value = 0;
  } finally {
    tableLoading.value = false;
  }
}

/**
 * 选中部门节点
 */
function onSelectDept(keys: (string | number)[]) {
  const key = keys[0];
  selectedDeptId.value = key !== undefined && key !== null ? Number(key) : null;
  page.value = 1;
  loadUsers();
}

function onSearch() {
  page.value = 1;
  loadUsers();
}

function onPageChange(p: number, ps: number) {
  page.value = p;
  pageSize.value = ps;
  loadUsers();
}

const columns = [
  { title: 'userid', dataIndex: 'userid', key: 'userid', width: 140 },
  { title: '姓名', dataIndex: 'name', key: 'name', width: 100 },
  { title: '手机号', dataIndex: 'mobile', key: 'mobile', width: 120 },
  {
    title: '主部门',
    dataIndex: 'main_department_name',
    key: 'main_department_name',
    width: 140,
  },
  { title: '职位', dataIndex: 'position', key: 'position', width: 120 },
  {
    title: '匹配系统员工',
    key: 'matched',
    width: 140,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 90,
  },
];

function statusLabel(status: number) {
  const map: Record<number, string> = {
    1: '已激活',
    2: '已禁用',
    4: '未激活',
    5: '退出企业',
  };
  return map[status] || String(status);
}

onMounted(async () => {
  await loadTree();
  await loadUsers();
});
</script>

<template>
  <div class="employee-panel flex flex-col gap-3">
    <div class="flex flex-wrap items-center gap-2">
      <Button type="primary" :loading="syncLoading" @click="handleSync">
        同步组织架构
      </Button>
      <InputSearch
        v-model:value="keyword"
        allow-clear
        placeholder="搜索姓名 / userid / 手机号"
        class="w-[280px]"
        @search="onSearch"
      />
      <span class="text-xs text-gray-400">
        需平台凭证且应用已开通通讯录读权限；匹配仅展示，不自动绑定
      </span>
    </div>

    <div class="flex gap-3">
      <!-- 左侧部门树：固定最大高度，内部滚动，避免撑高整页 -->
      <aside
        class="flex w-[260px] shrink-0 flex-col rounded-lg border border-border bg-card p-3"
        style="max-height: 560px"
      >
        <div class="mb-2 text-sm font-medium">组织架构</div>
        <Spin :spinning="treeLoading">
          <div class="overflow-auto" style="max-height: 500px">
            <Empty
              v-if="!treeLoading && treeData.length === 0"
              description="暂无部门，请先同步"
              :image="Empty.PRESENTED_IMAGE_SIMPLE"
            />
            <Tree
              v-else
              :tree-data="treeData"
              :selected-keys="
                selectedDeptId !== null ? [String(selectedDeptId)] : []
              "
              default-expand-all
              @select="onSelectDept"
            />
          </div>
        </Spin>
      </aside>

      <!-- 右侧员工表：不设自适应高度，内容自然撑开 + 横向滚动 -->
      <div class="min-w-0 flex-1 rounded-lg border border-border bg-card p-3">
        <Table
          size="small"
          :columns="columns"
          :data-source="users"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :scroll="{ x: 900 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'matched'">
              <Tag v-if="record.matched_admin_id" color="success">
                {{ record.matched_admin_name || `#${record.matched_admin_id}` }}
              </Tag>
              <span v-else class="text-gray-400">未匹配</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="record.status === 1 ? 'success' : 'default'">
                {{ statusLabel(Number(record.status)) }}
              </Tag>
            </template>
          </template>
        </Table>
        <div class="mt-3 flex justify-end">
          <Pagination
            :current="page"
            :page-size="pageSize"
            :total="total"
            show-size-changer
            :page-size-options="['10', '20', '50', '100']"
            @change="onPageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>
