'use strict';
const Hex = require('crypto-js/enc-hex');
const MD5 = require('crypto-js/md5');
const moment = require('moment');
const uuid = require('uuid');

async function login (ctx, next) {
   // const transaction = await ctx.fs.dc.orm.transaction();
   try {
      const models = ctx.fs.dc.models;
      const params = ctx.request.body;

      const emisLoginRes = await ctx.app.fs.emisRequest.post('login', {
         data: params
      })

      if (!emisLoginRes) {
         throw "无此用户,请使用正确的登录信息"
      } else {
         const pomsRegisterRes = await models.User.findOne({
            where: {
               pepUserId: emisLoginRes.id,
               $or: {
                  deleted: false,
                  role: { $contains: ['admin'] }
               }
            }
         })
         if (!pomsRegisterRes) {
            throw '你还不是飞尚运维中台成员,请联系管理员添加权限'
         } else if (
            pomsRegisterRes.disabled && !pomsRegisterRes.role.includes('admin')
         ) {
            throw '当前账号已禁用'
         }
         emisLoginRes.authorized = true
         emisLoginRes.expired = moment().add(1, 'day')
         emisLoginRes.pomsUserInfo = pomsRegisterRes.dataValues

         let userUpdateData = {
            lastInTime: moment().format(),
            inTimes: pomsRegisterRes.inTimes + 1,
            lastInAddress: ''
         }
         try {
            // 获取ip转为地点并记录
            let ip =
               // '117.90.39.49' ||
               ctx.ip
            console.log(`当前登录用户IP:${ip}`);
            if (ip && /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/.test(ip)) {
               const ipLocationRes = await ctx.app.fs.godRequest.post('ip', {
                  query: {
                     ip,
                  }
               })
               if (ipLocationRes) {
                  userUpdateData.lastInAddress = ipLocationRes.province + ipLocationRes.city
               }
            }
         } catch (error) {
            ctx.fs.logger.error(`IP GET, error: ${error}`);
         }

         await models.User.update(userUpdateData, {
            where: {
               id: emisLoginRes.id
            }
         })

         await ctx.redis.hmset(emisLoginRes.token, {
            expired: moment().add(1, 'day'),
            userInfo:JSON.stringify(emisLoginRes)
         });

         ctx.status = 200;
         ctx.body = emisLoginRes;
      }
      // await transaction.commit();
   } catch (error) {
      // await transaction.rollback();
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
      ctx.status = 400;
      let message = typeof error == 'string' ? error
         : error.response.body.message || "登录失败"
      if (message == '账号或密码错误') {
         message = '无此用户,请使用正确的登录信息'
      }

      ctx.body = {
         message: message
      }
   }
}

async function logout (ctx) {
   try {
      const models = ctx.fs.dc.models;
      const params = ctx.request.body;

      await ctx.app.fs.emisRequest.put('logout', {
         data: params
      })
      await ctx.redisTools.hdelall(token);

      ctx.status = 204;
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
      ctx.status = 400;
      ctx.body = {

      }
   }
}

module.exports = {
   login,
   logout,
};