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

defineOptions({ name: 'SchoolDetail' });

const route = useRoute();
const router = useRouter();
const formRef = ref();
const accountFormRef = ref();
const loading = ref(false);
const accountLoading = ref(false);
const activeTab = ref('basic');
const formData = ref<Partial<SchoolApi.SaveParams>>({
  name: '',
  address: '',
  contact: '',
  phone: '',
  description: '',
});

// 账号管理相关
const accountList = ref<SchoolApi.AccountInfo[]>([]);
const accountFormData = ref<Partial<SchoolApi.SaveAccountParams>>({
  username: '',
  password: '',
  status: 1,
});
const accountModalVisible = ref(false);
const isAccountEdit = ref(false);

const isEdit = computed(() => !!route.params.id);
const schoolId = computed(() => isEdit.value ? Number(route.params.id) : 0);

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    const data = { ...formData.value };
    if (isEdit.value) {
      data.id = Number(route.params.id);
    }
    await saveSchoolApi(data);
    message.success(isEdit.value ? '更新成功' : '创建成功');
    router.back();
  } catch (error: any) {
    console.error('保存失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '保存失败');
  } finally {
    loading.value = false;
  }
};

const fetchDetail = async () => {
  if (!isEdit.value) return;
  loading.value = true;
  try {
    const res = await getSchoolDetailApi({ id: Number(route.params.id) });
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 中
      const data = res.data;
      if (data) {
        formData.value = {
          name: data.name || '',
          address: data.address || '',
          contact: data.contact || '',
          phone: data.phone || '',
          description: data.description || '',
        };
      } else {
        message.error('获取学校详情失败：数据为空');
      }
    } else {
      message.error(res?.message || res?.msg || '获取学校详情失败');
    }
  } catch (error: any) {
    console.error('获取详情失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '获取学校详情失败');
  } finally {
    loading.value = false;
  }
};

// 账号管理相关方法
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 fetchAccountList = async () => {
  if (!isEdit.value) return;
  accountLoading.value = true;
  try {
    const res = await getSchoolAccountListApi({ school_id: schoolId.value });
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 数组中
      const data = Array.isArray(res.data) ? res.data : [];
      accountList.value = data;
    } else {
      accountList.value = [];
    }
  } catch (error) {
    console.error('获取账号列表失败:', error);
    accountList.value = [];
  } finally {
    accountLoading.value = false;
  }
};

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

const handleEditAccount = (record: SchoolApi.AccountInfo) => {
  isAccountEdit.value = true;
  accountFormData.value = {
    id: record.id,
    username: record.username || '',
    password: '', // 编辑时不显示密码
    status: record.status !== undefined ? record.status : 1,
  };
  accountModalVisible.value = true;
};

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

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

onMounted(() => {
  if (isEdit.value) {
    fetchDetail();
    fetchAccountList();
  }
});
</script>

<template>
  <Page :title="isEdit ? '编辑学校' : '新增学校'">
    <Card>
      <Tabs v-model:activeKey="activeTab">
        <Tabs.TabPane key="basic" tab="基本信息">
          <Form
            ref="formRef"
            :model="formData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <Form.Item
              label="学校名称"
              name="name"
              :rules="[{ required: true, message: '请输入学校名称' }]"
            >
              <Input v-model:value="formData.name" placeholder="请输入学校名称" />
            </Form.Item>
            <Form.Item label="地址" name="address">
              <Input v-model:value="formData.address" placeholder="请输入地址" />
            </Form.Item>
            <Form.Item label="联系人" name="contact">
              <Input v-model:value="formData.contact" placeholder="请输入联系人" />
            </Form.Item>
            <Form.Item label="联系电话" name="phone">
              <Input v-model:value="formData.phone" placeholder="请输入联系电话" />
            </Form.Item>
            <Form.Item label="描述" name="description">
              <Input.TextArea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
            </Form.Item>
            <Form.Item :wrapper-col="{ offset: 4, span: 20 }">
              <Button type="primary" :loading="loading" @click="handleSubmit">保存</Button>
              <Button class="ml-2" @click="router.back()">取消</Button>
            </Form.Item>
          </Form>
        </Tabs.TabPane>
        <Tabs.TabPane key="account" tab="账号管理" :disabled="!isEdit">
          <div class="mb-4">
            <Button type="primary" @click="handleAddAccount">添加账号</Button>
          </div>
          <Table
            :columns="accountColumns"
            :data-source="accountList"
            :loading="accountLoading"
            row-key="id"
          >
            <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>
        </Tabs.TabPane>
      </Tabs>
    </Card>

    <!-- 账号编辑弹窗 -->
    <Modal
      v-model:open="accountModalVisible"
      :title="isAccountEdit ? '编辑账号' : '新增账号'"
      :confirm-loading="accountLoading"
      @ok="handleAccountSubmit"
      @cancel="accountModalVisible = false"
    >
      <Form
        ref="accountFormRef"
        :model="accountFormData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <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>

