<script lang="ts" setup>
/**
 * OA 通知场景管理列表页
 * 新增/编辑走内页表单；列表展示启用平台与发送方式，点击平台 Tag 预览消息
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { onDeactivated, ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { deleteOaScene, getOaSceneInfo } from './api';
import MsgPreviewModal from './components/msg-preview-modal.vue';
import SceneFormPage from './components/form-page.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

defineOptions({ name: 'OaScene' });

const showForm = ref(false);
const formValues = ref<any>({});
const formIsUpdate = ref(false);
const hasTopTableDropDownActions = ref(false);

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,
});

/** 列表点击平台 Tag → 消息预览弹窗 */
const [PreviewModalComponent, previewModalApi] = useVbenModal({
  connectedComponent: MsgPreviewModal,
});

/**
 * 打开平台消息预览：取该行 message_config 中对应平台的类型与 payload
 */
function openPlatformPreview(row: any, summary: any) {
  const code = String(summary?.platform_code || '');
  const config = row?.message_config?.[code] || {};
  const messageType = String(
    config.message_type || summary?.message_type || '',
  );
  if (!messageType) {
    message.warning('该平台暂无消息配置');
    return;
  }
  previewModalApi.setData({
    platformName: summary?.platform_name || code,
    platformCode: code,
    messageType,
    payload: config.payload || {},
  });
  previewModalApi.open();
}

/**
 * 打开新增/编辑内页：编辑必须拉详情
 */
async function openForm(row: any = {}, isUpdate = false) {
  let values: any = {};
  if (isUpdate && row?.id) {
    try {
      values = await getOaSceneInfo(row.id);
    } catch (e) {
      console.error('加载场景详情失败', e);
      message.error('加载场景详情失败');
      return;
    }
  }
  formValues.value = values;
  formIsUpdate.value = isUpdate;
  showForm.value = true;
}

function onFormBack() {
  showForm.value = false;
}

function onFormSaved() {
  gridApi.query();
}

/**
 * 离开路由或 KeepAlive 失活时回到列表态
 * 避免缓存卡在表单页，以及 Transition 卸载时 DOM 节点悬空
 */
function resetFormView() {
  showForm.value = false;
}

onDeactivated(resetFormView);
onBeforeRouteLeave(() => {
  resetFormView();
});

/**
 * 删除场景（支持单个和批量）
 */
const deleteApi = (row: any) => {
  let ids: any[] = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item: any) => item.id);
  }
  deleteOaScene({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};
</script>

<!-- 单根节点：避免 KeepAlive + Transition 对多根组件报错导致切走空白 -->
<template>
  <div class="oa-scene-page">
    <div v-show="!showForm">
      <Page auto-content-height title="OA 通知场景管理">
        <Grid>
          <template #toolbar-actions>
            <TableAction
              :actions="[
                {
                  label: '新增',
                  type: 'primary',
                  icon: 'ant-design:plus-outlined',
                  onClick: openForm.bind(null),
                },
              ]"
              :drop-down-actions="[
                {
                  label: '批量删除',
                  icon: 'ant-design:delete-outlined',
                  ifShow: hasTopTableDropDownActions,
                  popConfirm: {
                    title: '确定删除吗？',
                    confirm: deleteApi.bind(null, false),
                  },
                },
              ]"
            />
          </template>

          <!-- 启用平台：点击名称标签可预览该平台消息 -->
          <template #platforms="{ row }">
            <div
              v-if="(row.platform_summaries || []).length"
              class="tag-wrap"
            >
              <Tag
                v-for="s in row.platform_summaries"
                :key="s.platform_code"
                color="processing"
                class="platform-tag"
                @click="openPlatformPreview(row, s)"
              >
                {{ s.platform_name || s.platform_code }}
              </Tag>
            </div>
            <span v-else class="text-gray-400">未启用</span>
          </template>

          <!-- 发送方式：通道 · 消息类型 -->
          <template #send_mode="{ row }">
            <div
              v-if="(row.platform_summaries || []).length"
              class="tag-wrap"
            >
              <Tag
                v-for="s in row.platform_summaries"
                :key="`mode-${s.platform_code}`"
                :color="s.channel === '应用API' ? 'orange' : 'blue'"
              >
                {{ s.channel
                }}{{ s.message_type ? ` · ${s.message_type}` : '' }}
              </Tag>
            </div>
            <span v-else class="text-gray-400">-</span>
          </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: openForm.bind(null, row, true),
                },
                {
                  label: '删除',
                  type: 'link',
                  icon: 'ant-design:delete-outlined',
                  size: 'small',
                  popConfirm: {
                    title: '确定删除吗？',
                    confirm: deleteApi.bind(null, row.id),
                  },
                },
              ]"
            />
          </template>
        </Grid>
        <PreviewModalComponent />
      </Page>
    </div>

    <SceneFormPage
      v-if="showForm"
      :values="formValues"
      :is-update="formIsUpdate"
      @back="onFormBack"
      @saved="onFormSaved"
    />
  </div>
</template>

<style scoped>
.tag-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.platform-tag {
  cursor: pointer;
}

.platform-tag:hover {
  opacity: 0.85;
}
</style>
