<template>
  <div class="users-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统用户账号和权限</p>
    </div>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <a-button type="primary" @click="showAddUserModal">
        <plus-outlined /> 添加用户
      </a-button>
      <a-input-search
        v-model:value="searchQuery"
        placeholder="搜索用户..."
        style="width: 250px; margin-left: 16px;"
        @search="handleSearch"
      />
    </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 === 'status'">
          <a-tag :color="record.status === 'active' ? 'green' : 'red'">
            {{ record.status === 'active' ? '活跃' : '禁用' }}
          </a-tag>
        </template>
        
        <!-- 角色列 -->
        <template v-if="column.key === 'role'">
          <a-tag :color="getRoleColor(record.role)">
            {{ getRoleName(record.role) }}
          </a-tag>
        </template>
        
        <!-- 操作列 -->
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="editUser(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除此用户吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteUser(record.id)"
            >
              <a class="danger-link">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 添加/编辑用户对话框 -->
    <a-modal
      v-model:visible="userModalVisible"
      :title="isEditing ? '编辑用户' : '添加用户'"
      @ok="handleUserFormSubmit"
      :confirmLoading="submitting"
    >
      <a-form
        :model="userForm"
        :rules="rules"
        ref="userFormRef"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="userForm.username" />
        </a-form-item>
        
        <a-form-item 
          label="密码" 
          name="password"
          :rules="isEditing ? [] : [{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="userForm.password" :placeholder="isEditing ? '不修改请留空' : '请输入密码'" />
        </a-form-item>
        
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="userForm.name" />
        </a-form-item>
        
        <a-form-item label="角色" name="role">
          <a-select v-model:value="userForm.role">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="manager">经理</a-select-option>
            <a-select-option value="teller">柜员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-select v-model:value="userForm.status">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="disabled">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { api } from '@/utils/api';

export default defineComponent({
  name: 'UsersPage',
  components: {
    PlusOutlined
  },
  setup() {
    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        sorter: true,
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
        sorter: true,
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        sorter: true,
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
        filters: [
          { text: '管理员', value: 'admin' },
          { text: '经理', value: 'manager' },
          { text: '柜员', value: 'teller' },
          { text: '普通用户', value: 'user' },
        ],
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        filters: [
          { text: '活跃', value: 'active' },
          { text: '禁用', value: 'disabled' },
        ],
      },
      {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        sorter: true,
      },
      {
        title: '操作',
        key: 'action',
      },
    ];

    // 状态变量
    const users = ref([]);
    const loading = ref(false);
    const searchQuery = ref('');
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`,
    });

    // 用户表单相关
    const userFormRef = ref(null);
    const userModalVisible = ref(false);
    const isEditing = ref(false);
    const submitting = ref(false);
    const userForm = reactive({
      id: null,
      username: '',
      password: '',
      name: '',
      role: 'user',
      status: 'active',
    });

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度必须在3-20个字符之间', trigger: 'blur' },
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' },
      ],
    };

    // 获取用户列表
    const fetchUsers = async (params = {}) => {
      loading.value = true;
      try {
        const response = await api.users.getList({
          page: params.page || pagination.current,
          limit: params.pageSize || pagination.pageSize,
          search: params.search || searchQuery.value,
          ...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('获取用户列表失败');
        
        // 如果API调用失败，使用模拟数据
        const mockUsers = [
          { id: 1, username: 'admin', name: '系统管理员', role: 'admin', status: 'active', createdAt: '2023-01-01' },
          { id: 2, username: 'manager1', name: '张经理', role: 'manager', status: 'active', createdAt: '2023-01-02' },
          { id: 3, username: 'teller1', name: '李柜员', role: 'teller', status: 'active', createdAt: '2023-01-03' },
          { id: 4, username: 'user1', name: '王用户', role: 'user', status: 'disabled', createdAt: '2023-01-04' },
        ];
        users.value = mockUsers;
        pagination.total = mockUsers.length;
      } finally {
        loading.value = false;
      }
    };

    // 表格变化处理
    const handleTableChange = (pag, filters, sorter) => {
      const params = {
        page: pag.current,
        pageSize: pag.pageSize,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      };
      
      pagination.current = pag.current;
      fetchUsers(params);
    };

    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      fetchUsers({ search: searchQuery.value });
    };

    // 显示添加用户对话框
    const showAddUserModal = () => {
      isEditing.value = false;
      resetUserForm();
      userModalVisible.value = true;
    };

    // 编辑用户
    const editUser = (record) => {
      isEditing.value = true;
      Object.assign(userForm, { ...record, password: '' });
      userModalVisible.value = true;
    };

    // 删除用户
    const deleteUser = async (id) => {
      try {
        const response = await api.users.delete(id);
        if (response.success) {
          message.success('用户删除成功');
          fetchUsers({ page: pagination.current });
        } else {
          message.error(response.message || '删除用户失败');
        }
      } catch (error) {
        console.error('删除用户失败:', error);
        message.error('删除用户失败');
      }
    };

    // 提交用户表单
    const handleUserFormSubmit = () => {
      userFormRef.value.validate().then(async () => {
        submitting.value = true;
        try {
          let response;
          if (isEditing.value) {
            // 编辑用户
            response = await api.users.update(userForm.id, userForm);
            if (response.success) {
              message.success('用户更新成功');
            } else {
              message.error(response.message || '更新用户失败');
              return;
            }
          } else {
            // 添加用户
            response = await api.users.create(userForm);
            if (response.success) {
              message.success('用户添加成功');
            } else {
              message.error(response.message || '添加用户失败');
              return;
            }
          }
          userModalVisible.value = false;
          fetchUsers({ page: pagination.current });
        } catch (error) {
          console.error('用户操作失败:', error);
          message.error(isEditing.value ? '更新用户失败' : '添加用户失败');
        } finally {
          submitting.value = false;
        }
      });
    };

    // 重置用户表单
    const resetUserForm = () => {
      userForm.id = null;
      userForm.username = '';
      userForm.password = '';
      userForm.name = '';
      userForm.role = 'user';
      userForm.status = 'active';
      
      // 如果表单已经创建，则重置验证
      if (userFormRef.value) {
        userFormRef.value.resetFields();
      }
    };

    // 获取角色名称
    const getRoleName = (role) => {
      const roleMap = {
        admin: '管理员',
        manager: '经理',
        teller: '柜员',
        user: '普通用户',
      };
      return roleMap[role] || role;
    };

    // 获取角色颜色
    const getRoleColor = (role) => {
      const colorMap = {
        admin: 'red',
        manager: 'blue',
        teller: 'green',
        user: 'default',
      };
      return colorMap[role] || 'default';
    };

    // 生命周期钩子
    onMounted(() => {
      fetchUsers();
    });

    return {
      columns,
      users,
      loading,
      searchQuery,
      pagination,
      userFormRef,
      userModalVisible,
      isEditing,
      submitting,
      userForm,
      rules,
      handleTableChange,
      handleSearch,
      showAddUserModal,
      editUser,
      deleteUser,
      handleUserFormSubmit,
      getRoleName,
      getRoleColor,
    };
  },
});
</script>

<style scoped>
.users-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  color: rgba(0, 0, 0, 0.45);
}

.action-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.danger-link {
  color: #ff4d4f;
}
</style>