import express from 'express';
const router = express.Router();

import Games from '../models/GamesPs.js';
import Clients from '../models/Clients.js';

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


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

/**
 * 更新内盘盘口
 */
router.post('/update_base_events', (req, res) => {
  const { games, timestamp, tp } = req.body ?? {};
  Games.updateBaseEvents({ games, timestamp, tp })
  .then(() => {
    res.sendSuccess();
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});


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

/**
 * 获取数据同步客户端列表
 */
router.get('/get_clients', (req, res) => {
  res.sendSuccess(Clients.getClients());
});

/**
 * 更新数据同步客户端信息
 */
router.post('/update_client', (req, res) => {
  Clients.updateClient(req.body)
  .then(client => {
    res.sendSuccess(client);
  })
  .catch(err => {
    if (err.message === 'CLIENT_NOT_FOUND') {
      return res.notFound('客户端不存在');
    }
    res.badRequest(err.message);
  });
});

/**
 * 删除数据同步客户端
 */
router.post('/delete_client', (req, res) => {
  const { key } = req.body ?? {};
  Clients.deleteClient(key)
  .then(() => {
    res.sendSuccess();
  })
  .catch(err => {
    if (err.message === 'CLIENT_NOT_FOUND') {
      return res.notFound('客户端不存在');
    }
    res.badRequest(err.message);
  });
});

/**
 * 更新比赛结果
 */
router.post('/update_games_result', (req, res) => {
  const { date, list } = req.body ?? {};
  Games.updateGamesResult({ date, list })
  .then(() => {
    res.sendSuccess();
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 获取筛选过的联赛
 */
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);
  });
});

/**
 * 更新OB原始数据
 */
router.post('/update_original_data', (req, res) => {
  const { leagues, matches } = req.body ?? {};
  Games.updateOriginalData({ leagues, matches });
  res.sendSuccess();
});

/**
 * 获取OB原始数据
 */
router.get('/get_original_data', (req, res) => {
  const obOriginalData = Games.getOriginalData();
  res.sendSuccess(obOriginalData);
});

/**
 * 获取关联列表
 */
router.get('/get_games_relation', (req, res) => {
  const { mk, ids, le, lp, lo, hb, hh, ho } = req.query;
  const gamesRelation = Games.getGamesRelation({
    ids: ids?.split(',').map(item => +item.trim()).filter(item => !!item) ?? [],
    listEvents: le === 'true',
    listPC: lp === 'true',
    listOdds: lo === 'true',
    hideBase: hb === 'true',
    hideHalf: hh === 'true',
    hideOut: ho === 'true',
    mk: (/^-?\d$/).test(mk) ? +mk : -1
  });
  res.sendSuccess(gamesRelation);
});

/**
 * 获取中单方案
 * 返回中单方案列表
 */
router.get('/get_solutions', (req, res) => {
  const { win_min, with_events, show_lower, mk } = req.query;
  Games.getSolutions({
    win_min: win_min ? +win_min : undefined,
    with_events: with_events === 'true',
    show_lower: show_lower === 'true',
    mk: mk ? +mk : -1
  })
  .then(({ solutions, gamesEvents, mkCount }) => {
    res.sendSuccess({ solutions, gamesEvents, mkCount });
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 获取中单方案
 * 返回按照比赛分组的中单方案列表
 */
router.get('/get_games_solutions', (req, res) => {
  const { win_min, with_events, show_lower, mk, gp, tp, sk } = req.query;
  Games.getGamesSolutions({
    win_min: win_min ? +win_min : undefined,
    with_events: with_events === 'true',
    show_lower: show_lower === 'true',
    mk: mk ? +mk : -1,
    gp: gp ? +gp : -1,
    tp: tp ? +tp : 0,
    sk: sk.trim() ? sk.trim() : undefined,
  })
  .then(gamesSolutions => {
    res.sendSuccess(gamesSolutions);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 通过sid获取单个中单方案
 */
router.get('/get_solution', (req, res) => {
  const { sid } = req.query;
  Games.getSolution(sid)
  .then(solution => {
    res.sendSuccess(solution);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 获取单场比赛赔率历史
 */
router.get('/get_odds_history', (req, res) => {
  const { event_id } = req.query;
  Games.getOddsHistory(event_id)
  .then(history => {
    res.sendSuccess(history ?? null);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 获取赔率历史比赛列表
 */
router.get('/get_odds_history_games', (req, res) => {
  const { page, page_size, status, keyword } = req.query;
  Games.getOddsHistoryGames({ page, pageSize: page_size, status, keyword })
  .then(games => {
    res.sendSuccess(games);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 通过比赛ID获取中单方案
 */
router.post('/solutions_by_ids', (req, res) => {
  const { ids } = req.body ?? {};
  Games.getSolutionsByIds(ids)
  .then(solutions => {
    res.sendSuccess(solutions);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 计算综合利润方案
 */
router.post('/calc_total_profit', (req, res) => {
  const data = req.body;
  let sid1, sid2, inner_base, inner_rebate;
  if (Array.isArray(data)) {
    [sid1, sid2, inner_base, inner_rebate] = data;
  }
  else {
    sid1 = data.sids[0];
    sid2 = data.sids[1];
    inner_base = data.inner_base;
    inner_rebate = data.inner_rebate;
  }
  // const [sid1, sid2, inner_base, inner_rebate] = req.body;
  Games.getTotalProfitWithSid(sid1, sid2, inner_base, inner_rebate)
  .then(totalProfit => {
    res.sendSuccess(totalProfit);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 计算自定义综合利润方案
 */
router.post('/calc_custom_total_profit', (req, res) => {
  // const [bet_info_1, bet_info_2, fixed, inner_base, inner_rebate] = req.body;
  const data = req.body;
  let bet_info_1, bet_info_2, fixed, inner_base, inner_rebate;
  if (Array.isArray(data)) {
    [bet_info_1, bet_info_2, fixed, inner_base, inner_rebate] = data;
  }
  else {
    bet_info_1 = data.bet_info[0];
    bet_info_2 = data.bet_info[1];
    inner_base = data.inner_base;
    inner_rebate = data.inner_rebate;
    fixed = data.fixed;
  }
  Games.getTotalProfitWithBetInfo(bet_info_1, bet_info_2, fixed, inner_base, inner_rebate)
  .then(totalProfit => {
    res.sendSuccess(totalProfit);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 计算补单方案
 */
router.post('/calc_total_replacement', (req, res) => {
  Games.getTotalReplacement(req.body)
  .then(totalProfit => {
    res.sendSuccess(totalProfit);
  })
  .catch(err => {
    res.badRequest(err.message);
  });
});

/**
 * 异常通知
 */
router.post('/notify_exception', (req, res) => {
  const { message } = req.body;
  Games.notifyException(message);
  res.sendSuccess();
});

export default router;
