/**
 * 牛只档案路由 - 基于iot_cattle表
 */
const express = require('express');
const multer = require('multer');
const router = express.Router();
const iotCattleController = require('../controllers/iotCattleController');
const { verifyToken, checkRole } = require('../middleware/auth');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/') // 上传文件保存目录
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + '.' + file.originalname.split('.').pop());
  }
});

const upload = multer({ 
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许Excel文件
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel'
    ];
    
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传Excel文件(.xlsx或.xls格式)'), false);
    }
  }
});

// 公开API路由，不需要验证token
const publicRoutes = express.Router();
router.use('/public', publicRoutes);

// 公开获取牛只档案列表
publicRoutes.get('/', iotCattleController.getCattleArchives);

// 公开获取单个牛只档案详情
publicRoutes.get('/:id', iotCattleController.getCattleArchiveById);

// 公开下载导入模板
publicRoutes.get('/import/template', iotCattleController.downloadImportTemplate);

// 公开获取栏舍列表
publicRoutes.get('/pens/list', iotCattleController.getPens);

// 公开获取批次列表
publicRoutes.get('/batches/list', iotCattleController.getBatches);

// 获取牛只档案列表
router.get('/', verifyToken, iotCattleController.getCattleArchives);

// 获取单个牛只档案详情
router.get('/:id', verifyToken, iotCattleController.getCattleArchiveById);

// 创建牛只档案
router.post('/', verifyToken, checkRole(['admin', 'manager']), iotCattleController.createCattleArchive);

// 更新牛只档案
router.put('/:id', verifyToken, checkRole(['admin', 'manager']), iotCattleController.updateCattleArchive);

// 删除牛只档案
router.delete('/:id', verifyToken, checkRole(['admin', 'manager']), iotCattleController.deleteCattleArchive);

// 批量删除牛只档案
router.delete('/', verifyToken, checkRole(['admin', 'manager']), iotCattleController.batchDeleteCattleArchives);

// 获取农场列表
router.get('/farms/list', verifyToken, iotCattleController.getFarms);

// 获取栏舍列表
router.get('/pens/list', verifyToken, iotCattleController.getPens);

// 获取批次列表
router.get('/batches/list', verifyToken, iotCattleController.getBatches);

// 导入牛只档案数据
router.post('/import', verifyToken, checkRole(['admin', 'manager']), upload.single('file'), iotCattleController.importCattleArchives);

// 下载导入模板
router.get('/import/template', verifyToken, iotCattleController.downloadImportTemplate);

module.exports = router;
