<template>
  <div class="account-management">
    <el-card class="main-card">
      <!-- 顶部操作 -->
      <template #header>
        <div class="card-header">
          <el-row :gutter="20" align="middle">
            <el-col :span="16">
              <el-input 
                v-model="searchQuery" 
                placeholder="输入账户ID或姓名搜索" 
                clearable 
                @input="handleSearchInput"
                class="search-input"
              >
              </el-input>
            </el-col>
            <el-col :span="8" class="text-right">
              <el-button type="primary" @click="handleAdd" class="add-btn">
                <el-icon><Plus /></el-icon>新增账户
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>

      <!-- 帐户管理主体内容 -->
      <el-row :gutter="20" class="menu-container">
        <!-- 侧边导航栏 -->
        <el-col :span="4">
          <el-menu
            default-active="all"
            class="category-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="all">
              <el-icon><Menu /></el-icon>全部
            </el-menu-item>
            <el-menu-item index="管理员">
              <el-icon><User /></el-icon>管理员
            </el-menu-item>
            <el-menu-item index="负责人">
              <el-icon><Avatar /></el-icon>负责人
            </el-menu-item>
            <el-menu-item index="顾客">
              <el-icon><UserFilled /></el-icon>顾客
            </el-menu-item>
          </el-menu>
        </el-col>

        <!-- 表格展示区域 -->
        <el-col :span="20">
          <el-card class="account-card">
            <el-table :data="currentAccountList" border style="width: 100%" class="account-table">
              <el-table-column prop="accountImg" label="图片" width="80" align="center">
                <template #default="{ row }">
                  <el-image
                    :src="row.accountImg || 'https://via.placeholder.com/50x50'"
                    :alt="row.accountName"
                    class="account-img"
                    :preview-src-list="[row.accountImg]"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="accountName" label="姓名" />
              <el-table-column prop="accountPhone" label="电话" width="120" />
              <el-table-column prop="accountGender" label="性别" width="80" align="center">
                <template #default="{ row }">
                  <el-tag :type="row.accountGender === '男' ? 'primary' : 'danger'" effect="dark">
                    {{ row.accountGender }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="accountType" label="账户类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="getAccountTypeTag(row.accountType)" effect="dark">
                    {{ row.accountType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="updatedAt" label="更新时间" width="160">
                <template #default="{ row }">
                  {{ formatDate(row.updatedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" align="center">
                <template #default="{ row }">
                  <el-button link type="primary" @click="handleEdit(row)" class="action-btn">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button link type="danger" @click="handleDelete(row)" class="action-btn">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                  <el-button link type="warning" @click="handleResetPassword(row)" class="action-btn">
                    <el-icon><Refresh /></el-icon>重置密码
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total, prev, pager, next, jumper"
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑账户弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="accountForm.accountId ? '编辑账户' : '新增账户'" width="40%" class="account-dialog">
      <el-form :model="accountForm" ref="formRef" :rules="rules" label-width="120px" class="account-form">
        <!-- 姓名 -->
        <el-form-item label="姓名" prop="accountName">
          <el-input v-model="accountForm.accountName" autocomplete="off" placeholder="请输入姓名" />
        </el-form-item>

        <!-- 电话 -->
        <el-form-item label="电话" prop="accountPhone">
          <el-input v-model="accountForm.accountPhone" autocomplete="off" placeholder="请输入电话" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="accountGender">
          <el-select v-model="accountForm.accountGender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <!-- 账户类型 -->
        <el-form-item label="账户类型" prop="accountType">
          <el-select v-model="accountForm.accountType" placeholder="请选择账户类型" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="员工" value="员工" />
            <el-option label="顾客" value="顾客" />
          </el-select>
        </el-form-item>

        <!-- 图片地址 -->
        <el-form-item label="图片地址" prop="accountImg">
          <el-input v-model="accountForm.accountImg" placeholder="请输入图片URL" />
        </el-form-item>

        <!-- 初始密码 -->
        <el-form-item label="初始密码" prop="accountPassword" v-if="!accountForm.accountId">
          <el-input v-model="accountForm.accountPassword" type="password" placeholder="请输入初始密码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleConfirm" class="confirm-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  Plus,
  Edit,
  Delete,
  Refresh,
  Menu,
  User,
  Avatar,
  UserFilled
} from '@element-plus/icons-vue';

// 搜索功能
const searchQuery = ref('');

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 存储账户数据
const accountList = ref([]);

// 当前选中的菜单项
const currentAccountType = ref('all');

// 动态计算当前展示的账户数据
const currentAccountList = computed(() => {
  return accountList.value;
});

// 获取账户类型标签样式
const getAccountTypeTag = (type) => {
  const types = {
    '管理员': 'success',
    '员工': 'warning',
    '顾客': 'info'
  };
  return types[type] || 'info';
};

// 获取账户数据（按类型）
const fetchAccounts = async (accountType, page, size) => {
  try {
    let url = `http://localhost:8080/admin/accounts`;
    let params = { 
      pageNum: page, 
      pageSize: size 
    };

    if (accountType !== 'all') {
      url = `http://localhost:8080/admin/accounts/byType`;
      params.accountType = accountType;
    }

    const response = await axios.get(url, { params });
    pagination.value.total = response.data.data.total;
    accountList.value = response.data.data.records.map(item => ({
      accountId: item.accountId,
      accountName: item.accountName,
      accountPhone: item.accountPhone,
      accountGender: item.accountGender,
      accountType: item.accountType,
      accountImg: item.accountImg,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt
    }));
  } catch (error) {
    console.error('获取账户数据失败：', error);
    ElMessage.error('获取账户数据失败');
  }
};

// 搜索框输入变化时触发
const handleSearchInput = (val) => {
  if (val.trim() === '') {
    fetchAccounts(currentAccountType.value, pagination.value.page, pagination.value.pageSize);
  }
};

// 根据关键词搜索账户
const searchAccounts = async (keyword, page, size) => {
  try {
    const params = {
      pageNum: page,
      pageSize: size
    };

    // 根据关键字类型设置不同参数
    if (/^\d+$/.test(keyword)) {
      params.id = keyword;
    } else {
      params.accountName = keyword;
      params.accountPhone = keyword;
    }

    const response = await axios.get('http://localhost:8080/admin/accounts/search', { params });
    pagination.value.total = response.data.data.total;
    accountList.value = response.data.data.records.map(item => ({
      accountId: item.accountId,
      accountName: item.accountName,
      accountPhone: item.accountPhone,
      accountGender: item.accountGender,
      accountType: item.accountType,
      accountImg: item.accountImg,
      createdAt: item.createdAt,
      updatedAt: item.updatedAt
    }));
  } catch (error) {
    console.error('搜索账户失败:', error);
    ElMessage.error('搜索账户失败');
  }
};

// 新增/编辑账户相关
const dialogFormVisible = ref(false);
const formRef = ref();
const accountForm = ref({
  accountId: null,
  accountName: '',
  accountPhone: '',
  accountGender: '',
  accountType: '',
  accountImg: '',
  accountPassword: '123456'
});

// 表单验证规则
const rules = ref({
  accountName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  accountPhone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  accountGender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
  accountPassword: [{ required: true, message: '请输入初始密码', trigger: 'blur' }]
});

// 处理新增操作
const handleAdd = () => {
  dialogFormVisible.value = true;
  accountForm.value = {
    accountId: null,
    accountName: '',
    accountPhone: '',
    accountGender: '',
    accountType: '',
    accountImg: '',
    accountPassword: '123456'
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理编辑操作
const handleEdit = (row) => {
  dialogFormVisible.value = true;
  accountForm.value = { 
    accountId: row.accountId,
    accountName: row.accountName,
    accountPhone: row.accountPhone,
    accountGender: row.accountGender,
    accountType: row.accountType,
    accountImg: row.accountImg
  };
};

// 保存或更新账户
const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const url = accountForm.value.accountId 
        ? `http://localhost:8080/admin/accounts/${accountForm.value.accountId}` 
        : 'http://localhost:8080/admin/accounts';
      
      const method = accountForm.value.accountId ? 'put' : 'post';

      axios[method](url, {
        accountName: accountForm.value.accountName,
        accountPhone: accountForm.value.accountPhone,
        accountGender: accountForm.value.accountGender,
        accountType: accountForm.value.accountType,
        accountImg: accountForm.value.accountImg,
        accountPassword: accountForm.value.accountPassword
      })
        .then(response => {
          if (response.status >= 200 && response.status < 300) {
            ElMessage.success(accountForm.value.accountId ? '账户更新成功' : '账户新增成功');
            dialogFormVisible.value = false;
            
            // 刷新数据
            if (searchQuery.value) {
              searchAccounts(searchQuery.value, pagination.value.page, pagination.value.pageSize);
            } else {
              fetchAccounts(
                currentAccountType.value, 
                pagination.value.page, 
                pagination.value.pageSize
              );
            }
          } else {
            ElMessage.error('账户操作失败');
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          ElMessage.error('请求失败，请稍后重试');
        });
    }
  });
};

// 删除账户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除账户 "${row.accountName}" 吗？此操作不可逆！`,
    '删除确认',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.delete(`http://localhost:8080/admin/accounts/${row.accountId}`)
      .then(response => {
        if (response.status >= 200 && response.status < 300) {
          ElMessage.success('删除成功');
          if (searchQuery.value) {
            searchAccounts(searchQuery.value, pagination.value.page, pagination.value.pageSize);
          } else {
            fetchAccounts(
              currentAccountType.value, 
              pagination.value.page, 
              pagination.value.pageSize
            );
          }
        } else {
          ElMessage.error('删除失败，请稍后重试');
        }
      })
      .catch(error => {
        console.error('删除账户失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 重置密码
const handleResetPassword = (row) => {
  ElMessageBox.confirm(
    `确认重置账户 "${row.accountName}" 的密码吗？密码将重置为123456`,
    '密码重置确认',
    {
      confirmButtonText: '确认重置',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.put(`http://localhost:8080/admin/accounts/${row.accountId}/reset-password`)
      .then(response => {
        if (response.status >= 200 && response.status < 300) {
          ElMessage.success('密码重置成功');
          if (searchQuery.value) {
            searchAccounts(searchQuery.value, pagination.value.page, pagination.value.pageSize);
          } else {
            fetchAccounts(
              currentAccountType.value, 
              pagination.value.page, 
              pagination.value.pageSize
            );
          }
        } else {
          ElMessage.error('密码重置失败，请稍后重试');
        }
      })
      .catch(error => {
        console.error('密码重置失败:', error);
        ElMessage.error('密码重置失败，请稍后重试');
      });
  }).catch(() => {
    ElMessage.info('已取消密码重置');
  });
};

// 事件处理
const handleMenuSelect = (index) => {
  currentAccountType.value = index;
  pagination.value.page = 1;
  searchQuery.value = '';
  fetchAccounts(index, pagination.value.page, pagination.value.pageSize);
};

const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1;
  if (searchQuery.value) {
    searchAccounts(searchQuery.value, pagination.value.page, size);
  } else {
    fetchAccounts(currentAccountType.value, pagination.value.page, size);
  }
};

const handlePageChange = (page) => {
  if (searchQuery.value) {
    searchAccounts(searchQuery.value, page, pagination.value.pageSize);
  } else {
    fetchAccounts(currentAccountType.value, page, pagination.value.pageSize);
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString();
};

// 监听搜索框变化
watch(searchQuery, (newVal) => {
  if (newVal) {
    pagination.value.page = 1;
    searchAccounts(newVal, pagination.value.page, pagination.value.pageSize);
  } else {
    fetchAccounts(
      currentAccountType.value, 
      pagination.value.page, 
      pagination.value.pageSize
    );
  }
});

// 组件挂载时加载默认数据
onMounted(() => {
  fetchAccounts(currentAccountType.value, pagination.value.page, pagination.value.pageSize);
});
</script>

<style scoped>
.account-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.main-card :deep(.el-card__header) {
  background: linear-gradient(120deg, #f0f7ff, #e6f7ff);
  border-radius: 12px 12px 0 0;
  padding: 16px 24px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-input {
  max-width: 400px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 20px;
  height: 40px;
  padding-left: 40px;
}

.search-input :deep(.el-input__prefix) {
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
}

.add-btn {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 600;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.25);
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.35);
}

.menu-container {
  margin-top: 12px;
}

.category-menu {
  height: 600px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.category-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  color: #5a5e66;
  transition: all 0.2s;
  border-radius: 8px;
  margin: 4px 8px;
  width: calc(100% - 16px);
}

.category-menu :deep(.el-menu-item):hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.category-menu :deep(.el-menu-item.is-active) {
  background: linear-gradient(90deg, #ecf5ff, #fff);
  color: #409eff;
  font-weight: 600;
  border-left: 4px solid #409eff;
}

.category-menu .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.account-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.account-card :deep(.el-card__body) {
  padding: 0;
}

.account-table {
  border-radius: 8px;
  overflow: hidden;
}

.account-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #409eff;
  font-weight: 600;
}

.account-table :deep(tr:hover) {
  background-color: #f0f7ff !important;
}

.account-img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 50%;
  display: block;
  margin: 0 auto;
  background-color: #f5f5f5;
}

.action-btn {
  padding: 5px 8px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 2px;
}

.action-btn .el-icon {
  margin-right: 4px;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
}

.account-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.account-form {
  padding: 0 20px;
}

.account-form .el-form-item {
  margin-bottom: 22px;
}

.account-form :deep(.el-input__inner),
.account-form :deep(.el-textarea__inner) {
  border-radius: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 20px;
}

.cancel-btn {
  border-radius: 20px;
  padding: 8px 20px;
}

.confirm-btn {
  border-radius: 20px;
  padding: 8px 20px;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s;
}

.confirm-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
}

.text-right {
  text-align: right;
}
</style>