<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

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

import {
  deleteGameConfig,
  pageGameConfig,
  regionConfigTable,
  saveOrUpdateGameConfig,
} from '#/api/legacy/system';
import { deleteBaishunGame } from '#/api/legacy/baishun-game';
import {
  OSS_FILE_BUCKETS,
  getAccessImgUrl,
  simpleUploadFile,
} from '#/api/legacy/oss';
import { formatDate, getAllowedSysOrigins } from '#/views/system/shared';

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

import {
  GAME_CATEGORY_OPTIONS,
  GAME_CLIENT_ORIGIN_OPTIONS,
  GAME_MODE_OPTIONS,
  GAME_ORIGIN_OPTIONS,
} from './constants';

defineOptions({ name: 'OperateGameConfig' });

function createForm() {
  return {
    amounts: '',
    category: '',
    clientOrigin: '',
    cover: '',
    fullScreen: undefined as any,
    gameCode: '',
    gameId: '',
    gameMode: undefined as any,
    gameOrigin: 'BAISHUN',
    height: '',
    id: '',
    name: '',
    regionList: [] as Array<number | string>,
    self: false,
    selfGameCode: '',
    showcase: undefined as any,
    sort: 0,
    sysOrigin: '',
    width: '',
  };
}

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

const loading = ref(false);
const total = ref(0);
const list = ref<Array<Record<string, any>>>([]);
const regions = ref<Array<Record<string, any>>>([]);
const modalOpen = ref(false);
const saving = ref(false);
const uploadLoading = ref(false);
const batchDeleting = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);
const selectedRowKeys = ref<Array<number | string>>([]);
const selectedRows = ref<Array<Record<string, any>>>([]);

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

const form = reactive(createForm());
const gameOriginOptions = GAME_ORIGIN_OPTIONS.map((item) => ({
  label: item.name,
  value: item.value as any,
}));
const clientOriginOptions = GAME_CLIENT_ORIGIN_OPTIONS.map((item) => ({
  label: item.name,
  value: item.value as any,
}));
const categoryOptions = GAME_CATEGORY_OPTIONS.map((item) => ({
  label: item.name,
  value: item.value as any,
}));
const gameModeOptions = GAME_MODE_OPTIONS.map((item) => ({
  label: item.name,
  value: item.value as any,
}));
const booleanOptions = [
  { label: '是', value: true as any },
  { label: '否', value: false as any },
];
const showcaseOptions = [
  { label: '下架', value: false as any },
  { label: '上架', value: true as any },
];
const regionSelectOptions = computed(() =>
  regions.value.map((item) => ({
    label: String(item.regionName || item.id || '-'),
    value: item.id as any,
  })),
);

const columns = [
  { dataIndex: 'cover', key: 'cover', title: '封面', width: 90 },
  { dataIndex: 'name', key: 'name', title: '名称', width: 160 },
  { dataIndex: 'gameOrigin', key: 'gameOrigin', title: '三方类型', width: 120 },
  { dataIndex: 'gameId', key: 'gameId', title: '游戏ID', width: 160 },
  { dataIndex: 'gameCode', key: 'gameCode', title: '三方游戏ID', width: 120 },
  { dataIndex: 'category', key: 'category', title: '分类', width: 120 },
  { dataIndex: 'clientOrigin', key: 'clientOrigin', title: '客户端', width: 120 },
  { dataIndex: 'fullScreen', key: 'fullScreen', title: '全屏', width: 90 },
  { dataIndex: 'showcase', key: 'showcase', title: '状态', width: 100 },
  { dataIndex: 'sort', key: 'sort', title: '排序', width: 100 },
  { dataIndex: 'regionNameStr', key: 'regionNameStr', title: '区域', width: 180 },
  { dataIndex: 'gameMode', key: 'gameMode', title: '游戏模式', width: 120 },
  { dataIndex: 'amounts', key: 'amounts', title: '金额配置', width: 160 },
  { dataIndex: 'width', key: 'width', title: '宽', width: 90 },
  { dataIndex: 'height', key: 'height', title: '高', width: 90 },
  { dataIndex: 'createTime', key: 'createTime', title: '创建时间', width: 180 },
  { dataIndex: 'updateTime', key: 'updateTime', title: '更新时间', width: 180 },
  { dataIndex: 'actions', key: 'actions', title: '操作', width: 140, fixed: 'right' as const },
];

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: Array<number | string>, rows: Array<Record<string, any>>) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
  },
}));

const selectedCount = computed(() => selectedRowKeys.value.length);

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

watch(
  () => query.sysOrigin,
  async (value) => {
    if (!value) {
      return;
    }
    regions.value = await regionConfigTable({ sysOrigin: value });
  },
  { immediate: true },
);

watch(
  () => form.sysOrigin,
  async (value) => {
    if (!modalOpen.value || !value) {
      return;
    }
    regions.value = await regionConfigTable({ sysOrigin: value });
  },
);

