/**
 * 意见反馈管理控制器（客户端接口）
 * 提供客户端调用的意见反馈相关接口
 */

const Framework = require("../../framework/node-core-framework.js");

module.exports = {
  /**
   * @swagger
   * /api/feedback/submit:
   *   post:
   *     summary: 提交反馈
   *     description: 提交用户反馈
   *     tags: [前端-意见反馈]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - type
   *               - content
   *             properties:
   *               type:
   *                 type: string
   *                 description: 反馈类型
   *               content:
   *                 type: string
   *                 description: 反馈内容
   *               contact:
   *                 type: string
   *                 description: 联系方式（可选）
   *     responses:
   *       200:
   *         description: 提交成功
   */
  'POST /feedback/submit': async (ctx) => {
    try {
      const body = ctx.getBody();
      const { type, content, contact } = body;
      const sn_code = body.sn_code;

      if (!type || !content) {
        return ctx.fail('反馈类型和内容不能为空');
      }

      if (!sn_code) {
        return ctx.fail('请提供设备SN码');
      }

      const models = await Framework.getModels();
      const { feedback, pla_account } = models;

      // 根据 sn_code 查找用户
      const user = await pla_account.findOne({
        where: { sn_code, is_delete: 0 }
      });

      if (!user) {
        return ctx.fail('用户不存在');
      }

      // 创建反馈记录
      const feedbackRecord = await feedback.create({
        user_id: user.id,
        sn_code: sn_code,
        type: type,
        content: content,
        contact: contact || '',
        status: 'pending',
        is_delete: 0
      });

      return ctx.success({
        message: '反馈提交成功，感谢您的反馈！',
        feedbackId: feedbackRecord.id
      });
    } catch (error) {
      console.error('提交反馈失败:', error);
      return ctx.fail('提交反馈失败: ' + error.message);
    }
  },

  /**
   * @swagger
   * /api/feedback/list:
   *   post:
   *     summary: 获取反馈列表
   *     description: 根据用户ID获取反馈列表
   *     tags: [前端-意见反馈]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             properties:
   *               page:
   *                 type: integer
   *                 description: 页码
   *               pageSize:
   *                 type: integer
   *                 description: 每页数量
   *     responses:
   *       200:
   *         description: 获取成功
   */
  'POST /feedback/list': async (ctx) => {
    try {
      const body = ctx.getBody();
      const sn_code = body.sn_code;
      const page = parseInt(body.page) || 1;
      const pageSize = parseInt(body.pageSize) || 20;

      if (!sn_code) {
        return ctx.fail('请提供设备SN码');
      }

      const models = await Framework.getModels();
      const { feedback, pla_account } = models;

      // 根据 sn_code 查找用户
      const user = await pla_account.findOne({
        where: { sn_code, is_delete: 0 }
      });

      if (!user) {
        return ctx.fail('用户不存在');
      }

      const offset = (page - 1) * pageSize;

      // 查询反馈列表
      const { count, rows } = await feedback.findAndCountAll({
        where: {
          user_id: user.id,
          is_delete: 0
        },
        limit: pageSize,
        offset: offset,
        order: [['create_time', 'DESC']]
      });

      return ctx.success({
        count: count,
        total: count,
        rows: rows,
        list: rows,
        page: page,
        pageSize: pageSize
      });
    } catch (error) {
      console.error('获取反馈列表失败:', error);
      return ctx.fail('获取反馈列表失败: ' + error.message);
    }
  },

  /**
   * @swagger
   * /api/feedback/detail:
   *   get:
   *     summary: 获取反馈详情
   *     description: 根据反馈ID获取详细信息
   *     tags: [前端-意见反馈]
   *     parameters:
   *       - in: query
   *         name: feedbackId
   *         required: true
   *         schema:
   *           type: string
   *         description: 反馈ID
   *     responses:
   *       200:
   *         description: 获取成功
   */
  'GET /feedback/detail': async (ctx) => {
    try {
      const { feedbackId, id } = ctx.query;
      const recordId = feedbackId || id;

      if (!recordId) {
        return ctx.fail('反馈ID不能为空');
      }

      const models = await Framework.getModels();
      const { feedback } = models;

      // 查询反馈详情
      const record = await feedback.findOne({
        where: {
          id: recordId,
          is_delete: 0
        }
      });

      if (!record) {
        return ctx.fail('反馈记录不存在');
      }

      return ctx.success(record);
    } catch (error) {
      console.error('获取反馈详情失败:', error);
      return ctx.fail('获取反馈详情失败: ' + error.message);
    }
  }
};

