import { Request, Response } from 'express';

const appTypeList: string[] = ['pc', 'h5', 'miniapp', 'webapp'];
const statusList: string[] = ['developing', 'online', 'offline', 'maintenance'];

const genAppList = () => {
  const appData = [
    {
      name: '企业官网',
      icon: '🏢',
      type: 'pc',
      desc: '企业官方网站，展示品牌形象',
    },
    { name: '管理后台', icon: '⚙️', type: 'pc', desc: '企业内部管理系统' },
    { name: '移动端官网', icon: '📱', type: 'h5', desc: '移动端展示网站' },
    { name: '微信小程序', icon: '💬', type: 'miniapp', desc: '微信生态小程序' },
    {
      name: '员工Portal',
      icon: '👥',
      type: 'webapp',
      desc: '员工工作入口平台',
    },
    { name: '客户管理系统', icon: '🤝', type: 'pc', desc: 'CRM客户关系管理' },
    { name: '微商城', icon: '🛒', type: 'miniapp', desc: '微信小程序商城' },
    {
      name: '数据分析平台',
      icon: '📊',
      type: 'pc',
      desc: '企业数据可视化平台',
    },
    { name: '移动OA', icon: '📋', type: 'h5', desc: '移动办公应用' },
    { name: '知识库', icon: '📚', type: 'webapp', desc: '企业知识管理平台' },
    { name: '招聘系统', icon: '👔', type: 'pc', desc: '在线招聘管理平台' },
    { name: '会议系统', icon: '🎥', type: 'webapp', desc: '视频会议管理' },
  ];

  return appData.map((item, index) => ({
    id: `app-${index + 1}`,
    appName: item.name,
    appDesc: item.desc,
    appIcon: item.icon,
    appType: item.type,
    status: statusList[index % 4],
    version: `v${Math.floor(Math.random() * 3) + 1}.${Math.floor(
      Math.random() * 10,
    )}.${Math.floor(Math.random() * 20)}`,
    owner: ['张三', '李四', '王五', '赵六', '钱七'][index % 5],
    url: `https://app${index + 1}.example.com`,
    tags: [
      ['企业', '重要'],
      ['内部', '核心'],
      ['移动端', '新项目'],
      ['微信生态'],
    ][index % 4],
    createdAt: new Date(
      Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000,
    ).toISOString(),
    updatedAt: new Date(
      Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000,
    ).toISOString(),
  }));
};

let appDataSource = genAppList();

// 计算统计数据
const calculateStats = () => {
  const stats = {
    total: appDataSource.length,
    online: 0,
    developing: 0,
    offline: 0,
    maintenance: 0,
  };
  appDataSource.forEach((app: { status: string }) => {
    if (app.status === 'online') stats.online++;
    else if (app.status === 'developing') stats.developing++;
    else if (app.status === 'offline') stats.offline++;
    else if (app.status === 'maintenance') stats.maintenance++;
  });
  return stats;
};

export default {
  'GET /api/projects': (req: Request, res: Response) => {
    const current = Number(req.query.current) || 1;
    const pageSize = Number(req.query.pageSize) || 12;
    const appName = req.query.appName as string | undefined;
    const owner = req.query.owner as string | undefined;
    const appType = req.query.appType as string | undefined;
    const status = req.query.status as string | undefined;

    let filtered = [...appDataSource];

    // 关键词搜索
    if (appName) {
      filtered = filtered.filter((p) => p.appName.includes(appName));
    }
    if (owner) {
      filtered = filtered.filter((p) => p.owner.includes(owner));
    }
    if (appType) {
      filtered = filtered.filter((p) => p.appType === appType);
    }
    if (status) {
      filtered = filtered.filter((p) => p.status === status);
    }

    // 分页
    const start = (current - 1) * pageSize;
    const data = filtered.slice(start, start + pageSize);

    res.json({
      data,
      total: filtered.length,
      success: true,
      current,
      pageSize,
    });
  },

  'GET /api/projects/stats': (_req: Request, res: Response) => {
    const stats = calculateStats();
    res.json({
      stats,
      success: true,
    });
  },

  'POST /api/projects': (req: Request, res: Response) => {
    const newApp = {
      ...req.body,
      id: `app-${Date.now()}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    appDataSource.unshift(newApp);
    res.json(newApp);
  },

  'PUT /api/projects/:id': (req: Request, res: Response) => {
    const { id } = req.params;
    const index = appDataSource.findIndex((p) => p.id === id);
    if (index !== -1) {
      appDataSource[index] = {
        ...appDataSource[index],
        ...req.body,
        updatedAt: new Date().toISOString(),
      };
      res.json(appDataSource[index]);
    } else {
      res.status(404).json({ success: false, message: '应用不存在' });
    }
  },

  'PUT /api/projects/:id/status': (req: Request, res: Response) => {
    const { id } = req.params;
    const { status } = req.body;
    const index = appDataSource.findIndex((p) => p.id === id);
    if (index !== -1) {
      appDataSource[index] = {
        ...appDataSource[index],
        status,
        updatedAt: new Date().toISOString(),
      };
      res.json(appDataSource[index]);
    } else {
      res.status(404).json({ success: false, message: '应用不存在' });
    }
  },

  'DELETE /api/projects/:id': (req: Request, res: Response) => {
    const { id } = req.params;
    appDataSource = appDataSource.filter((p) => p.id !== id);
    res.json({ success: true });
  },
};
