<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.packageType"
            placeholder="全部套餐"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="BASIC">基础版</a-select-option>
            <a-select-option value="STANDARD">标准版</a-select-option>
            <a-select-option value="ADVANCED">高级版</a-select-option>
            <a-select-option value="CUSTOM">定制版</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-tag :color="getPackageTypeColor(record.packageType)">
              {{ getPackageTypeLabel(record.packageType) }}
            </a-tag>
          </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-divider />
                    <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="字母开头，4-20位"
            :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="packageType">
          <a-select v-model:value="formData.packageType">
            <a-select-option value="BASIC">基础版</a-select-option>
            <a-select-option value="STANDARD">标准版</a-select-option>
            <a-select-option value="ADVANCED">高级版</a-select-option>
            <a-select-option value="CUSTOM">定制版</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="dateRange"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </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-select v-model:value="quotaForm.packageType">
            <a-select-option value="BASIC">基础版</a-select-option>
            <a-select-option value="STANDARD">标准版</a-select-option>
            <a-select-option value="ADVANCED">高级版</a-select-option>
            <a-select-option value="CUSTOM">定制版</a-select-option>
          </a-select>
        </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-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.loginAccount }}
          </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.contactPerson || '-' }}
          </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-tag :color="getPackageTypeColor(detailData.packageType)">
              {{ getPackageTypeLabel(detailData.packageType) }}
            </a-tag>
          </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._count?.classes || 0" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="授课数" :value="detailData._count?.lessons || 0" />
          </a-col>
        </a-row>

        <a-divider>最近教师</a-divider>
        <a-table
          v-if="detailData.teachers && detailData.teachers.length > 0"
          :columns="teacherColumns"
          :data-source="detailData.teachers"
          :pagination="false"
          size="small"
        />
        <a-empty v-else description="暂无教师数据" />

        <a-divider>最近学生</a-divider>
        <a-table
          v-if="detailData.students && detailData.students.length > 0"
          :columns="studentColumns"
          :data-source="detailData.students"
          :pagination="false"
          size="small"
        />
        <a-empty v-else description="暂无学生数据" />
      </template>
      <a-skeleton v-else active />
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  PlusOutlined,
  SearchOutlined,
  DownOutlined,
} 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,
  type Tenant,
  type TenantDetail,
  type CreateTenantDto,
  type UpdateTenantDto,
} from '@/api/admin';

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: undefined as string | undefined,
  packageType: undefined as string | 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: 'loginAccount', key: 'loginAccount', width: 120 },
  { title: '联系人', dataIndex: 'contactPerson', key: 'contactPerson', 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 teacherColumns = [
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '手机号', dataIndex: 'phone', key: 'phone' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

const studentColumns = [
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '性别', dataIndex: 'gender', key: 'gender' },
  { title: '阅读数', dataIndex: 'readingCount', key: 'readingCount' },
];

// 弹窗相关
const modalVisible = ref(false);
const modalLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const editingId = ref<number | null>(null);
const dateRange = ref<[string, string] | undefined>(undefined);

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

const formRules = {
  name: [{ required: true, message: '请输入学校名称' }],
  loginAccount: [
    { required: true, message: '请输入登录账号' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]{3,19}$/, message: '字母开头，4-20位字母数字或下划线' },
  ],
  contactPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }],
};

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

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

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

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

// 重置
const handleReset = () => {
  searchForm.keyword = '';
  searchForm.status = undefined;
  searchForm.packageType = 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: '',
    packageType: 'STANDARD',
    teacherQuota: 20,
    studentQuota: 200,
  });
  dateRange.value = [
      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.contactPerson,
    contactPhone: record.contactPhone,
    address: record.address,
    packageType: record.packageType,
    teacherQuota: record.teacherQuota,
    studentQuota: record.studentQuota,
  });
  dateRange.value = [record.startDate, record.expireDate] as [string, string];
  modalVisible.value = true;
};

// 弹窗确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate();
  } catch {
    return;
  }

  modalLoading.value = true;
  try {
    const [startDate, expireDate] = dateRange.value || [];
    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}`);
    }
    modalVisible.value = false;
    loadData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '操作失败');
  } finally {
    modalLoading.value = false;
  }
};

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

// 查看详情
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.packageType = record.packageType;
  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) => {
  Modal.confirm({
    title: '确认重置密码',
    content: `确定要重置 "${record.name}" 的密码吗？`,
    async onOk() {
      try {
        const res = await resetTenantPassword(record.id);
        Modal.success({
          title: '密码已重置',
          content: `新密码: ${res.tempPassword}`,
        });
      } catch (error: any) {
        message.error(error.response?.data?.message || '重置失败');
      }
    },
  });
};

// 更新状态
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> = {
    BASIC: 'green',
    STANDARD: 'blue',
    ADVANCED: 'purple',
    CUSTOM: 'orange',
  };
  return colors[type] || 'default';
};

const getPackageTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    BASIC: '基础版',
    STANDARD: '标准版',
    ADVANCED: '高级版',
    CUSTOM: '定制版',
  };
  return labels[type] || type;
};

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();
});
</script>

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