<script lang="ts" setup>
import type { AgentApi } from '#/api/agent';

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

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

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

import { getLevelName } from '#/utils/agent';
import { upgradeAgent } from '#/api/agent';

interface ModalData {
  row: AgentApi.AgentListItem;
  onSuccess?: () => void;
}

const [Modal, modalApi] = useVbenModal({
  title: '平台升级代理等级',
  destroyOnClose: true,
  onConfirm: () => handleSubmit(),
});

const modalData = computed(() => modalApi.getData<ModalData>());

// 当前代理信息
const currentLevel = computed(() => modalData.value?.row?.level ?? 1);
const levelName = computed(() => getLevelName(currentLevel.value));
const agentId = computed(() => String(modalData.value?.row?.id ?? ''));
const mobile = computed(() => modalData.value?.row?.mobile ?? '');

// 可选目标等级：只能升级不能降级
const targetLevelOptions = computed(() => {
  const options: { label: string; value: number }[] = [];
  if (currentLevel.value < 2) {
    options.push({ label: '黄金代理', value: 2 });
  }
  if (currentLevel.value < 3) {
    options.push({ label: '钻石代理', value: 3 });
  }
  return options;
});

const selectedToLevel = ref<number>(targetLevelOptions.value[0]?.value ?? 0);
const canUpgrade = computed(() => targetLevelOptions.value.length > 0);

// 当可选目标等级变化时（如打开弹窗、切换代理），重置选中为第一项
watch(targetLevelOptions, (opts) => {
  if (opts.length) {
    selectedToLevel.value = opts[0].value;
  }
});

async function handleSubmit() {
  if (!agentId.value || !selectedToLevel.value) {
    message.warning('请选择目标等级');
    return;
  }
  if (selectedToLevel.value <= currentLevel.value) {
    message.warning('目标等级必须高于当前等级');
    return;
  }
  modalApi.lock(true);
  try {
    await upgradeAgent({
      agent_id: agentId.value,
      to_level: selectedToLevel.value,
    });
    message.success('升级成功');
    modalData.value?.onSuccess?.();
    modalApi.close();
  } catch (e: any) {
    message.error(e?.message ?? '升级失败');
  } finally {
    modalApi.lock(false);
  }
}
</script>

<template>
  <Modal class="w-[420px]" :ok-button-props="{ disabled: !canUpgrade }">
    <div class="platform-upgrade-modal py-2">
      <div v-if="!canUpgrade" class="text-warning mb-4">
        当前已是最高等级（钻石代理），无需升级。
      </div>
      <template v-else>
        <div class="mb-4">
          <span class="text-gray-500">代理：</span>
          <span>{{ mobile }}</span>
          <span class="ml-2 text-gray-500">当前等级：</span>
          <span>{{ levelName }}</span>
        </div>
        <div>
          <span class="text-gray-500">升级为：</span>
          <Select
            v-model:value="selectedToLevel"
            class="w-[160px] ml-2"
            placeholder="请选择目标等级"
            :options="targetLevelOptions"
          />
        </div>
        <div class="mt-4 text-gray-400 text-sm">
          平台免费升级，将按代理系统规则处理（脱离/重连上级、团队首领等）。
        </div>
      </template>
    </div>
  </Modal>
</template>

<style lang="less" scoped>
.platform-upgrade-modal {
  min-height: 80px;
}
</style>
