'use strict';

const Service = require('egg').Service;
const assert = require('assert');
const crypto = require('crypto');
const menu = require('../public/adminMenu');
class UserService extends Service {
  async login({ acct, password }) {
    assert(acct, '帐号不存在');
    assert(password, '密码不存在');
    const { AdminUser: model } = this.ctx.model;
    const hash = crypto.createHmac('sha256', this.app.config.userSecret);
    const pwd = hash.update(password).digest('hex');
    try {
      const res = await model.find({ acct });
      if (res.length <= 0) {
        return { errmsg: '用户不存在', errcode: -2003 };
      }
      const userInfo = res[0];
      if (userInfo.state !== '0') {
        return { errmsg: '用户状态异常', errcode: -2003 };
      }
      if (userInfo.password !== pwd) {
        return { errmsg: '密码错误', errcode: -2003 };
      }
      const token = this.app.jwt.sign({ acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id }, this.app.config.jwt.secret);
      return { errmsg: '', errcode: 0, token, userInfo: { acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id } };
    } catch (error) {
      console.log(error);
      throw new Error({ errcode: -2001, errmsg: '登录失败' });
    }
  }
  async getUserMenu() {
    const { AdminUser: model } = this.ctx.model;
    const { Role: rolemodel } = this.ctx.model;
    try {
      const str = this.ctx.request.header.authorization;
      const token = str.substring(7);
      const decode = this.ctx.app.jwt.verify(token, this.app.config.jwt.secret);
      const menulist = [];
      const res = await model.find({ acct: decode.acct });
      if (res.length > 0) {
        const userRoleList = res[0].roleList;
        if (userRoleList && userRoleList.length > 0) {
          for (let e = 0; e < userRoleList.length; e++) {
            const role = await rolemodel.find({ code: userRoleList[e], state: '0' });
            if (role.length > 0) {
              const adminMenuList = role[0].adminMenuList;
              for (let i = 0; i < adminMenuList.length; i++) {
                const item = menu.filter(j => adminMenuList[i] === j.id)[0];
                if (!menulist.includes(item)) {
                  menulist.push(item);
                }
              }
            }
          }
        }
      }

      return { errcode: 0, errmsg: '', data: menulist };
    } catch (error) {
      throw new Error({ errcode: -2001, errmsg: '登录失败' });
    }
  }
}

module.exports = UserService;