<script lang="ts" setup>
import type { AppHomePopupItem } from '#/api/legacy/app-system';

import { computed, reactive, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';

import {
  Button,
  Card,
  Input,
  InputNumber,
  message,
  Modal,
  Pagination,
  Select,
  Space,
  Switch,
  Table,
  Tag,
} from 'antdv-next';

import {
  deleteAppHomePopup,
  pageAppHomePopups,
  saveAppHomePopup,
} from '#/api/legacy/app-system';
import InlineFilterField from '#/views/_shared/inline-filter-field.vue';
import InlineFilterToolbar from '#/views/_shared/inline-filter-toolbar.vue';
import { getAllowedSysOrigins } from '#/views/system/shared';

defineOptions({ name: 'AppSystemHomePopupManager' });

const jumpTypeOptions = [
  { label: 'H5', value: 'H5' },
  { label: '端内路由', value: 'APP_ROUTE' },
  { label: '游戏', value: 'GAME' },
  { label: '无跳转', value: 'NOOP' },
];

const columns = [
  { dataIndex: 'enabled', key: 'enabled', title: '状态', width: 90 },
  { dataIndex: 'popupKey', key: 'popupKey', title: '弹窗 key', width: 160 },
  { dataIndex: 'limitDays', key: 'limitDays', title: 'limit时间(天)', width: 130 },
  { dataIndex: 'description', key: 'description', title: '描述', width: 220 },
  { dataIndex: 'title', key: 'title', title: '标题', width: 180 },
  { dataIndex: 'jumpType', key: 'jumpType', title: '跳转类型', width: 120 },
  { dataIndex: 'jumpUrl', key: 'jumpUrl', title: '跳转地址', width: 220 },
  { dataIndex: 'priority', key: 'priority', title: '优先级', width: 100 },
  { dataIndex: 'version', key: 'version', title: '版本', width: 90 },
  { dataIndex: 'updateTime', key: 'updateTime', title: '更新时间', width: 180 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 130, fixed: 'right' as const },
];

const accessStore = useAccessStore();
const sysOriginOptions = computed(() => {
  const options = getAllowedSysOrigins(accessStore.accessCodes || []);
  return options.length > 0 ? options : getAllowedSysOrigins([]);
});

const loading = ref(false);
const saving = ref(false);
const formOpen = ref(false);
const formTitle = ref('新增弹窗');
const list = ref<AppHomePopupItem[]>([]);
const total = ref(0);

const query = reactive<Record<string, any>>({
  cursor: 1,
  limit: 20,
  popupKey: '',
  scene: 'APP_ENTER',
  sysOrigin: '',
});

const form = reactive<Record<string, any>>(createForm());

function createForm() {
  return {
    description: '',
    enabled: true,
    id: '',
    image: '',
    jumpType: 'NOOP',
    jumpUrl: '',
    limitDays: 7,
    name: '',
    popupKey: '',
    priority: 10,
    scene: 'APP_ENTER',
    title: '',
    version: 1,
  };
}

function resetForm() {
  Object.assign(form, createForm());
}

async function loadData(reset = false) {
  if (!query.sysOrigin) {
    return;
  }
  if (reset) {
    query.cursor = 1;
  }
  loading.value = true;
  try {
    const result = await pageAppHomePopups({ ...query });
    list.value = result.records || [];
    total.value = Number(result.total || 0);
  } finally {
    loading.value = false;
  }
}

function handlePageChange(page: number, pageSize: number) {
  query.cursor = page;
  query.limit = pageSize;
  void loadData();
}

function handleCreate() {
  resetForm();
  formTitle.value = '新增弹窗';
  formOpen.value = true;
}

function handleEdit(record: AppHomePopupItem) {
  resetForm();
  Object.assign(form, {
    description: record.description || '',
    enabled: record.enabled !== false,
    id: record.id || '',
    image: record.image || '',
    jumpType: record.jumpType || 'NOOP',
    jumpUrl: record.jumpUrl || '',
    limitDays: Number(record.limitDays ?? 7),
    name: record.name || '',
    popupKey: record.popupKey || '',
    priority: Number(record.priority ?? 10),
    scene: record.scene || 'APP_ENTER',
    title: record.title || '',
    version: Number(record.version ?? 1),
  });
  formTitle.value = '编辑弹窗';
  formOpen.value = true;
}

function validateForm() {
  if (!String(form.popupKey || '').trim()) {
    message.warning('请输入弹窗 key');
    return false;
  }
  if (Number(form.limitDays) < 0) {
    message.warning('limit 时间不能小于 0');
    return false;
  }
  if (!String(form.description || '').trim()) {
    message.warning('请输入描述');
    return false;
  }
  return true;
}

async function handleSubmit() {
  if (!validateForm()) {
    return;
  }
  saving.value = true;
  try {
    await saveAppHomePopup({
      description: String(form.description || '').trim(),
      enabled: Boolean(form.enabled),
      id: form.id || undefined,
      image: String(form.image || '').trim(),
      jumpType: String(form.jumpType || '').trim(),
      jumpUrl: String(form.jumpUrl || '').trim(),
      limitDays: Number(form.limitDays || 0),
      name: String(form.name || '').trim(),
      popupKey: String(form.popupKey || '').trim(),
      priority: Number(form.priority || 0),
      scene: 'APP_ENTER',
      sysOrigin: query.sysOrigin,
      title: String(form.title || '').trim(),
      version: Number(form.version || 1),
    });
    message.success('保存成功');
    formOpen.value = false;
    await loadData();
  } finally {
    saving.value = false;
  }
}

function handleDelete(record: AppHomePopupItem) {
  Modal.confirm({
    title: `确认删除 ${record.popupKey || ''} 吗？`,
    async onOk() {
      if (!record.id) {
        return;
      }
      await deleteAppHomePopup(record.id);
      message.success('删除成功');
      await loadData(true);
    },
  });
}

watch(
  sysOriginOptions,
  (options) => {
    if (!query.sysOrigin) {
      query.sysOrigin = String(options[0]?.value || '');
    }
  },
  { immediate: true },
);

watch(
  () => query.sysOrigin,
  (value) => {
    if (value) {
      void loadData(true);
    }
  },
  { immediate: true },
);
</script>

<template>
  <Page title="首页弹窗管理">
    <Card>
      <InlineFilterToolbar class="toolbar">
        <InlineFilterField label="系统">
          <SysOriginSelect
            v-model:value="query.sysOrigin"
            :options="sysOriginOptions"
            style="width: 140px"
            @change="loadData(true)"
          />
        </InlineFilterField>
        <InlineFilterField label="弹窗 key">
          <Input
            v-model:value="query.popupKey"
            allow-clear
            placeholder="invite / game"
            style="width: 180px"
            @press-enter="loadData(true)"
          />
        </InlineFilterField>
        <Button :loading="loading" type="primary" @click="loadData(true)">
          搜索
        </Button>
        <Button type="primary" @click="handleCreate">新增</Button>
      </InlineFilterToolbar>

      <Table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1640 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'enabled'">
            <Tag :color="record.enabled ? 'success' : 'default'">
              {{ record.enabled ? '启用' : '关闭' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'limitDays'">
            {{ record.limitDays === 0 ? '每次' : `${record.limitDays} 天` }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button size="small" type="link" @click="handleEdit(record)">
                编辑
              </Button>
              <Button danger size="small" type="link" @click="handleDelete(record)">
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>

      <div class="pager">
        <Pagination
          :current="query.cursor"
          :page-size="query.limit"
          :total="total"
          show-size-changer
          @change="handlePageChange"
          @show-size-change="handlePageChange"
        />
      </div>
    </Card>

    <Modal
      :confirm-loading="saving"
      :open="formOpen"
      destroy-on-close
      ok-text="保存"
      :title="formTitle"
      width="720px"
      @cancel="formOpen = false"
      @ok="handleSubmit"
    >
      <div class="form-grid">
        <div class="form-item">
          <label>弹窗 key</label>
          <Input
            v-model:value="form.popupKey"
            :disabled="Boolean(form.id)"
            placeholder="invite"
          />
        </div>
        <div class="form-item">
          <label>limit时间(天)</label>
          <InputNumber
            v-model:value="form.limitDays"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </div>
        <div class="form-item">
          <label>描述</label>
          <Input v-model:value="form.description" placeholder="运营备注" />
        </div>
        <div class="form-item">
          <label>启用</label>
          <Switch v-model:checked="form.enabled" />
        </div>
        <div class="form-item">
          <label>标题</label>
          <Input v-model:value="form.title" placeholder="弹窗标题" />
        </div>
        <div class="form-item">
          <label>图片</label>
          <Input v-model:value="form.image" placeholder="https://..." />
        </div>
        <div class="form-item">
          <label>跳转类型</label>
          <Select
            v-model:value="form.jumpType"
            :options="jumpTypeOptions"
            option-label-prop="label"
          />
        </div>
        <div class="form-item">
          <label>跳转地址</label>
          <Input v-model:value="form.jumpUrl" placeholder="/game-center" />
        </div>
        <div class="form-item">
          <label>优先级</label>
          <InputNumber
            v-model:value="form.priority"
            :precision="0"
            style="width: 100%"
          />
        </div>
        <div class="form-item">
          <label>版本</label>
          <InputNumber
            v-model:value="form.version"
            :min="1"
            :precision="0"
            style="width: 100%"
          />
        </div>
      </div>
    </Modal>
  </Page>
</template>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-item label {
  color: hsl(var(--muted-foreground));
  font-size: 13px;
}
</style>

