<template>
  <div class="user-management">
    <a-card title="用户管理" :bordered="false">
      <!-- 操作按钮 -->
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showAddModal = true">
            <template #icon><UserAddOutlined /></template>
            添加用户
          </a-button>
          <a-button @click="loadUsers">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
        </a-space>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form layout="inline" :model="searchForm" @finish="handleSearch">
          <a-form-item label="用户名">
            <a-input v-model:value="searchForm.username" placeholder="请输入用户名" />
          </a-form-item>
          <a-form-item label="用户类型">
            <a-select v-model:value="searchForm.user_type" placeholder="请选择用户类型" style="width: 120px;">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
              <a-select-option value="farmer">养殖户</a-select-option>
              <a-select-option value="banker">银行职员</a-select-option>
              <a-select-option value="insurer">保险员</a-select-option>
              <a-select-option value="government">政府人员</a-select-option>
              <a-select-option value="trader">交易员</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px;" @click="resetSearch">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="users"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'user_type'">
            <a-tag :color="getUserTypeColor(record.user_type)">
              {{ getUserTypeText(record.user_type) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="editUser(record)">编辑</a-button>
              <a-button type="link" size="small" @click="viewUser(record)">查看</a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="deleteUser(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑用户模态框 -->
    <a-modal
      v-model:open="showAddModal"
      :title="editingUser ? '编辑用户' : '添加用户'"
      @ok="handleSaveUser"
      @cancel="handleCancel"
      :confirm-loading="saving"
    >
      <a-form :model="userForm" :rules="rules" ref="userFormRef" layout="vertical">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="userForm.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="真实姓名" name="real_name">
          <a-input v-model:value="userForm.real_name" placeholder="请输入真实姓名" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="userForm.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="userForm.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="用户类型" name="user_type">
          <a-select v-model:value="userForm.user_type" placeholder="请选择用户类型">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="farmer">养殖户</a-select-option>
            <a-select-option value="banker">银行职员</a-select-option>
            <a-select-option value="insurer">保险员</a-select-option>
            <a-select-option value="government">政府人员</a-select-option>
            <a-select-option value="trader">交易员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="!editingUser" label="密码" name="password">
          <a-input-password v-model:value="userForm.password" placeholder="请输入密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UserAddOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { userAPI } from '../services/api.js';

// 响应式数据
const users = ref([]);
const loading = ref(false);
const saving = ref(false);
const showAddModal = ref(false);
const editingUser = ref(null);
const userFormRef = ref();

// 搜索表单
const searchForm = reactive({
  username: '',
  user_type: '',
});

// 用户表单
const userForm = reactive({
  username: '',
  real_name: '',
  email: '',
  phone: '',
  user_type: '',
  password: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '真实姓名', dataIndex: 'real_name', key: 'real_name' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '手机号', dataIndex: 'phone', key: 'phone' },
  { title: '用户类型', dataIndex: 'user_type', key: 'user_type' },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 160 },
  { title: '操作', key: 'action', width: 200 },
];

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  real_name: [{ required: true, message: '请输入真实姓名' }],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '邮箱格式不正确' },
  ],
  phone: [{ required: true, message: '请输入手机号' }],
  user_type: [{ required: true, message: '请选择用户类型' }],
  password: [{ required: true, message: '请输入密码', min: 6 }],
};

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    
    const response = await userAPI.getUsers(params);
    
    if (response.success) {
      users.value = response.data.users || [];
      pagination.total = response.data.pagination?.total || 0;
    } else {
      message.error(response.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    message.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadUsers();
};

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

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    user_type: '',
  });
  pagination.current = 1;
  loadUsers();
};

// 获取用户类型颜色
const getUserTypeColor = (type) => {
  const colors = {
    admin: 'red',
    farmer: 'green',
    banker: 'blue',
    insurer: 'orange',
    government: 'purple',
    trader: 'cyan',
  };
  return colors[type] || 'default';
};

// 获取用户类型文本
const getUserTypeText = (type) => {
  const texts = {
    admin: '管理员',
    farmer: '养殖户',
    banker: '银行职员',
    insurer: '保险员',
    government: '政府人员',
    trader: '交易员',
  };
  return texts[type] || type;
};

// 编辑用户
const editUser = (record) => {
  editingUser.value = record;
  Object.assign(userForm, {
    username: record.username,
    real_name: record.real_name,
    email: record.email,
    phone: record.phone,
    user_type: record.user_type,
    password: '',
  });
  showAddModal.value = true;
};

// 查看用户
const viewUser = (record) => {
  message.info(`查看用户: ${record.real_name}`);
};

// 删除用户
const deleteUser = async (id) => {
  try {
    const response = await userAPI.deleteUser(id);
    if (response.success) {
      message.success('删除成功');
      loadUsers();
    } else {
      message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除用户失败:', error);
    message.error('删除失败');
  }
};

// 保存用户
const handleSaveUser = async () => {
  try {
    await userFormRef.value.validate();
    saving.value = true;

    let response;
    if (editingUser.value) {
      response = await userAPI.updateUser(editingUser.value.id, userForm);
    } else {
      response = await userAPI.createUser(userForm);
    }

    if (response.success) {
      message.success(editingUser.value ? '更新成功' : '创建成功');
      showAddModal.value = false;
      loadUsers();
    } else {
      message.error(response.message || '保存失败');
    }
  } catch (error) {
    console.error('保存用户失败:', error);
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  showAddModal.value = false;
  editingUser.value = null;
  userFormRef.value?.resetFields();
};

// 组件挂载时加载数据
onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management {
  padding: 24px;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}
</style>