const express = require('express');
const router = express.Router();

const authMiddleware = require('../middleware/authMiddleware');

const Games = require('../models/Games');

// 更新比赛列表
router.post('/update_games_list', (req, res) => {
  const { platform, mk, games } = req.body ?? {};
  Games.updateGamesList({ platform, mk, games })
  .then(updateCount => {
    res.sendSuccess({ updateCount });
  })
  .catch(err => {
    res.badRequest(err.message);
  })
});

// 更新比赛盘口
router.post('/update_games_events', (req, res) => {
  const { platform, mk, games, outrights } = req.body ?? {};
  Games.updateGamesEvents({ platform, mk, games, outrights })
  .then(updateCount => {
    res.sendSuccess({ updateCount });
  })
  .catch(err => {
    res.badRequest(err.message);
  })
});

// 更新联赛列表
router.post('/update_leagues_list', (req, res) => {
  const { mk, leagues } = req.body ?? {};
  const updateCount = Games.updateLeaguesList({ mk, leagues });
  res.sendSuccess({ updateCount });
});

// 获取筛选过的联赛
router.get('/get_filtered_leagues', (req, res) => {
  const { mk } = req.query;
  Games.getFilteredLeagues(mk)
  .then(filteredLeagues => {
    res.sendSuccess(filteredLeagues);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

// 保存关联比赛
router.post('/update_games_relation', authMiddleware, (req, res) => {
  const relation = req.body;
  Games.updateGamesRelation(relation)
  .then(ret => {
    res.sendSuccess(ret);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

// 删除关联比赛
router.post('/remove_games_relation', authMiddleware, (req, res) => {
  const { id } = req.body;
  Games.removeGamesRelation(id)
  .then(ret => {
    res.sendSuccess(ret);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

// 获取比赛列表
router.get('/get_games_list', (req, res) => {
  const gamesList = Games.getGamesList();
  res.sendSuccess(gamesList);
});

// 获取关联列表
router.get('/get_games_relation', (req, res) => {
  const gamesRelation = Games.getGamesRelation();
  res.sendSuccess(gamesRelation);
});

// 获取比赛盘口
router.get('/get_games_events', authMiddleware, (req, res) => {
  const { platform } = req.query;
  const gamesEvents = Games.getGamesEvents({ platform });
  res.sendSuccess(gamesEvents);
});

// 获取中单方案
router.get('/get_solutions', authMiddleware, (req, res) => {
  Games.getSolutions().then(solutions => {
    res.sendSuccess(solutions);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

// 计算总利润
router.post('/calc_total_profit', authMiddleware, (req, res) => {
  const { sid1, sid2, gold_side_inner } = req.body;
  const totalProfit = Games.getTotalProfit(sid1, sid2, gold_side_inner);
  res.sendSuccess(totalProfit);
});

module.exports = router;