<script lang="ts" setup>
/**
 * OA 群聊管理页
 * Tab：员工（组织架构）| 群聊；localStorage 记住上次选中的 Tab
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { message, Tabs, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import { getOaPlatformList } from '#/views/system/oa-platform/api';

import { deleteOaChat, syncOaCustomerGroups } from './api';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';
import FormModalDemo from './components/modal.vue';
import CreateAppChatModalDemo from './components/create-app-chat-modal.vue';
import EmployeePanel from './components/employee-panel.vue';

defineOptions({ name: 'OaChat' });

/** Tab 记忆：employee=员工 chat=群聊 */
const TAB_STORAGE_KEY = 'oa_chat_active_tab';
const activeKey = ref('chat');

function readStoredTab() {
  const stored = localStorage.getItem(TAB_STORAGE_KEY);
  if (stored === 'employee' || stored === 'chat') {
    activeKey.value = stored;
  }
}

function handleTabChange(key: string | number) {
  activeKey.value = String(key);
  localStorage.setItem(TAB_STORAGE_KEY, String(key));
}

const hasTopTableDropDownActions = ref(false);
const syncLoading = ref(false);
const platformMap = ref<Record<string, any>>({});

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const [CreateAppChatModal, createAppChatModalApi] = useVbenModal({
  connectedComponent: CreateAppChatModalDemo,
});

const showModal = (data = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

const showCreateAppChat = () => {
  createAppChatModalApi.setData({ gridApi });
  createAppChatModalApi.open();
};

/**
 * 同步企微客户群（92120）
 */
const handleSyncCustomerGroups = async () => {
  syncLoading.value = true;
  try {
    const res = await syncOaCustomerGroups({ platform_code: 'work_wechat_app' });
    const data = res?.data ?? res ?? {};
    message.success(
      `同步完成：匹配 ${data.matched ?? 0}，新建 ${data.created ?? 0}，更新 ${data.updated ?? 0}，跳过 ${data.skipped ?? 0}`,
    );
    gridApi.query();
  } catch (e: any) {
    message.error(e?.message || '同步失败');
  } finally {
    syncLoading.value = false;
  }
};

const deleteApi = (row: any) => {
  let ids: any[] = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item: any) => item.id);
  }
  deleteOaChat({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};

async function loadPlatforms() {
  try {
    const list = await getOaPlatformList();
    const rows: any[] = Array.isArray(list) ? list : list?.data || [];
    platformMap.value = rows.reduce(
      (acc, item) => {
        acc[item.platform_code] = item;
        return acc;
      },
      {} as Record<string, any>,
    );
  } catch (e) {
    console.error('加载平台列表失败', e);
  }
}

onMounted(() => {
  readStoredTab();
  loadPlatforms();
});
</script>

<template>
  <Page title="OA 群聊管理">
    <FormModal />
    <CreateAppChatModal />
    <Tabs :active-key="activeKey" @change="handleTabChange">
      <Tabs.TabPane key="employee" tab="员工">
        <EmployeePanel v-if="activeKey === 'employee'" />
      </Tabs.TabPane>
      <Tabs.TabPane key="chat" tab="群聊">
        <Grid v-if="activeKey === 'chat'">
          <template #toolbar-actions>
            <TableAction
              :actions="[
                {
                  label: '新增',
                  type: 'primary',
                  icon: 'ant-design:plus-outlined',
                  onClick: showModal.bind(null),
                },
                {
                  label: '同步客户群',
                  type: 'default',
                  icon: 'ant-design:cloud-sync-outlined',
                  loading: syncLoading,
                  onClick: handleSyncCustomerGroups,
                },
                {
                  label: '创建应用群',
                  type: 'default',
                  icon: 'ant-design:usergroup-add-outlined',
                  onClick: showCreateAppChat,
                },
              ]"
              :drop-down-actions="[
                {
                  label: '批量删除',
                  icon: 'ant-design:delete-outlined',
                  ifShow: hasTopTableDropDownActions,
                  popConfirm: {
                    title: '确定删除吗？',
                    confirm: deleteApi.bind(null, false),
                  },
                },
              ]"
            />
          </template>
          <template #platform_code="{ row }">
            <Tag v-if="platformMap[row.platform_code]" color="processing">
              {{ platformMap[row.platform_code].name }}
            </Tag>
            <span v-else>{{ row.platform_code }}</span>
          </template>
          <template #chat_kind="{ row }">
            <Tag :color="row.chat_kind === 1 ? 'blue' : 'orange'">
              {{ row.chat_kind === 1 ? '应用群聊' : '客户群' }}
            </Tag>
          </template>
          <template #status="{ row }">
            <Tag :color="row.status === 1 ? 'success' : 'default'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </Tag>
          </template>
          <template #toolbar-tools></template>
          <template #action="{ row }">
            <TableAction
              :actions="[
                {
                  label: '编辑',
                  type: 'link',
                  icon: 'uil:edit',
                  size: 'small',
                  onClick: showModal.bind(null, row, true),
                },
                {
                  label: '删除',
                  type: 'link',
                  icon: 'ant-design:delete-outlined',
                  size: 'small',
                  popConfirm: {
                    title: '确定删除吗？',
                    confirm: deleteApi.bind(null, row.id),
                  },
                },
              ]"
            />
          </template>
        </Grid>
      </Tabs.TabPane>
    </Tabs>
  </Page>
</template>
