var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');

var cacheBaseComp = null;
class UserCtl extends CtlBase {
  constructor() {
    super("auth", CtlBase.getServiceName(UserCtl));

    this.captchaPrev = "xgg_captcha_";


    this.redisClient = system.getObject("util.redisClient");
  }

  async captcha(qobj, pobj, req) {
    var uuid = uuidv4();
    var key = uuid.replace(/\-/g, "");

    var options = {
      size: 4,
      noise: 1,
      ignoreChars: '0o1i'
    };
    options.width = this.trim(qobj.width) || 120;
    options.height = this.trim(qobj.height) || 32;
    options.background = this.trim(qobj.background) || "#E8E8E8";

    try {
      var redisKey = this.captchaPrev + key;
      var cap = svgCaptcha.create(options);
      console.log(cap);
      await this.redisClient.setWithEx(redisKey, cap.text, 3 * 60);
      return system.getResultSuccess({
        key: key,
        captcha: cap.data,
      });
    } catch (error) {
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async smsCode(qobj, pobj, req) {
    var mobile = this.trim(qobj.mobile);
    // var captchaKey = this.trim(qobj.captchaKey);
    // var captchaCode = this.trim(qobj.captchaCode);

    try {
      if (!/^1[23456789]\d{9}$/.test(mobile)) {
        return system.getResult(null, "手机号码格式不正确");
      }

      // var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";

      // if (!code) {
      //   return system.getResult(null, "图片验证码过期，请刷新重试");
      // }
      // if (code.toLowerCase() != captchaCode.toLowerCase()) {
      //   await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
      //   return system.getResult(null, "图片验证码不一致，请刷新重试");
      // }

      // TODO 发送短信验证码
      return system.getResultSuccess("发送成功");
    } catch (error) {
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async login(qobj, pobj, req, res) {
    var loginName = this.trim(pobj.loginName);
    var password = this.trim(pobj.password);
    var captchaKey = this.trim(qobj.captchaKey);
    var captchaCode = this.trim(qobj.captchaCode);

    try {

      // var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";

      // if (!code) {
      //   return system.getResult(null, "图片验证码过期，请点击重试");
      // }
      // if (code.toLowerCase() != captchaCode.toLowerCase()) {
      //   await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
      //   return system.getResult(null, "图片验证码不一致，请点击重试");
      // }

      var adminUser = await this.service.findById(1);

      adminUser.lastLoginTime = new Date();
      await adminUser.save();

      var xggadminsid = uuidv4();
      xggadminsid = "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
      await this.redisClient.setWithEx(xggadminsid, JSON.stringify(adminUser), 60 * 60 * 2);

      // 处理登录逻辑
      var result = {
        xggadminsid: xggadminsid,
      }
      return system.getResultSuccess(result);

    } catch (error) {
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }


  async forgetPassword(qobj, pobj, req, res) {
    var mobile = this.trim(pobj.mobile);
    var vcode = this.trim(pobj.vcode);
    var password = this.trim(qobj.password);

    try {

    } catch (error) {
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async currentUser(qobj, pobj, req) {
    return system.getResultSuccess(req.loginUser);
  }

  async getMenu(qobj, pobj, req) {
    var menu = [
      {"name": "首页", "path": "/", "submenu": [] },
      {
          "name": "商户中心",
          "path": "/merchants",
          "submenu": [{"name": "客户管理", "team": [{"name": "商户信息", "path": "/merchants/businessInformation"}, {"name": "签约信息", "path": "/merchants/contractInformation"} ] } ]
      }, {
          "name": "交易中心",
          "path": "/trading",
          "submenu": [{"name": "资金管理", "team": [{"name": "资金账户", "path": "/trading/capitalAccount"}, {"name": "充值申请", "path": "/trading/topUpApplication"}, {"name": "资金交易", "path": "/trading/cashTransactions"}, {"name": "资金流水", "path": "/trading/capitalFlows"} ] }, {"name": "订单管理", "team": [{"name": "订单信息", "path": "/trading/orderInformation"} ] }, {"name": "用户管理", "team": [{"name": "用户信息", "path": "/trading/userInformation"}, {"name": "用户签约", "path": "/trading/usersSignUp"} ] } ]
      }, {
          "name": "财务中心",
          "path": "/financial",
          "submenu": [{"name": "发票管理", "team": [{"name": "发票申请", "path": "/financial/invoiceApplyFor"}, {"name": "发票管理", "path": "/financial/invoiceManagement"} ] } ]
      }, {
          "name": "数据中心",
          "path": "/information",
          "submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] } ]
      }, {
          "name": "系统中心",
          "path": "/system",
          "submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] }
          ]
      }
    ]
    return system.getResultSuccess(menu);
  }


  /**
   * 开放平台回调处理
   * @param {*} req 
   */
  async authByCode(req) {
    var opencode = req.query.code;
    var user = await this.service.authByCode(opencode);
    if (user) {
      req.session.user = user;
    } else {
      req.session.user = null;
    }
    //缓存opencode,方便本应用跳转到其它应用
    //  /auth?code=xxxxx,缓存没有意义，如果需要跳转到其它应用，需要调用
    //平台开放的登录方法，返回 <待跳转的目标地址>/auth?code=xxxxx
    //this.cacheManager["OpenCodeCache"].cacheOpenCode(user.id,opencode);
    return user;
  }

  async navSysSetting(pobj, qobj, req) {
    //开始远程登录，返回code
    var jumpobj = await this.service.navSysSetting(req.session.user);
    if (jumpobj) {
      return system.getResultSuccess(jumpobj);
    }
    return system.getResultFail();
  }

  async loginUser(qobj, pobj, req) {
    return super.findById(req.session.user.id);
  }
  async initNewInstance(queryobj, req) {
    var rtn = {};
    rtn.roles = [];
    if (rtn) {
      return system.getResultSuccess(rtn);
    }
    return system.getResultFail();
  }

  async checkLogin(gobj, qobj, req) {
    //当前如果缓存中存在user,还是要检查当前user所在的域名，如果不和来访一致，则退出重新登录
    if (req.session.user) {
      var x = null;
      if (req.session.user.Roles) {
        x = req.session.user.Roles.map(r => {
          return r.code
        });
      }
      var tmp = {
        id: req.session.user.id,
        userName: req.session.user.userName,
        nickName: req.session.user.nickName,
        mobile: req.session.user.mobile,
        isAdmin: req.session.user.isAdmin,
        created_at: req.session.user.created_at,
        email: req.session.user.email,
        headUrl: req.session.user.headUrl,
        roles: x ? x.join(",") : ""
      }
      return system.getResult(tmp, "用户登录", req);
    } else {
      req.session.user = null;
      //req.session.destroy();
      return system.getResult(null, "用户未登录", req);
    }
  }
  async exit(pobj, qobj, req) {
    req.session.user = null;
    req.session.destroy();
    return system.getResultSuccess({
      "env": settings.env
    });
  }
}
module.exports = UserCtl;