import { http, HttpResponse } from 'msw';
import adminMockData from '../admin.js';
import profileData from '../data/profile.js';

// 人员管理相关的mock处理器
export const adminHandlers = [
  // 人员列表
  http.post('*/admin/list', async ({ request }) => {
    const data = await request.json();
    const result = adminMockData['admin/list'](data);
    return HttpResponse.json(result);
  }),

  // 人员详情
  http.post('*/admin/detail', async ({ request }) => {
    const data = await request.json();
    const result = adminMockData['admin/detail'](data);
    return HttpResponse.json(result);
  }),

  // 新增人员
  http.post('*/admin/add', async ({ request }) => {
    const data = await request.json();
    const result = adminMockData['admin/add'](data);
    return HttpResponse.json(result);
  }),

  // 编辑人员
  http.post('*/admin/edit', async ({ request }) => {
    const data = await request.json();
    const result = adminMockData['admin/edit'](data);
    return HttpResponse.json(result);
  }),

  // 删除人员
  http.post('*/admin/delete', async ({ request }) => {
    const data = await request.json();
    const result = adminMockData['admin/delete'](data);
    return HttpResponse.json(result);
  }),

  // 获取个人信息
  http.get('*/admin/index/profile', () => {
    return HttpResponse.json({
      code: '200',
      message: '操作成功',
      data: profileData,
    });
  }),

  // 更新个人信息
  http.post('*/admin/index/update', async ({ request }) => {
    const data = await request.json();
    // 更新profile数据
    Object.assign(profileData, data, {
      update_time: new Date().toLocaleString('zh-CN'),
    });

    return HttpResponse.json({
      code: '200',
      message: '更新成功',
      data: profileData,
    });
  }),

  // 登录接口
  http.post('*/admin/index/login', async ({ request }) => {
    const data = await request.json();

    // 简单验证
    if (data.account === 'admin' && data.password === '123456') {
      return HttpResponse.json({
        code: '200',
        message: '登录成功',
        data: {
          token: profileData.token,
          userInfo: profileData,
        },
      });
    } else {
      return HttpResponse.json({
        code: '500',
        message: '用户名或密码错误',
        data: null,
      });
    }
  }),

  // 登出接口
  http.post('*/admin/index/logout', () => {
    return HttpResponse.json({
      code: '200',
      message: '登出成功',
      data: null,
    });
  }),

  // 获取菜单权限
  http.get('*/admin/index/rules', () => {
    return HttpResponse.json({
      code: '200',
      message: '操作成功',
      data: ['*'], // 所有权限
    });
  }),

  // 清空缓存
  http.post('*/admin/index/clearCache', () => {
    return HttpResponse.json({
      code: '200',
      message: '缓存清空成功',
      data: null,
    });
  }),
];