function normalizeMultiValue(value: any) {
  if (Array.isArray(value)) {
    return value.filter((item) => item !== '' && item !== null && item !== undefined);
  }
  if (value === '' || value === null || value === undefined) {
    return [];
  }
  return String(value)
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
}

function clearSelection() {
  selectedRowKeys.value = [];
  selectedRows.value = [];
}

function isBaishunGame(record: Record<string, any>) {
  return String(record.gameOrigin || query.gameOrigin || '').toUpperCase() === 'BAISHUN';
}

function deleteGameRecord(record: Record<string, any>) {
  if (isBaishunGame(record)) {
    return deleteBaishunGame(record.id, record.sysOrigin || query.sysOrigin);
  }
  return deleteGameConfig(record.id, record.sysOrigin || query.sysOrigin);
}

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

function handleSearch() {
  void loadData(true);
}

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

function resetForm() {
  Object.assign(form, createForm(), {
    gameOrigin: query.gameOrigin || 'BAISHUN',
    sysOrigin: query.sysOrigin,
  });
}

function openEdit(record: Record<string, any>) {
  Object.assign(form, createForm(), {
    ...record,
    category: record.category || '',
    clientOrigin: record.clientOrigin || '',
    cover: record.cover || '',
    fullScreen: record.fullScreen,
    gameMode: record.gameMode,
    gameOrigin: record.gameOrigin || query.gameOrigin,
    id: String(record.id || ''),
    regionList: normalizeMultiValue(
      record.regionList || record.regions?.map((item: Record<string, any>) => item.id),
    ),
    self: record.self === true || Boolean(record.selfGameCode),
    selfGameCode: record.selfGameCode || '',
    showcase: record.showcase,
    sort: Number(record.sort || 0),
    sysOrigin: record.sysOrigin || query.sysOrigin,
  });
  modalOpen.value = true;
}

async function submitForm() {
  if (!form.cover) {
    message.warning('请上传封面');
    return;
  }
  if (!form.sysOrigin || !form.gameOrigin || !form.clientOrigin) {
    message.warning('请补全系统、游戏源和客户端');
    return;
  }
  if (!form.gameId || !form.category || !form.name || !form.gameCode) {
    message.warning('请补全游戏基础信息');
    return;
  }
  if (form.showcase === undefined || form.showcase === null) {
    message.warning('请选择状态');
    return;
  }
  saving.value = true;
  try {
    await saveOrUpdateGameConfig({ ...form });
    message.success('保存成功');
    modalOpen.value = false;
    resetForm();
    await loadData(true);
  } finally {
    saving.value = false;
  }
}

function handleDelete(record: Record<string, any>) {
  Modal.confirm({
    title: '确认删除吗？',
    async onOk() {
      await deleteGameRecord(record);
      message.success('删除成功');
      await loadData(true);
    },
  });
}

function handleBatchDelete() {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要删除的游戏');
    return;
  }
  const rows = [...selectedRows.value];
  Modal.confirm({
    title: `确认删除已选 ${rows.length} 个游戏吗？`,
    async onOk() {
      batchDeleting.value = true;
      try {
        const results = await Promise.allSettled(
          rows.map((row) => deleteGameRecord(row)),
        );
        const failed = results.filter((item) => item.status === 'rejected').length;
        const success = results.length - failed;
        if (failed > 0) {
          message.warning(`批量删除完成：成功 ${success} 个，失败 ${failed} 个`);
        } else {
          message.success(`已删除 ${success} 个游戏`);
        }
        await loadData(true);
      } finally {
        batchDeleting.value = false;
      }
    },
  });
}

function openUpload() {
  fileInput.value?.click();
}

async function handleUpload(event: Event) {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) {
    return;
  }
  uploadLoading.value = true;
  try {
    const result = await simpleUploadFile(file, OSS_FILE_BUCKETS.other);
    form.cover = getAccessImgUrl(result.name);
    message.success('上传成功');
  } finally {
    uploadLoading.value = false;
    target.value = '';
  }
}

void loadData(true);
</script>

