import { http, HttpResponse } from 'msw';
import { generatePaginationData } from '../utils';

// 用户状态枚举
const USER_STATUS = {
  NORMAL: 'normal',
  WITHDRAW_DISABLED: 'withdraw_disabled',
  LOGIN_DISABLED: 'login_disabled',
};

// 用户等级数据
const userLevels = [
  { id: 1, name: 'V1', icon: '🥉' },
  { id: 2, name: 'V2', icon: '🥈' },
  { id: 3, name: 'V3', icon: '🥇' },
  { id: 4, name: 'V4', icon: '💎' },
  { id: 5, name: 'V5', icon: '👑' },
  { id: 6, name: 'V6', icon: '⭐' },
  { id: 7, name: 'V7', icon: '🌟' },
  { id: 8, name: 'V8', icon: '✨' },
];

// 生成用户数据
const generateUserData = (id) => {
  const level = userLevels[Math.floor(Math.random() * userLevels.length)];
  const status =
    Object.values(USER_STATUS)[Math.floor(Math.random() * Object.values(USER_STATUS).length)];
  const banks = ['中国银行', '工商银行', '建设银行', '农业银行', '招商银行', '交通银行'];
  const bank = banks[Math.floor(Math.random() * banks.length)];

  return {
    id: `B12345${String(id).padStart(2, '0')}`,
    username: `Aamru Khan`,
    nickname: `用户${id}`,
    mobile: `8864223${String(id).padStart(4, '0')}`,
    level: level.name,
    level_id: level.id,
    invite_count: Math.floor(Math.random() * 1000) + 1,
    team_count: Math.floor(Math.random() * 10000) + 10,
    success_orders: Math.floor(Math.random() * 100) + 10,
    balance: `৳${(Math.random() * 10000).toFixed(0)}`,
    commission_balance: `৳${(Math.random() * 5000).toFixed(0)}`,
    status: status,
    status_text:
      status === USER_STATUS.NORMAL
        ? '正常'
        : status === USER_STATUS.WITHDRAW_DISABLED
          ? '禁止提现'
          : '禁止登录',
    remark: Math.random() > 0.8 ? '活跃用户' : '',
    register_time: `2025/06/06 12:30:30`,
    avatar:
      'https://mall-oss.trust-will.com/storage/default/20250701/7bf12c56300454532244dec2aff808eb.jpg?x-oss-process=image/resize,w_200,h_200',
    // 新增字段
    bank_name: bank,
    account_name: `用户${id}`,
    account_number: `6222${String(Math.floor(Math.random() * 10000000000000000)).padStart(16, '0')}`,
    password: '123456',
    permissions:
      status === USER_STATUS.NORMAL
        ? ['normal']
        : status === USER_STATUS.WITHDRAW_DISABLED
          ? ['normal', 'withdraw_disabled']
          : ['normal', 'login_disabled'],
  };
};

// 生成用户列表数据
const generateUserList = (count = 50) => {
  return Array.from({ length: count }, (_, index) => generateUserData(index + 1));
};

const userList = generateUserList();

