<template>
  <div class="tenant-list-view">
    <a-page-header title="租户管理" sub-title="管理平台租户（学校）" />
    <a-card :bordered="false" style="margin-top: 16px">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="searchForm" style="margin-bottom: 16px">
        <a-form-item label="关键词">
          <a-input v-model:value="searchForm.keyword" placeholder="学校名称/账号/联系人" allow-clear style="width: 200px"
            @pressEnter="handleSearch" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" placeholder="全部状态" allow-clear style="width: 120px">
            <a-select-option value="ACTIVE">生效中</a-select-option>
            <a-select-option value="EXPIRED">已过期</a-select-option>
            <a-select-option value="SUSPENDED">已暂停</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="套餐">
          <a-select
            v-model:value="searchForm.collectionId"
            placeholder="全部套餐"
            allow-clear
            style="width: 200px"
          >
            <a-select-option
              v-for="pkg in packageList"
              :key="pkg.id"
              :value="pkg.id"
            >
              {{ pkg.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
        <a-form-item style="float: right">
          <a-button type="primary" @click="showAddModal">
            <template #icon>
              <PlusOutlined />
            </template>
            添加租户
          </a-button>
        </a-form-item>
      </a-form>

      <!-- 数据表格 -->
      <a-table :columns="columns" :data-source="tenants" :loading="loading" :pagination="pagination"
        @change="handleTableChange">
        <template #bodyCell="{ column, record }: any">
          <template v-if="column.key === 'name'">
            <a-button type="link" @click="handleViewDetail(record)">
              {{ record.name }}
            </a-button>
          </template>
          <template v-else-if="column.key === 'packageType'">
            <a-space wrap>
              <a-tag
                v-for="(pkg, index) in (record.packageNames || [])"
                :key="index"
                :color="getPackageTypeColor(pkg)"
              >
                {{ pkg }}
              </a-tag>
              <span v-if="!record.packageNames || record.packageNames.length === 0">未关联套餐</span>
            </a-space>
          </template>
          <template v-else-if="column.key === 'quota'">
            <div>
              <div>教师: {{ record.teacherCount }}/{{ record.teacherQuota }}</div>
              <div>学生: {{ record.studentCount }}/{{ record.studentQuota }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'validity'">
            <div>
              <div>{{ record.startDate }}</div>
              <div>至 {{ record.expireDate }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-badge :status="getStatusType(record.status)" :text="getStatusText(record.status)" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-dropdown>
                <a-button type="link" size="small">
                  操作
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleEdit(record)">编辑</a-menu-item>
                    <a-menu-item @click="handleViewDetail(record)">查看详情</a-menu-item>
                    <a-menu-divider />
                    <a-menu-item @click="handleQuota(record)">调整配额</a-menu-item>
                    <a-menu-item @click="handleResetPassword(record)">重置密码</a-menu-item>
                    <a-menu-item v-if="record.status === 'ACTIVE'" @click="handleUpdateStatus(record, 'SUSPENDED')">
                      暂停服务
                    </a-menu-item>
                    <a-menu-item v-if="record.status === 'SUSPENDED'" @click="handleUpdateStatus(record, 'ACTIVE')">
                      恢复服务
                    </a-menu-item>
                    <a-menu-item danger @click="handleDelete(record)">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑租户弹窗 -->
    <a-modal v-model:open="modalVisible" :title="isEdit ? '编辑租户' : '添加租户'" :confirm-loading="modalLoading" width="600px"
      @ok="handleModalOk" @cancel="handleModalCancel">
      <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="学校名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入学校名称" />
        </a-form-item>
        <a-form-item v-if="!isEdit" label="登录账号" name="loginAccount">
          <a-input v-model:value="formData.loginAccount" :placeholder="LOGIN_ACCOUNT_PLACEHOLDER" :disabled="isEdit" />
        </a-form-item>
        <a-form-item v-if="!isEdit" label="初始密码" name="password">
          <a-input-password v-model:value="formData.password" placeholder="留空则默认为 123456" />
        </a-form-item>
        <a-form-item label="联系人" name="contactPerson">
          <a-input v-model:value="formData.contactPerson" placeholder="请输入联系人姓名" />
        </a-form-item>
        <a-form-item label="联系电话" name="contactPhone">
          <a-input v-model:value="formData.contactPhone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="学习地址" name="address">
          <a-input v-model:value="formData.address" placeholder="请输入学习地址" />
        </a-form-item>
        <a-form-item label="套餐" name="collectionIds">
          <a-select
            v-model:value="formData.collectionIds"
            mode="multiple"
            placeholder="请选择套餐"
          >
            <a-select-option
              v-for="pkg in packageList"
              :key="pkg.id"
              :value="pkg.id"
            >
              {{ pkg.name }} ({{ formatPackagePrice(pkg.discountPrice || pkg.price) }}元{{ pkg.discountType ? ' ' + getDiscountTypeText(pkg.discountType) : '' }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="教师配额" name="teacherQuota">
          <a-input-number v-model:value="formData.teacherQuota" :min="1" :max="1000" style="width: 100%" />
        </a-form-item>
        <a-form-item label="学生配额" name="studentQuota">
          <a-input-number v-model:value="formData.studentQuota" :min="1" :max="10000" style="width: 100%" />
        </a-form-item>
        <a-form-item label="有效期" name="dateRange">
          <a-range-picker v-model:value="formData.dateRange" style="width: 100%" value-format="YYYY-MM-DD"
            :disabled-date="disabledPastDate" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 配额调整弹窗 -->
    <a-modal v-model:open="quotaModalVisible" title="调整配额" :confirm-loading="quotaModalLoading" @ok="handleQuotaOk">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="当前租户">
          <span>{{ currentTenant?.name }}</span>
        </a-form-item>
        <a-form-item label="教师配额">
          <a-input-number v-model:value="quotaForm.teacherQuota" :min="currentTenant?.teacherCount || 1" :max="1000"
            style="width: 100%" />
          <div style="color: #999; font-size: 12px">
            已使用：{{ currentTenant?.teacherCount || 0 }}
          </div>
        </a-form-item>
        <a-form-item label="学生配额">
          <a-input-number v-model:value="quotaForm.studentQuota" :min="currentTenant?.studentCount || 1" :max="10000"
            style="width: 100%" />
          <div style="color: #999; font-size: 12px">
            已使用：{{ currentTenant?.studentCount || 0 }}
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 强制移除确认弹窗 -->
    <a-modal
      v-model:open="forceRemoveModalVisible"
      title="确认移除套餐"
      :confirm-loading="modalLoading"
      ok-type="primary"
      ok-text="确认移除"
      cancel-text="取消"
      @ok="handleForceRemoveConfirm"
      @cancel="handleForceRemoveCancel"
    >
      <div style="color: #fa8c16; font-size: 14px; margin-bottom: 16px">
        <ExclamationCircleOutlined style="margin-right: 8px" />
        以下套餐下有排课计划，移除后将无法继续为该套餐下的课程排课：
      </div>
      <div style="max-height: 300px; overflow-y: auto">
        <div
          v-for="(item, index) in forceRemoveWarnings"
          :key="index"
          style="padding: 12px; border: 1px solid #d9d9d9; border-radius: 4px; margin-bottom: 8px"
        >
          <div style="font-weight: 500">{{ item.collectionName }}</div>
          <div style="font-size: 13px; color: #666; margin-top: 4px">
            排课数量：{{ item.scheduleCount }} 个
          </div>
        </div>
      </div>
      <div style="margin-top: 16px; color: #999; font-size: 13px">
        已存在的排课计划不受影响，但将无法新增该套餐下课程包的排课
      </div>
    </a-modal>

    <!-- 详情抽屉 -->
    <a-drawer v-model:open="drawerVisible" title="租户详情" width="600" :destroy-on-close="true">
      <template v-if="detailData">
        <a-descriptions :column="2" bordered size="small">
          <a-descriptions-item label="学校名称" :span="2">
            {{ detailData.name }}
          </a-descriptions-item>
          <a-descriptions-item label="登录账号">
            {{ detailData.username || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-badge :status="getStatusType(detailData.status)" :text="getStatusText(detailData.status)" />
          </a-descriptions-item>
          <a-descriptions-item label="联系人">
            {{ detailData.contactName || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ detailData.contactPhone || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="学习地址" :span="2">
            {{ detailData.address || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="套餐">
            <a-space wrap>
              <a-tag
                v-for="(pkg, index) in (detailData.packageNames || [])"
                :key="index"
                :color="getPackageTypeColor(pkg)"
              >
                {{ pkg }}
              </a-tag>
              <span v-if="!detailData.packageNames || detailData.packageNames.length === 0">未关联套餐</span>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="有效期">
            {{ detailData.startDate }} 至 {{ detailData.expireDate }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider>使用统计</a-divider>

        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic title="教师数" :value="detailData.teacherCount" :suffix="'/ ' + detailData.teacherQuota" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="学生数" :value="detailData.studentCount" :suffix="'/ ' + detailData.studentQuota" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="班级数" :value="detailData.classCount || 0" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="授课数" :value="detailData.lessonCount || 0" />
          </a-col>
        </a-row>
      </template>
      <a-skeleton v-else active />
    </a-drawer>

    <!-- 重置密码确认模态框 -->
    <a-modal v-model:open="resetPasswordVisible" @ok="confirmResetPassword" :confirm-loading="resetting" :width="400" okText="重置">
      <template #title>
        <span class="modal-title">
          <KeyOutlined class="modal-title-icon" />
          重置密码
        </span>
      </template>
      <div class="reset-password-content">
        <div class="reset-warning">
          <WarningOutlined class="warning-icon" />
          <p>确定要重置 <strong>{{ currentTenant?.name }}</strong> 的密码吗？</p>
        </div>
        <div v-if="newPassword" class="new-password-box">
          <p>新密码：</p>
          <div class="password-display">
            <a-typography-text copyable>{{ newPassword }}</a-typography-text>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  PlusOutlined,
  SearchOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
  KeyOutlined,
  WarningOutlined,
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import type { TableProps, FormInstance } from 'ant-design-vue';
import dayjs from 'dayjs';
import {
  getTenants,
  getTenant,
  createTenant,
  updateTenant,
  updateTenantQuota,
  updateTenantStatus,
  resetTenantPassword,
  deleteTenant,
  getPublishedPackages,
  type Tenant,
  type TenantDetail,
  type CreateTenantDto,
  type UpdateTenantDto,
  type CourseCollectionResponse,
} from '@/api/admin';
import { getDiscountTypeText } from '@/api/collections';
import {
  LOGIN_ACCOUNT_PATTERN,
  LOGIN_ACCOUNT_PATTERN_MESSAGE,
  LOGIN_ACCOUNT_PLACEHOLDER,
} from '@/constants/loginAccount';
import { trimFormModel } from '@/utils/trimFormModel';

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: undefined as string | undefined,
  collectionId: undefined as number | undefined,
});

// 数据列表
const loading = ref(false);
const tenants = ref<Tenant[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
});

// 表格列定义
const columns = [
  { title: '学校名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '登录账号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '联系人', dataIndex: 'contactName', key: 'contactName', width: 100 },
  { title: '联系电话', dataIndex: 'contactPhone', key: 'contactPhone', width: 120 },
  { title: '套餐', dataIndex: 'packageType', key: 'packageType', width: 80 },
  { title: '配额使用', key: 'quota', width: 120 },
  { title: '有效期', key: 'validity', width: 140 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
];

// 弹窗相关
const modalVisible = ref(false);
const modalLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const editingId = ref<number | null>(null);
// 强制移除确认相关
const forceRemoveModalVisible = ref(false);
const forceRemoveWarnings = ref<Array<{ collectionId: number; collectionName: string; scheduleCount: number }>>([]);
const pendingFormData = ref<any>(null);

const formData = reactive<CreateTenantDto & { dateRange?: [string, string]; collectionIds?: number[] }>({
  name: '',
  loginAccount: '',
  password: '',
  contactPerson: '',
  contactPhone: '',
  address: '',
  collectionIds: undefined,
  teacherQuota: 20,
  studentQuota: 200,
  startDate: '',
  expireDate: '',
  dateRange: undefined,
});

const formRules = {
  name: [{ required: true, message: '请输入学校名称' }],
  loginAccount: [
    { required: true, message: '请输入登录账号' },
    {
      pattern: LOGIN_ACCOUNT_PATTERN,
      message: LOGIN_ACCOUNT_PATTERN_MESSAGE,
    },
  ],
  contactPerson: [{ required: true, message: '请输入联系人' }],
  contactPhone: [
    { required: true, message: '请输入联系电话' },
    {
      validator: (_: unknown, value: string) => {
        if (!value) return Promise.resolve();
        return /^1[3-9]\d{9}$/.test(value) ? Promise.resolve() : Promise.reject(new Error('请输入正确的手机号'));
      },
      trigger: 'blur',
    },
  ],
  address: [{ required: true, message: '请输入学习地址' }],
  collectionIds: [{ required: true, message: '请选择套餐', type: 'array', trigger: 'change' }],
  teacherQuota: [
    { required: true, message: '请输入教师配额' },
    { type: 'number' as const, min: 1, max: 1000, message: '教师配额需为 1-1000 的整数' },
  ],
  studentQuota: [
    { required: true, message: '请输入学生配额' },
    { type: 'number' as const, min: 1, max: 10000, message: '学生配额需为 1-10000 的整数' },
  ],
  dateRange: [
    { required: true, message: '请选择有效期', type: 'array' as const, trigger: 'change' },
  ],
} as any;

// 配额弹窗
const quotaModalVisible = ref(false);
const quotaModalLoading = ref(false);
const currentTenant = ref<Tenant | null>(null);
const quotaForm = reactive<{
  teacherQuota: number;
  studentQuota: number;
}>({
  teacherQuota: 20,
  studentQuota: 200,
});

// 详情抽屉
const drawerVisible = ref(false);
const detailData = ref<TenantDetail | null>(null);

// 套餐列表
const packageList = ref<CourseCollectionResponse[]>([]);

// 重置密码相关
const resetPasswordVisible = ref(false);
const resetting = ref(false);
const newPassword = ref('');

// 禁用过去的日期（有效期不能选今天之前的日期）
const disabledPastDate = (current: dayjs.Dayjs) => {
  return current && current < dayjs().startOf('day');
};

// 格式化价格（分转为元）
const formatPackagePrice = (priceInCents?: number) => {
  if (priceInCents === undefined || priceInCents === null) return '0.00';
  return (priceInCents / 100).toFixed(2);
};


// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const res = await getTenants({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status,
      collectionId: searchForm.collectionId,
    });
    tenants.value = res.list;
    pagination.total = Number(res.total);
  } catch (error) {
    console.error('加载租户列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 加载套餐列表
const loadPackageList = async () => {
  try {
    const res = await getPublishedPackages();
    packageList.value = res;
  } catch (error) {
    console.error('加载套餐列表失败', error);
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchForm.keyword = '';
  searchForm.status = undefined;
  searchForm.collectionId = undefined;
  pagination.current = 1;
  loadData();
};

// 表格变化
const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current || 1;
  pagination.pageSize = pag.pageSize || 10;
  loadData();
};

// 显示添加弹窗
const showAddModal = () => {
  isEdit.value = false;
  editingId.value = null;
  Object.assign(formData, {
    name: '',
    loginAccount: '',
    password: '',
    contactPerson: '',
    contactPhone: '',
    address: '',
    collectionIds: undefined,
    teacherQuota: 20,
    studentQuota: 200,
    dateRange: [
      dayjs().format('YYYY-MM-DD'),
      dayjs().add(1, 'year').format('YYYY-MM-DD'),
    ] as [string, string],
  });
  modalVisible.value = true;
};

// 编辑
const handleEdit = (record: Tenant) => {
  isEdit.value = true;
  editingId.value = record.id;
  Object.assign(formData, {
    name: record.name,
    contactPerson: (record as any).contactName,
    contactPhone: record.contactPhone,
    address: record.address,
    collectionIds: record.packageNames && record.packageNames.length > 0
      ? record.packageNames.map((name: string) => {
          const pkg = packageList.value.find(p => p.name === name);
          return pkg?.id;
        }).filter((id: number | undefined) => id !== undefined)
      : undefined,
    teacherQuota: record.teacherQuota,
    studentQuota: record.studentQuota,
    dateRange: [record.startDate, record.expireDate] as [string, string],
  });
  modalVisible.value = true;
};

// 弹窗确认
const handleModalOk = async () => {
  try {
    // 提交前先移除表单字符串字段首尾空格，避免仅有空格导致的误校验
    trimFormModel(formData as any);
    await formRef.value?.validate();
  } catch {
    return;
  }

  modalLoading.value = true;
  const [startDate, expireDate] = formData.dateRange || [];
  try {
    const data = {
      ...formData,
      startDate,
      expireDate,
    };

    if (isEdit.value && editingId.value) {
      await updateTenant(editingId.value, data as UpdateTenantDto);
      message.success('更新成功');
    } else {
      const res = await createTenant(data as CreateTenantDto);
      message.success(`创建成功，初始密码: ${res.tempPassword || '123456'}`);
    }
    modalVisible.value = false;
    loadData();
  } catch (error: any) {
    // 处理错误码 3102 - 套餐下有排课计划
    if (error.response?.data?.code === 3102) {
      const warnings = error.response.data.data as Array<{
        collectionId: number;
        collectionName: string;
        scheduleCount: number;
      }>;
      // 保存当前表单数据
      pendingFormData.value = {
        ...formData,
        startDate,
        expireDate,
      };
      // 显示强制移除确认弹窗
      forceRemoveWarnings.value = warnings;
      forceRemoveModalVisible.value = true;
      modalLoading.value = false;
      return;
    }
    message.error(error.response?.data?.message || '操作失败');
  } finally {
    modalLoading.value = false;
  }
};

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false;
  formRef.value?.resetFields();
};

// 强制移除确认弹窗 - 确认
const handleForceRemoveConfirm = async () => {
  if (!pendingFormData.value || !editingId.value) {
    return;
  }

  modalLoading.value = true;
  try {
    // 传递 forceRemove: true 重新调用更新接口
    await updateTenant(editingId.value, { ...pendingFormData.value, forceRemove: true } as UpdateTenantDto);
    message.success('更新成功');
    modalVisible.value = false;
    forceRemoveModalVisible.value = false;
    pendingFormData.value = null;
    loadData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '操作失败');
  } finally {
    modalLoading.value = false;
  }
};

// 强制移除确认弹窗 - 取消
const handleForceRemoveCancel = () => {
  forceRemoveModalVisible.value = false;
  pendingFormData.value = null;
  forceRemoveWarnings.value = [];
};

// 查看详情
const handleViewDetail = async (record: Tenant) => {
  drawerVisible.value = true;
  try {
    detailData.value = await getTenant(record.id);
  } catch (error) {
    message.error('获取详情失败');
    drawerVisible.value = false;
  }
};

// 配额调整
const handleQuota = (record: Tenant) => {
  currentTenant.value = record;
  quotaForm.teacherQuota = record.teacherQuota;
  quotaForm.studentQuota = record.studentQuota;
  quotaModalVisible.value = true;
};

const handleQuotaOk = async () => {
  quotaModalLoading.value = true;
  try {
    await updateTenantQuota(currentTenant.value!.id, quotaForm);
    message.success('配额调整成功');
    quotaModalVisible.value = false;
    loadData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '操作失败');
  } finally {
    quotaModalLoading.value = false;
  }
};

// 重置密码
const handleResetPassword = (record: Tenant) => {
  currentTenant.value = record;
  newPassword.value = '';
  resetPasswordVisible.value = true;
};

const confirmResetPassword = async () => {
  if (!currentTenant.value) return;

  resetting.value = true;
  try {
    const result = await resetTenantPassword(currentTenant.value.id);
    newPassword.value = result.tempPassword;
    message.success('密码重置成功');
  } catch (error: any) {
    message.error(error.response?.data?.message || '重置密码失败');
  } finally {
    resetting.value = false;
  }
};
// 更新状态
const handleUpdateStatus = (record: Tenant, status: string) => {
  const statusText = status === 'ACTIVE' ? '恢复' : '暂停';
  Modal.confirm({
    title: `确认${statusText}服务`,
    content: `确定要${statusText} "${record.name}" 的服务吗？`,
    async onOk() {
      try {
        await updateTenantStatus(record.id, status);
        message.success(`${statusText}成功`);
        loadData();
      } catch (error: any) {
        message.error(error.response?.data?.message || '操作失败');
      }
    },
  });
};

// 删除
const handleDelete = (record: Tenant) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除 "${record.name}" 吗？此操作不可恢复！`,
    okType: 'danger',
    async onOk() {
      try {
        await deleteTenant(record.id);
        message.success('删除成功');
        loadData();
      } catch (error: any) {
        message.error(error.response?.data?.message || '删除失败');
      }
    },
  });
};

// 辅助函数
const getPackageTypeColor = (type: string) => {
  // 根据套餐名称生成颜色
  const colors: Record<string, string> = {
    '基础版': 'green',
    '标准版': 'blue',
    '高级版': 'purple',
    '定制版': 'orange',
    'BASIC': 'green',
    'STANDARD': 'blue',
    'ADVANCED': 'purple',
    'CUSTOM': 'orange',
  };
  return colors[type] || 'default';
};


const getStatusType = (status: string): 'success' | 'default' | 'warning' | 'error' | 'processing' => {
  const types: Record<string, 'success' | 'default' | 'warning' | 'error' | 'processing'> = {
    ACTIVE: 'success',
    EXPIRED: 'default',
    SUSPENDED: 'warning',
  };
  return types[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    ACTIVE: '生效中',
    EXPIRED: '已过期',
    SUSPENDED: '已暂停',
  };
  return texts[status] || status;
};

// 初始化
onMounted(() => {
  loadData();
  loadPackageList();
});
</script>

<style scoped>
.tenant-list-view {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
}

/* 重置密码弹窗样式 */
.reset-password-content {
  text-align: center;
}

.reset-warning {
  padding: 20px;
  background: #EEF2FF;
  border-radius: 12px;
  margin-bottom: 20px;
}

.warning-icon {
  font-size: 32px;
  color: #6366F1;
  display: block;
  margin-bottom: 8px;
}

.reset-warning p {
  margin: 0;
  color: #636E72;
}

.new-password-box p {
  margin-bottom: 8px;
  color: #636E72;
}

.password-display {
  padding: 16px;
  background: linear-gradient(135deg, #6366F1 0%, #4F46E5 100%);
  border-radius: 12px;
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.password-display :deep(.ant-typography),
.password-display :deep(.ant-typography-copy) {
  color: white !important;
}

.password-display :deep(.ant-typography-copy-icon) {
  color: rgba(255, 255, 255, 0.85);
}

/* Modal title styling */
.modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-title-icon {
  color: #6366F1;
}
</style>
