<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Button, Card, Table, Space, message, Modal, Input, Form, Radio } from 'ant-design-vue';
import {
  deleteSchoolAccountApi,
  deleteSchoolApi,
  getSchoolAccountListApi,
  getSchoolListApi,
  saveSchoolAccountApi,
  type SchoolApi
} from '#/api';

defineOptions({ name: 'SchoolList' });

const router = useRouter();
const loading = ref(false);
const tableData = ref<SchoolApi.SchoolInfo[]>([]);
const total = ref(0);
const pagination = reactive({
  current: 1,
  pageSize: 10,
});

const searchForm = reactive({
  name: '',
});

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '学校名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    width: 250,
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: SchoolApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getSchoolListApi(params);
    // 根据实际返回格式，code 为 0 表示成功，返回格式为 {code, msg, count, data}
    if (res && (res.code === 0 || res.code === 200)) {
      const data = Array.isArray(res.data) ? res.data : [];
      tableData.value = data;
      total.value = res.count || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取学校列表失败:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const handleEdit = (record: SchoolApi.SchoolInfo) => {
  router.push({
    name: 'SchoolDetail',
    params: { id: record.id }
  });
};

const handleDelete = (record: SchoolApi.SchoolInfo) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除学校"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteSchoolApi({ id: record.id! });
        message.success('删除成功');
        fetchData();
      } catch (error) {
        console.error('删除失败:', error);
      }
    },
  });
};

// 账号管理
const accountLoading = ref(false);
const accountModalVisible = ref(false);
const accountFormRef = ref();
const accountList = ref<SchoolApi.AccountInfo[]>([]);
const accountColumns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
];
const currentSchool = ref<SchoolApi.SchoolInfo | null>(null);
const isAccountEdit = ref(false);
const accountFormData = ref<Partial<SchoolApi.SaveAccountParams>>({
  username: '',
  password: '',
  status: 1,
});

const fetchAccountList = async (schoolId: number) => {
  accountLoading.value = true;
  try {
    const res = await getSchoolAccountListApi({ school_id: schoolId });
    if (res && (res.code === 0 || res.code === 200)) {
      accountList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      accountList.value = [];
    }
  } catch (error) {
    console.error('获取账号列表失败:', error);
    accountList.value = [];
  } finally {
    accountLoading.value = false;
  }
};

const openAccountModal = (record: SchoolApi.SchoolInfo) => {
  currentSchool.value = record;
  isAccountEdit.value = false;
  accountFormData.value = {
    username: '',
    password: '',
    status: 1,
  };
  fetchAccountList(record.id!);
  accountModalVisible.value = true;
};

const handleAddAccount = () => {
  isAccountEdit.value = false;
  accountFormData.value = {
    username: '',
    password: '',
    status: 1,
  };
};

const handleEditAccount = (record: SchoolApi.AccountInfo) => {
  isAccountEdit.value = true;
  accountFormData.value = {
    id: record.id,
    username: record.username || '',
    password: '',
    status: record.status !== undefined ? record.status : 1,
  };
};

const handleDeleteAccount = (record: SchoolApi.AccountInfo) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除账号"${record.username}"吗？`,
    onOk: async () => {
      if (!record.id) return;
      try {
        await deleteSchoolAccountApi({ id: record.id });
        message.success('删除成功');
        if (currentSchool.value?.id) {
          fetchAccountList(currentSchool.value.id);
        }
      } catch (error) {
        console.error('删除失败:', error);
      }
    },
  });
};

const handleAccountSubmit = async () => {
  if (!currentSchool.value?.id) return;
  try {
    await accountFormRef.value.validate();
    accountLoading.value = true;
    const data = {
      ...accountFormData.value,
      school_id: currentSchool.value.id,
    };
    await saveSchoolAccountApi(data);
    message.success(isAccountEdit.value ? '更新成功' : '创建成功');
    fetchAccountList(currentSchool.value.id);
    accountModalVisible.value = false;
  } catch (error: any) {
    console.error('保存账号失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '保存账号失败');
  } finally {
    accountLoading.value = false;
  }
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <Page title="学校列表">
    <Card>
      <div class="mb-4">
        <Space>
          <Input
            v-model:value="searchForm.name"
            placeholder="学校名称"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button type="primary" @click="router.push({ name: 'SchoolDetail' })">新增</Button>
        </Space>
      </div>
      <Table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: total,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'address'">
            <span :title="record.address || '-'">
              {{ record.address || '-' }}
            </span>
          </template>
          <template v-else-if="column.key === 'contact'">
            {{ record.contact || '-' }}
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.phone || '-' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="openAccountModal(record)">账号管理</Button>
              <Button type="link" size="small" @click="handleEdit(record)">编辑</Button>
              <Button type="link" danger size="small" @click="handleDelete(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <Modal
      v-model:open="accountModalVisible"
      :title="`${currentSchool?.name || '账号管理'}`"
      :confirm-loading="accountLoading"
      width="720px"
      @ok="handleAccountSubmit"
      @cancel="accountModalVisible = false"
    >
      <div class="mb-3">
        <Button type="primary" size="small" @click="handleAddAccount">新增账号</Button>
      </div>
      <Table
        :columns="accountColumns"
        :data-source="accountList"
        :loading="accountLoading"
        size="small"
        row-key="id"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            {{ record.status === 1 ? '启用' : '禁用' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleEditAccount(record)">编辑</Button>
              <Button type="link" danger size="small" @click="handleDeleteAccount(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>

      <Form
        ref="accountFormRef"
        :model="accountFormData"
        class="mt-4"
        layout="vertical"
      >
        <Form.Item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <Input
            v-model:value="accountFormData.username"
            placeholder="请输入用户名"
            :disabled="isAccountEdit"
          />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          :rules="[{ required: !isAccountEdit, message: '请输入密码' }]"
        >
          <Input.Password v-model:value="accountFormData.password" placeholder="请输入密码" />
          <div v-if="isAccountEdit" style="margin-top: 4px; font-size: 12px; color: #999;">
            留空则不修改密码
          </div>
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Radio.Group v-model:value="accountFormData.status">
            <Radio :value="1">启用</Radio>
            <Radio :value="0">禁用</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>

