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 md5 = require("MD5");
const uuidv4 = require('uuid/v4');

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

    this.redisClient = system.getObject("util.redisClient");
    this.captchaSve = system.getObject("service.common.captchaSve");
    this.platformUtils = system.getObject("util.businessManager.opPlatformUtils");
  }

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

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

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

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

    try {
      var vrs = await this.captchaSve.valid({
        key: captchaKey,
        code: captchaCode,
      });
      if (vrs.status !== 0) {
        return vrs;
      }
      // 查用户
      var loginrs = await this.platformUtils.login(loginName, password);
      if(loginrs.status !== 0) {
        return loginrs;
      }
      var user = await this.service.authByCode(loginrs.data.opencode);
      req.session.user = user;

      var xggadminsid = await this.setLogin(user);

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

  async setLogin(user) {
    var xggadminsid = uuidv4();
    await this.redisClient.setWithEx(xggadminsid, JSON.stringify(user), 60 * 60);
    return xggadminsid;
  }

  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": "/merchants/addressInformation"
            },
            {
              "name": "抬头信息",
              "path": "/merchants/lookUpInformation"
            }
          ]
        }]
      },
      {
        "name": "业务中心",
        "path": "/trading",
        "submenu": [{
            "name": "订单管理",
            "team": [{
              "name": "订单信息",
              "path": "/trading/orderInformation"
            }]
          },
          {
            "name": "个体户管理",
            "team": [{
                "name": "用户信息",
                "path": "/trading/userInformation"
              },
              {
                "name": "用户签约",
                "path": "/trading/usersSignUp"
              }
            ]
          },
          {
            "name": "发票管理",
            "team": [{
                "name": "发票申请",
                "path": "/trading/invoiceApplyFor"
              },
              {
                "name": "发票管理",
                "path": "/trading/invoiceManagement"
              }
            ]
          }
        ]
      },
      {
        "name": "财务中心",
        "path": "/financial",
        "submenu": [{
          "name": "资金管理",
          "team": [{
              "name": "资金账户",
              "path": "/financial/capitalAccount"
            },
            {
              "name": "充值申请",
              "path": "/financial/topUpApplication"
            },
            {
              "name": "资金交易",
              "path": "/financial/cashTransactions"
            },
            {
              "name": "资金流水",
              "path": "/financial/capitalFlows"
            }
          ]
        }]
      },
      {
        "name": "数据中心",
        "path": "/information",
        "submenu": [{
          "name": "暂无",
          "team": [{
            "name": "暂无",
            "path": ""
          }]
        }]
      },
      {
        "name": "系统中心",
        "path": "/system",
        "submenu": [{
          "name": "信息维护",
          "team": [{
              "name": "注册地信息",
              "path": "/system/registered"
            },
            {
              "name": "经营范围信息",
              "path": "/system/businessScope"
            },
            {
              "name": "交付商信息",
              "path": "/system/delivery"
            },
            {
              "name": "发票内容信息",
              "path": "/system/invoiceContent"
            }
          ]
        }]
      }
    ]
    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) {
      return system.getResultSuccess(req.session.user);
    } else {
      req.session.user = null;
      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;