
'use strict';

const Service = require('egg').Service;
const R = require('ramda');
const _ = require('lodash');

class BackService extends Service {
  // 登录
  async login(input) {
    const { ctx } = this;
    const { account, password } = input;

    const userInfo = await ctx.classModel.CourseBackUser.findOne({ where: { account, is_deleted: 0 } });
    if (ctx.isEmpty(userInfo)) {
      ctx.failed('用户不存在');
    }

    console.log(ctx.helper.md5(password + 'course'));
    if (userInfo.password !== ctx.helper.md5(password + 'course')) {
      ctx.failed('密码错误');
    }

    const authToken = await this.service.jwt.apply({ user_uuid: userInfo.id });
    await this.app.memcache.set('course_back_auth_token_' + userInfo.id, authToken, 3600);

    return { auth_token: authToken };
  }

  // 获取菜单
  async getMenuList() {
    const { ctx } = this;
    const userUuid = ctx.userUuid;

    const userInfo = await ctx.classModel.CourseBackUser.findOne({ where: { id: userUuid, is_deleted: 0 } });
    if (ctx.isEmpty(userInfo)) {
      ctx.failed('无效用户');
    }

    let menuList = [];
    if (userInfo.is_admin > 0) {
      menuList = await ctx.classModel.CourseBackMenu.findAll({ where: { is_deleted: 0 }, attributes: [ 'id', 'title', 'path', 'icon', 'parent_id' ], raw: true });
    } else {
      const userToMenuList = await ctx.classModel.CourseBackUserToMenu.findAll({ where: { user_uuid: userUuid, is_deleted: 0 } });
      menuList = await ctx.classModel.CourseBackMenu.findAll({ where: { id: { $in: R.pluck('menu_id', userToMenuList) }, is_deleted: 0 }, attributes: [ 'id', 'title', 'path', 'icon', 'parent_id' ], raw: true });
    }

    for (const i in menuList) {
      menuList[i].subs = [];
    }
    const menu = _.groupBy(menuList, 'id');

    for (const v of menuList) {
      if (v.parent_id > 0 && !ctx.isEmpty(menu[v.parent_id])) {
        menu[v.parent_id][0].subs.push(v);
      }
    }

    const results = [];
    for (const i in menu) {
      if (menu[i][0].parent_id === 0) {
        results.push(menu[i][0]);
      }
    }

    return { list: results };
  }
}

module.exports = BackService;
