/**
 * 商品分类 Mock 数据
 */

// 生成分类数据
const generateCategories = (count = 20) => {
  const categories = [];
  const categoryNames = [
    '电子产品',
    '服装鞋帽',
    '家居用品',
    '美妆护肤',
    '食品饮料',
    '运动户外',
    '图书音像',
    '母婴用品',
    '汽车用品',
    '办公用品',
    '珠宝首饰',
    '手机数码',
    '家用电器',
    '箱包皮具',
    '玩具乐器',
    '医疗保健',
    '五金工具',
    '建材装修',
    '农资园艺',
    '宠物用品',
  ];

  for (let i = 1; i <= count; i++) {
    const createTime = new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000);
    const updateTime = new Date(createTime.getTime() + Math.random() * 30 * 24 * 60 * 60 * 1000);

    categories.push({
      id: i,
      title: categoryNames[i - 1] || `分类${i}`,
      sort: Math.floor(Math.random() * 100),
      status: Math.random() > 0.2 ? 1 : 0, // 80% 启用
      create_time: createTime.toISOString().slice(0, 19).replace('T', ' '),
      update_time: updateTime.toISOString().slice(0, 19).replace('T', ' '),
    });
  }

  return categories.sort((a, b) => b.id - a.id); // 按ID倒序
};

// 模拟数据
let mockCategories = generateCategories(20);

// 分页函数
const paginate = (data, page = 1, perPage = 10) => {
  const start = (page - 1) * perPage;
  const end = start + perPage;
  const paginatedData = data.slice(start, end);

  return {
    data: paginatedData,
    current_page: page,
    per_page: perPage,
    total: data.length,
    last_page: Math.ceil(data.length / perPage),
  };
};

// 搜索过滤函数
const filterCategories = (categories, searchParams) => {
  let filtered = [...categories];

  // 按名称搜索
  if (searchParams.name) {
    filtered = filtered.filter((item) =>
      item.title.toLowerCase().includes(searchParams.name.toLowerCase()),
    );
  }

  return filtered;
};

// 排序函数
const sortCategories = (categories, sort, order) => {
  if (!sort) return categories;

  return [...categories].sort((a, b) => {
    let aVal = a[sort];
    let bVal = b[sort];

    // 处理数字类型
    if (sort === 'id' || sort === 'sort') {
      aVal = Number(aVal);
      bVal = Number(bVal);
    }

    if (order === 'asc') {
      return aVal > bVal ? 1 : -1;
    } else {
      return aVal < bVal ? 1 : -1;
    }
  });
};

export default {
  // 获取分类列表
  'GET /admin/shop/admin/category_tag': (req, res) => {
    const { page = 1, size = 10, sort = 'id', order = 'desc', name = '' } = req.query;

    // 搜索过滤
    let filtered = filterCategories(mockCategories, { name });

    // 排序
    filtered = sortCategories(filtered, sort, order);

    // 分页
    const result = paginate(filtered, parseInt(page), parseInt(size));

    res.json({
      error: 0,
      msg: 'success',
      data: result,
    });
  },

  // 获取分类详情
  'GET /admin/shop/admin/category_tag/:id': (req, res) => {
    const { id } = req.params;
    const category = mockCategories.find((item) => item.id == id);

    if (category) {
      res.json({
        error: 0,
        msg: 'success',
        data: category,
      });
    } else {
      res.json({
        error: 1,
        msg: '分类不存在',
        data: null,
      });
    }
  },

  // 新增分类
  'POST /admin/shop/admin/category_tag': (req, res) => {
    const { title, sort = 0 } = req.body;

    if (!title) {
      return res.json({
        error: 1,
        msg: '分类名称不能为空',
        data: null,
      });
    }

    const newId = Math.max(...mockCategories.map((item) => item.id)) + 1;
    const now = new Date().toISOString().slice(0, 19).replace('T', ' ');

    const newCategory = {
      id: newId,
      title,
      sort: parseInt(sort),
      status: 1,
      create_time: now,
      update_time: now,
    };

    mockCategories.unshift(newCategory);

    res.json({
      error: 0,
      msg: '添加成功',
      data: newCategory,
    });
  },

  // 编辑分类
  'PUT /admin/shop/admin/category_tag/:id': (req, res) => {
    const { id } = req.params;
    const { title, sort } = req.body;

    const index = mockCategories.findIndex((item) => item.id == id);

    if (index === -1) {
      return res.json({
        error: 1,
        msg: '分类不存在',
        data: null,
      });
    }

    if (!title) {
      return res.json({
        error: 1,
        msg: '分类名称不能为空',
        data: null,
      });
    }

    const now = new Date().toISOString().slice(0, 19).replace('T', ' ');

    mockCategories[index] = {
      ...mockCategories[index],
      title,
      sort: parseInt(sort || 0),
      update_time: now,
    };

    res.json({
      error: 0,
      msg: '更新成功',
      data: mockCategories[index],
    });
  },

  // 删除分类
  'DELETE /admin/shop/admin/category_tag/:id': (req, res) => {
    const { id } = req.params;
    const ids = id.split(',').map((item) => parseInt(item));

    // 批量删除
    mockCategories = mockCategories.filter((item) => !ids.includes(item.id));

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

  // 获取分类选择列表（用于其他模块选择分类）
  'GET /admin/shop/admin/category_tag/select': (req, res) => {
    const selectData = mockCategories
      .filter((item) => item.status === 1)
      .map((item) => ({
        value: item.id,
        label: item.title,
        sort: item.sort,
      }))
      .sort((a, b) => a.sort - b.sort);

    res.json({
      error: 0,
      msg: 'success',
      data: selectData,
    });
  },
};