export const userHandlers = [
  // 用户列表
  http.get('https://shop.trust-will.com/shop/admin/user/list', ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('size') || '10');
    const username = url.searchParams.get('username') || '';
    const mobile = url.searchParams.get('mobile') || '';
    const status = url.searchParams.get('status') || '';
    const startTime = url.searchParams.get('start_time') || '';
    const endTime = url.searchParams.get('end_time') || '';

    // 过滤数据
    let filteredData = userList;

    if (username) {
      filteredData = filteredData.filter(
        (user) =>
          user.username.toLowerCase().includes(username.toLowerCase()) ||
          user.nickname.toLowerCase().includes(username.toLowerCase()),
      );
    }

    if (mobile) {
      filteredData = filteredData.filter((user) => user.mobile.includes(mobile));
    }

    if (status && status !== 'all') {
      filteredData = filteredData.filter((user) => user.status === status);
    }

    const paginatedData = generatePaginationData(filteredData, page, pageSize);

    return HttpResponse.json({
      error: 0,
      msg: '获取成功',
      data: paginatedData,
    });
  }),

  // 用户详情
  http.get('https://shop.trust-will.com/shop/admin/user/list/:id', ({ params }) => {
    const user = userList.find((u) => u.id === params.id);

    if (!user) {
      return HttpResponse.json({
        error: 1,
        msg: '用户不存在',
        data: null,
      });
    }

    return HttpResponse.json({
      error: 0,
      msg: '获取成功',
      data: user,
    });
  }),

  // 编辑用户
  http.put('https://shop.trust-will.com/shop/admin/user/list/:id', async ({ params, request }) => {
    const data = await request.json();
    const userIndex = userList.findIndex((u) => u.id === params.id);

    if (userIndex === -1) {
      return HttpResponse.json({
        error: 1,
        msg: '用户不存在',
        data: null,
      });
    }

    // 更新用户数据
    userList[userIndex] = { ...userList[userIndex], ...data };

    return HttpResponse.json({
      error: 0,
      msg: '更新成功',
      data: userList[userIndex],
    });
  }),

  // 删除用户
  http.delete('https://shop.trust-will.com/shop/admin/user/list/:id', ({ params }) => {
    const userIndex = userList.findIndex((u) => u.id === params.id);

    if (userIndex === -1) {
      return HttpResponse.json({
        error: 1,
        msg: '用户不存在',
        data: null,
      });
    }

    userList.splice(userIndex, 1);

    return HttpResponse.json({
      error: 0,
      msg: '删除成功',
      data: null,
    });
  }),

  // 用户统计
  http.get('https://shop.trust-will.com/shop/admin/user/list/statistics', () => {
    const totalUsers = userList.length;
    const normalUsers = userList.filter((u) => u.status === USER_STATUS.NORMAL).length;
    const withdrawDisabledUsers = userList.filter(
      (u) => u.status === USER_STATUS.WITHDRAW_DISABLED,
    ).length;
    const loginDisabledUsers = userList.filter(
      (u) => u.status === USER_STATUS.LOGIN_DISABLED,
    ).length;

    return HttpResponse.json({
      error: 0,
      msg: '获取成功',
      data: {
        total: totalUsers,
        normal: normalUsers,
        withdraw_disabled: withdrawDisabledUsers,
        login_disabled: loginDisabledUsers,
      },
    });
  }),

  // 用户详情
  http.get('https://shop.trust-will.com/shop/admin/user/list/:id', ({ params }) => {
    const { id } = params;
    const user = userList.find((u) => u.id === id);

    if (!user) {
      return HttpResponse.json({
        error: 1,
        msg: '用户不存在',
        data: null,
      });
    }

    // 扩展用户详情数据
    const userDetail = {
      ...user,
      user_id: user.id,
      created_at: user.register_time,
      total_commission: (Math.random() * 50000).toFixed(0),
      settled_commission: (Math.random() * 30000).toFixed(0),
      recharge_total: (Math.random() * 100000).toFixed(0),
      week_commission: (Math.random() * 5000).toFixed(0),
      pending_commission: (Math.random() * 10000).toFixed(0),
      withdraw_total: (Math.random() * 20000).toFixed(0),
      group_count: Math.floor(Math.random() * 50) + 1,
    };

    return HttpResponse.json({
      error: 0,
      msg: '获取成功',
      data: userDetail,
    });
  }),

  // 用户订单记录
  http.get('https://shop.trust-will.com/shop/admin/user/list/:id/orders', ({ params, request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('size') || '10');

    // 生成订单数据
    const orders = Array.from({ length: 20 }, (_, index) => ({
      id: `ORD${String(index + 1).padStart(6, '0')}`,
      order_sn: `2025010${String(index + 1).padStart(6, '0')}`,
      items: [
        {
          goods_image:
            'https://mall-oss.trust-will.com/storage/default/20250701/7bf12c56300454532244dec2aff808eb.jpg?x-oss-process=image/resize,w_200,h_200',
          goods_title: `商品名称${index + 1}`,
          goods_sku_text: '黑色/L',
          goods_num: Math.floor(Math.random() * 5) + 1,
        },
      ],
      pay_fee: (Math.random() * 1000 + 100).toFixed(0),
      status_text: ['待付款', '待发货', '待收货', '已完成'][Math.floor(Math.random() * 4)],
      express_info: '顺丰快递',
      created_at: '2025/06/06 12:30:30',
      pay_time: '2025/06/06 12:35:30',
    }));

    const paginatedData = generatePaginationData(orders, page, pageSize);

    return HttpResponse.json({
      error: 0,
      msg: '获取成功',
      data: paginatedData,
    });
  }),

  // 用户下线用户
  http.get(
    'https://shop.trust-will.com/shop/admin/user/list/:id/subordinates',
    ({ params, request }) => {
      const url = new URL(request.url);
      const page = parseInt(url.searchParams.get('page') || '1');
      const pageSize = parseInt(url.searchParams.get('size') || '10');

      const subordinates = Array.from({ length: 15 }, (_, index) => ({
        id: index + 1,
        nickname: `下线用户${index + 1}`,
        mobile: `1380000${String(index + 1).padStart(4, '0')}`,
        created_at: '2025/06/06 12:30:30',
        level: Math.floor(Math.random() * 8) + 1,
      }));

      const paginatedData = generatePaginationData(subordinates, page, pageSize);

      return HttpResponse.json({
        error: 0,
        msg: '获取成功',
        data: paginatedData,
      });
    },
  ),

  // 用户佣金记录
  http.get(
    'https://shop.trust-will.com/shop/admin/user/list/:id/commissions',
    ({ params, request }) => {
      const url = new URL(request.url);
      const page = parseInt(url.searchParams.get('page') || '1');
      const pageSize = parseInt(url.searchParams.get('size') || '10');

      const commissions = Array.from({ length: 25 }, (_, index) => ({
        commission_id: `COM${String(index + 1).padStart(6, '0')}`,
        type_text: ['推荐佣金', '团队佣金', '销售佣金'][Math.floor(Math.random() * 3)],
        description: `佣金说明${index + 1}`,
        amount: (Math.random() * 500 + 50).toFixed(0),
        status_text: ['已发放', '待发放'][Math.floor(Math.random() * 2)],
        created_at: '2025/06/06 12:30:30',
      }));

      const paginatedData = generatePaginationData(commissions, page, pageSize);

      return HttpResponse.json({
        error: 0,
        msg: '获取成功',
        data: paginatedData,
      });
    },
  ),

  // 用户充值记录
  http.get(
    'https://shop.trust-will.com/shop/admin/user/list/:id/recharges',
    ({ params, request }) => {
      const url = new URL(request.url);
      const page = parseInt(url.searchParams.get('page') || '1');
      const pageSize = parseInt(url.searchParams.get('size') || '10');

      const recharges = Array.from({ length: 18 }, (_, index) => ({
        id: index + 1,
        order_sn: `RCH${String(index + 1).padStart(6, '0')}`,
        channel_text: ['支付宝', '微信支付', '银行卡'][Math.floor(Math.random() * 3)],
        currency: 'BDT',
        amount: (Math.random() * 5000 + 100).toFixed(0),
        status_text: ['成功', '失败', '处理中'][Math.floor(Math.random() * 3)],
        created_at: '2025/06/06 12:30:30',
        success_time: '2025/06/06 12:35:30',
      }));

      const paginatedData = generatePaginationData(recharges, page, pageSize);

      return HttpResponse.json({
        error: 0,
        msg: '获取成功',
        data: paginatedData,
      });
    },
  ),

  // 用户提现记录
  http.get(
    'https://shop.trust-will.com/shop/admin/user/list/:id/withdraws',
    ({ params, request }) => {
      const url = new URL(request.url);
      const page = parseInt(url.searchParams.get('page') || '1');
      const pageSize = parseInt(url.searchParams.get('size') || '10');

      const withdraws = Array.from({ length: 12 }, (_, index) => ({
        id: index + 1,
        order_sn: `WTH${String(index + 1).padStart(6, '0')}`,
        type_text: '余额提现',
        channel_text: ['银行卡', 'BKASH', 'Nagad'][Math.floor(Math.random() * 3)],
        currency: 'BDT',
        amount: (Math.random() * 3000 + 100).toFixed(0),
        status_text: ['成功', '失败', '审核中'][Math.floor(Math.random() * 3)],
        bank_name: 'BKASH',
        account_name: `用户${index + 1}`,
        account_number: `8864223${String(index + 1).padStart(4, '0')}`,
        created_at: '2025/06/06 12:30:30',
        success_time: '2025/06/06 12:35:30',
      }));

      const paginatedData = generatePaginationData(withdraws, page, pageSize);

      return HttpResponse.json({
        error: 0,
        msg: '获取成功',
        data: paginatedData,
      });
    },
  ),

  // 用户收货地址
  http.get(
    'https://shop.trust-will.com/shop/admin/user/list/:id/addresses',
    ({ params, request }) => {
      const url = new URL(request.url);
      const page = parseInt(url.searchParams.get('page') || '1');
      const pageSize = parseInt(url.searchParams.get('size') || '10');

      const addresses = Array.from({ length: 5 }, (_, index) => ({
        id: index + 1,
        consignee: `收件人${index + 1}`,
        mobile: `1380000${String(index + 1).padStart(4, '0')}`,
        address: `详细地址${index + 1}，某某区某某街道某某号`,
      }));

      const paginatedData = generatePaginationData(addresses, page, pageSize);

      return HttpResponse.json({
        error: 0,
        msg: '获取成功',
        data: paginatedData,
      });
    },
  ),
];