<template>
  <Page title="游戏列表">
    <Card>
      <div class="toolbar">
        <Select
          option-label-prop="label"
          v-model:value="query.gameOrigin"
          style="width: 140px"
          @change="handleSearch"
          :options="GAME_ORIGIN_OPTIONS.map((item) => ({ label: `${item.name}`, value: item.value as any }))"
        />
        <Button :loading="loading" type="primary" @click="handleSearch">
          搜索
        </Button>
        <Button
          danger
          :disabled="selectedCount === 0"
          :loading="batchDeleting"
          @click="handleBatchDelete"
        >
          批量删除
        </Button>
        <span v-if="selectedCount > 0" class="selected-tip">
          已选 {{ selectedCount }} 项
        </span>
      </div>

      <Table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="false"
        :row-selection="rowSelection"
        row-key="id"
        :scroll="{ x: 2160 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <Image :src="record.cover" class="cover" />
          </template>
          <template v-else-if="column.key === 'gameOrigin'">
            {{
              GAME_ORIGIN_OPTIONS.find((item) => item.value === record.gameOrigin)?.name ||
              record.gameOrigin ||
              '-'
            }}
          </template>
          <template v-else-if="column.key === 'fullScreen'">
            {{ record.fullScreen ? '是' : '否' }}
          </template>
          <template v-else-if="column.key === 'showcase'">
            {{ record.showcase ? '上架' : '下架' }}
          </template>
          <template v-else-if="column.key === 'regionNameStr'">
            {{ record.regionNameStr || '-' }}
          </template>
          <template v-else-if="column.key === 'gameMode'">
            {{ record.gameMode || '-' }}
          </template>
          <template v-else-if="column.key === 'amounts'">
            {{ record.amounts || '-' }}
          </template>
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
          <template v-else-if="column.key === 'updateTime'">
            {{ formatDate(record.updateTime) }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button size="small" type="link" @click="openEdit(record)">
                编辑
              </Button>
              <Button danger size="small" type="link" @click="handleDelete(record)">
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>

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

    <Modal
      :confirm-loading="saving"
      :open="modalOpen"
      destroy-on-close
      title="编辑游戏"
      width="720px"
      @cancel="modalOpen = false"
      @ok="submitForm"
    >
      <Form layout="vertical">
        <FormItem label="封面">
          <div class="upload-row">
            <Button :loading="uploadLoading" @click="openUpload">
              上传封面
            </Button>
            <Image v-if="form.cover" :src="form.cover" class="cover" />
          </div>
          <input
            ref="fileInput"
            accept="image/*"
            class="hidden-input"
            type="file"
            @change="handleUpload"
          >
        </FormItem>
        <FormItem label="系统">
          <SysOriginSelect
            v-model:value="form.sysOrigin"
            :options="sysOriginOptions"
          />
        </FormItem>
        <FormItem label="游戏源">
          <Select
            v-model:value="form.gameOrigin"
            :options="gameOriginOptions"
            option-label-prop="label"
            placeholder="请选择游戏源"
          />
        </FormItem>
        <FormItem label="客户端">
          <Select
            v-model:value="form.clientOrigin"
            :options="clientOriginOptions"
            option-label-prop="label"
            placeholder="请选择客户端"
          />
        </FormItem>
        <FormItem label="是否自研">
          <Select
            v-model:value="form.self"
            :options="booleanOptions"
            allow-clear
            option-label-prop="label"
            placeholder="请选择是否自研"
          />
        </FormItem>
        <FormItem v-if="form.self" label="自研游戏Code">
          <Input v-model:value="form.selfGameCode" placeholder="请输入自研游戏Code" />
        </FormItem>
        <FormItem label="游戏ID">
          <Input v-model:value="form.gameId" placeholder="请输入游戏ID" />
        </FormItem>
        <FormItem label="游戏分类">
          <Select
            v-model:value="form.category"
            :options="categoryOptions"
            option-label-prop="label"
            placeholder="请选择游戏分类"
          />
        </FormItem>
        <FormItem label="名称">
          <Input v-model:value="form.name" placeholder="请输入名称" />
        </FormItem>
        <FormItem label="编号">
          <Input v-model:value="form.gameCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="金额">
          <Input v-model:value="form.amounts" placeholder="金币必须是整数多个逗号隔开" />
        </FormItem>
        <FormItem label="是否全屏">
          <Select
            v-model:value="form.fullScreen"
            :options="booleanOptions"
            allow-clear
            option-label-prop="label"
            placeholder="请选择是否全屏"
          />
        </FormItem>
        <FormItem label="游戏模式">
          <Select
            v-model:value="form.gameMode"
            :options="gameModeOptions"
            allow-clear
            option-label-prop="label"
            placeholder="请选择游戏模式"
          />
        </FormItem>
        <FormItem label="宽">
          <Input v-model:value="form.width" placeholder="宽度" />
        </FormItem>
        <FormItem label="高">
          <Input v-model:value="form.height" placeholder="高度" />
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="form.showcase"
            :options="showcaseOptions"
            allow-clear
            option-label-prop="label"
            placeholder="请选择状态"
          />
        </FormItem>
        <FormItem label="排序">
          <InputNumber v-model:value="form.sort" :max="99999" :min="0" style="width: 100%" />
        </FormItem>
        <FormItem label="区域">
          <Select
            v-model:value="form.regionList"
            :options="regionSelectOptions"
            mode="multiple"
            option-label-prop="label"
            placeholder="请选择区域"
          />
        </FormItem>
      </Form>
    </Modal>
  </Page>
</template>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.cover {
  border-radius: 8px;
  height: 50px;
  object-fit: cover;
  width: 50px;
}

.upload-row {
  align-items: center;
  display: flex;
  gap: 12px;
}

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

.selected-tip {
  color: rgb(100 116 139);
  line-height: 32px;
}
</style>
