const News = require('../module/News');
const Router = require('koa-router');
const permission = require('../intercept/permission');
const router = new Router();


async function getNews(id) {
  let news = new News();
  news.id = id;

  let [result = {}] = await news.query()

  return result
}

/**
 * 获取新闻数据
 */
router.get('/', async ctx => {
  let { page = 1, keyword = '', limit = 15, language } = ctx.request.query;
  let news = new News();

  news.hide = 0;
  let result = await news.paging(page, Number(limit), keyword, language)

  ctx.body = {
    msg: '成功获取数据',
    content: result
  }
});

/**
 * 获取数据具体数据
 */
router.get('/:id', async ctx => {
  let language = Number(ctx.query.language)
  let id = ctx.params.id;

  (!id || !Number.isFinite(Number(id))) &&
    ctx.error('该新闻不存在，请刷新后重试！');

  let result = await getNews(id)

  if (language && result.language !== language && result.redire) {
    let reResult = null
    let reId = language === 1 ? result.chinese_id :
      language === 2 ? result.english_id : null

    reId && (reResult = await getNews(reId))
    reResult && (result = reResult)
  }

  ctx.body = {
    msg: '成功获取!',
    content: result
  };
});


/**
 * 添加新闻
 */
router.post('/', permission, async ctx => {
  let body = ctx.request.body;
  let news = new News();

  news.title = body.title;
  news.content = body.content;
  news.cover = body.cover;
  news.label = body.label;
  news.redire = body.redire;
  news.date = body.date;
  news.sort = Number(body.sort) || 0;
  news.address = body.address;
  news.origin = body.origin;
  news.language = body.language;
  news.chinese_id = Number(body.chinese_id) || 0;
  news.english_id = Number(body.english_id) || 0;
  news.user_id = ctx.session.user.id

  let { insertId } = await news.insert()

  ctx.body = {
    msg: '成功添加!',
    insertId
  };
});


/**
 * 修改新闻
 */
router.put('/', permission, async ctx => {
  let body = ctx.request.body;
  let news = new News();
  news.id = body.id;

  if (!await news.exists()) {
    ctx.error('该新闻不存在!')
  }
  console.log('----------', body.origin, '--------------')

  news.title = body.title;
  news.content = body.content;
  news.cover = body.cover;
  news.label = body.label;
  news.date = body.date;
  news.redire = body.redire;
  news.origin = body.origin;
  news.language = body.language;
  news.chinese_id = Number(body.chinese_id) || 0;
  news.english_id = Number(body.english_id) || 0;
  news.sort = Number(body.sort) || 0;
  news.address = body.address;

  await news.update()

  ctx.body = {
    msg: '成功修改!'
  };
});

/**
 * 删除文章
 */
router.delete('/:id', permission, async ctx => {
  let id = ctx.params.id;

  (!id || !Number.isFinite(Number(id))) &&
    ctx.error('该新闻不存在，请刷新后重试！');

  let news = new News();
  news.id = id;
  news.hide = 0;

  (await news.exists()) ||
    ctx.error('该新闻不存在，请刷新后重试！');

  news.hide = 1;
  await news.update();

  ctx.body = { msg: '成功删除！' };
});

module.exports = exports = { path: '/news', router };