/**
 * 电子围栏坐标点控制器
 * 处理围栏坐标点的CRUD操作
 */

const { ElectronicFencePoint, ElectronicFence } = require('../models');
const { Op } = require('sequelize');

class ElectronicFencePointController {
  /**
   * 获取围栏的所有坐标点
   */
  async getFencePoints(req, res) {
    try {
      const { fenceId } = req.params;
      const { point_type, is_active } = req.query;

      // 构建查询条件
      const where = { fence_id: fenceId };
      if (point_type) where.point_type = point_type;
      if (is_active !== undefined) where.is_active = is_active === 'true';

      const points = await ElectronicFencePoint.findAll({
        where,
        order: [['point_order', 'ASC']]
      });

      res.json({
        success: true,
        data: points.map(point => point.toFrontendFormat()),
        total: points.length,
        message: '获取围栏坐标点成功'
      });

    } catch (error) {
      console.error('获取围栏坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '获取围栏坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 获取单个坐标点详情
   */
  async getPointById(req, res) {
    try {
      const { id } = req.params;

      const point = await ElectronicFencePoint.findByPk(id);
      if (!point) {
        return res.status(404).json({
          success: false,
          message: '坐标点不存在'
        });
      }

      res.json({
        success: true,
        data: point.toFrontendFormat(),
        message: '获取坐标点详情成功'
      });

    } catch (error) {
      console.error('获取坐标点详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取坐标点详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建坐标点
   */
  async createPoint(req, res) {
    try {
      const {
        fence_id,
        point_order,
        longitude,
        latitude,
        point_type = 'corner',
        description
      } = req.body;

      // 验证必填字段
      if (!fence_id || point_order === undefined || !longitude || !latitude) {
        return res.status(400).json({
          success: false,
          message: '围栏ID、顺序、经度、纬度为必填项'
        });
      }

      // 验证围栏是否存在
      const fence = await ElectronicFence.findByPk(fence_id);
      if (!fence) {
        return res.status(404).json({
          success: false,
          message: '围栏不存在'
        });
      }

      // 创建坐标点
      const point = await ElectronicFencePoint.create({
        fence_id,
        point_order,
        longitude,
        latitude,
        point_type,
        description,
        created_by: req.user?.id
      });

      res.status(201).json({
        success: true,
        data: point.toFrontendFormat(),
        message: '坐标点创建成功'
      });

    } catch (error) {
      console.error('创建坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '创建坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 批量创建坐标点
   */
  async createPoints(req, res) {
    try {
      const { fence_id, points } = req.body;

      // 验证必填字段
      if (!fence_id || !Array.isArray(points) || points.length === 0) {
        return res.status(400).json({
          success: false,
          message: '围栏ID和坐标点数组为必填项'
        });
      }

      // 验证围栏是否存在
      const fence = await ElectronicFence.findByPk(fence_id);
      if (!fence) {
        return res.status(404).json({
          success: false,
          message: '围栏不存在'
        });
      }

      // 批量创建坐标点
      const createdPoints = await ElectronicFencePoint.createPoints(fence_id, points, {
        createdBy: req.user?.id,
        created_by: req.user?.id
      });

      res.status(201).json({
        success: true,
        data: createdPoints.map(point => point.toFrontendFormat()),
        total: createdPoints.length,
        message: '坐标点批量创建成功'
      });

    } catch (error) {
      console.error('批量创建坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '批量创建坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 更新坐标点
   */
  async updatePoint(req, res) {
    try {
      const { id } = req.params;
      const updateData = req.body;

      const point = await ElectronicFencePoint.findByPk(id);
      if (!point) {
        return res.status(404).json({
          success: false,
          message: '坐标点不存在'
        });
      }

      // 更新坐标点
      updateData.updated_by = req.user?.id;
      await point.update(updateData);

      res.json({
        success: true,
        data: point.toFrontendFormat(),
        message: '坐标点更新成功'
      });

    } catch (error) {
      console.error('更新坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '更新坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 更新围栏的所有坐标点
   */
  async updateFencePoints(req, res) {
    try {
      const { fenceId } = req.params;
      const { points } = req.body;

      // 验证必填字段
      if (!Array.isArray(points)) {
        return res.status(400).json({
          success: false,
          message: '坐标点数组为必填项'
        });
      }

      // 验证围栏是否存在
      const fence = await ElectronicFence.findByPk(fenceId);
      if (!fence) {
        return res.status(404).json({
          success: false,
          message: '围栏不存在'
        });
      }

      // 更新围栏的所有坐标点
      const updatedPoints = await ElectronicFencePoint.updateFencePoints(fenceId, points, {
        createdBy: req.user?.id
      });

      res.json({
        success: true,
        data: updatedPoints.map(point => point.toFrontendFormat()),
        total: updatedPoints.length,
        message: '围栏坐标点更新成功'
      });

    } catch (error) {
      console.error('更新围栏坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '更新围栏坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 删除坐标点
   */
  async deletePoint(req, res) {
    try {
      const { id } = req.params;

      const point = await ElectronicFencePoint.findByPk(id);
      if (!point) {
        return res.status(404).json({
          success: false,
          message: '坐标点不存在'
        });
      }

      await point.destroy();

      res.json({
        success: true,
        message: '坐标点删除成功'
      });

    } catch (error) {
      console.error('删除坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '删除坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 删除围栏的所有坐标点
   */
  async deleteFencePoints(req, res) {
    try {
      const { fenceId } = req.params;

      const deletedCount = await ElectronicFencePoint.destroy({
        where: { fence_id: fenceId }
      });

      res.json({
        success: true,
        data: { deletedCount },
        message: '围栏坐标点删除成功'
      });

    } catch (error) {
      console.error('删除围栏坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '删除围栏坐标点失败',
        error: error.message
      });
    }
  }

  /**
   * 获取围栏边界框
   */
  async getFenceBounds(req, res) {
    try {
      const { fenceId } = req.params;

      const bounds = await ElectronicFencePoint.getFenceBounds(fenceId);
      if (!bounds) {
        return res.status(404).json({
          success: false,
          message: '围栏没有坐标点'
        });
      }

      res.json({
        success: true,
        data: bounds,
        message: '获取围栏边界框成功'
      });

    } catch (error) {
      console.error('获取围栏边界框失败:', error);
      res.status(500).json({
        success: false,
        message: '获取围栏边界框失败',
        error: error.message
      });
    }
  }

  /**
   * 搜索坐标点
   */
  async searchPoints(req, res) {
    try {
      const {
        fence_id,
        point_type,
        longitude_min,
        longitude_max,
        latitude_min,
        latitude_max,
        description,
        page = 1,
        limit = 10
      } = req.query;

      // 构建查询条件
      const where = {};
      if (fence_id) where.fence_id = fence_id;
      if (point_type) where.point_type = point_type;
      if (description) where.description = { [Op.like]: `%${description}%` };

      // 坐标范围查询
      if (longitude_min !== undefined || longitude_max !== undefined) {
        where.longitude = {};
        if (longitude_min !== undefined) where.longitude[Op.gte] = longitude_min;
        if (longitude_max !== undefined) where.longitude[Op.lte] = longitude_max;
      }

      if (latitude_min !== undefined || latitude_max !== undefined) {
        where.latitude = {};
        if (latitude_min !== undefined) where.latitude[Op.gte] = latitude_min;
        if (latitude_max !== undefined) where.latitude[Op.lte] = latitude_max;
      }

      const offset = (page - 1) * limit;

      const { count, rows } = await ElectronicFencePoint.findAndCountAll({
        where,
        order: [['fence_id', 'ASC'], ['point_order', 'ASC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      res.json({
        success: true,
        data: rows.map(point => point.toFrontendFormat()),
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        message: '搜索坐标点成功'
      });

    } catch (error) {
      console.error('搜索坐标点失败:', error);
      res.status(500).json({
        success: false,
        message: '搜索坐标点失败',
        error: error.message
      });
    }
  }
}

module.exports = new ElectronicFencePointController();
