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.oplogCtl");

var cacheBaseComp = null;
class UserCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(UserCtl));
    //this.loginS=system.getObject("service.userSve");
    this.restS = system.getObject("util.restClient");
    this.smsS = system.getObject("util.smsClient");
    this.companyS = system.getObject("service.companySve");
    this.footerinfoSve = system.getObject("service.footerinfoSve");
    this.moneyaccountS = system.getObject("service.moneyaccountSve");
    this.sitethemeSve = system.getObject("service.sitethemeSve");
    this.metaCtl = system.getObject("web.metaCtl");
    this.loopCtl = system.getObject("web.loopplayCtl");
    this.serviceitemCtl = system.getObject("web.serviceitemCtl");
  }
  async preReadyData(req){
    var x=await this.preFetchComanyAndFooterAndBankaccount(req);
    var m=await this.metaCtl.getRouteConfigWithoutProduct2(null,req);
    var ps=await this.serviceitemCtl.getAllProducts2(null,{"webjs":"speed"},req);
    var rs=await this.metaCtl.getRsConfig2(null,req);
    var tname=req.query.paramtheme?req.query.paramtheme:x.company.siteTheme;
    var lps=await this.loopCtl.findAll2(req.hostname,tname);
    var rtn= {"loopplays":escape(JSON.stringify(lps)),"rsconfig":escape(JSON.stringify(rs)),"productLst":escape(JSON.stringify(ps)),"routePath":escape(JSON.stringify(m)),"basecom":this.getBaseComp(),"companyinfo":encodeURIComponent(JSON.stringify(x)),"company":x.company,"footerinfo":x.footerinfo};
   return rtn;
  }
  async initNewInstance(queryobj, req) {
    var rtn = {};
    rtn.roles = [];
    return system.getResult2(rtn, null);
  }
  async resetUserInfo(qobj, obj, req) {
    var params = {
      id: req.session.user.id,
      userName: obj.userName,
      nickName: obj.nickName,
      email: obj.email,
      mobile: obj.mobile,
    };
    if (obj.password) {
      obj.password = super.encryptPasswd(obj.password);
      params.password = obj.password;
    };
    console.log("-------------obj------------");
    console.log(obj);
    var result = await this.service.update(params);
    return system.getResult2(result);
  }
  async loginUser(qobj, pobj, req) {
    return super.findById(req.session.user.id);
  }
  //获取验证码，发送给指定手机
  async fetchVcode(qobj, pobj, req) {
    var mobile = pobj.mobile;
    //生成一个验证码，发送
    var vcode = await this.service.getUidStr(6, 10);
    await this.smsS.sendMsg(mobile, vcode);
    return system.getResult2({ vcodestr: vcode });
  }
  async preFetchComany(gobj, qobj, req) {
    //获取当前域名
    var rtn = await this.cacheManager["CompanyCache"].cacheCompany(req.hostname);
    return system.getResult2(rtn, req);
  }

  getBaseComp() {
    if (cacheBaseComp) {
      return cacheBaseComp;
    }
    var glob = require("glob");
    var vuePath = settings.basepath + "/app/front/vues/base";
    var baseComps = [];
    var rs = glob.sync(vuePath + "/**/*.vue");
    if (rs) {
      rs.forEach(function (r) {
        var comp = "";
        if (settings.env == "dev") {
          delete require.cache[r];
          comp = require(r).replace(/\n/g, "");
        } else {
          comp = require(r).replace(/\n/g, "");
        }
        baseComps.push(comp);
      });
    }
    cacheBaseComp = escape(JSON.stringify(baseComps));
    return cacheBaseComp;
  }

  async preFetchComanyAndFooterAndBankaccount(req) {
    //获取当前域名
    var rtn = await this.cacheManager["CompanyCache"].cacheCompany(req.hostname);
    return rtn;
  }

  async checkLogin(gobj, qobj, req) {
    //获取当前域名
    var hostname = req.hostname;
    //按照hostname去查找公司站点信息
    var companytmp = await this.cacheManager["CompanyCache"].cacheCompany(req.hostname);
    var isJump = 0;//表示是否是没有审核通过，而返回默认平台公司站点

    if (!companytmp) {
      //查询公司对公账户
      isJump = 1;
    } else {
      isJump = 0;
    }
    //判断是否是切换状态进来的，如果是切换状态进入，那么
    //需要判断是否是平台域名，如果是查询条件需要去掉isAdmin
    if (qobj && qobj.isswitch == 1) {
      if (companytmp.id != 1) {
        var useradmin = await this.service.getComanyAdminUser(companytmp.id);
        req.session.user = useradmin;
      } else {
        var userid = qobj.userid;
        var usercommon = await this.service.getComanyUserById(userid, companytmp.id);
        req.session.user = usercommon;
      }
    }

    //当前如果缓存中存在user,还是要检查当前user所在的域名，如果不和来访一致，则退出重新登录
    if (req.session.user && isJump == 0 && req.session.user.company && req.session.user.company.domainname == hostname) {
      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,
        // company: companytmp,
        // footerinfo: footerinfo,
        isJump: isJump,
        // bankAccount: bankAccount,
        roles: x ? x.join(",") : ""
      }
      return system.getResult2(tmp, req);
    } else {
      var x = {
        status: -99,
        msg: "no login",
        // company: companytmp,
        // footerinfo: footerinfo,
        isJump: isJump,
      };
      req.session.user = null;
      req.session.destroy();
      return system.getResult2(x, req);
    }
  }
  async exit(qobj, req) {
    req.session.user = null;
    req.session.destroy();
    return system.getResult2({ "env": settings.env });
  }
  async register(qobj, pobj, req) {
    console.log(pobj.u);

    var user = await this.service.findOne({ userName: pobj.u.userName });
    if (user) {
      return system.getErrResult2("用户已存在, 请修改并重试");
    }
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    const cid = req.companyid;
    pobj.u.company_id = cid;
    var u = await this.service.register(pobj.u);
    //req.session.user=u;
    return system.getResult2(u);
  }
  async loginByMobile(pobj, obj, req) {
    const cid = req.companyid;
    obj.u.cid = cid;
    var existedUser = await this.service.getUserByMobile(obj.u);
    if (existedUser != null) {
      req.session.user = existedUser;
      return system.getResult2(existedUser);
    } else {
      var params = {
        mobile: obj.u.mobile,
        userName: obj.u.mobile,
        nickName: obj.u.mobile,
        company_id: obj.u.cid
      };
      var result = await this.service.create(params);
      req.session.user = result;
      return system.getResult2(result);
    }
  }

  //切换渠道登录
  async switchLogin(queryobj, qobj, req) {
    var tocompanyid = qobj.companyid;
    //按照companyid,查询出管理员信息，并作出登录操作
    var useradmin = await this.service.findOne({ isAdmin: true, company_id: tocompanyid });
    req.session.user = useradmin;
    return system.getResult2({});
  }

  async switchUser(queryobj, qobj, req) {
    var tocompanyid = qobj.companyid;
    //按照companyid,查询出管理员信息，并作出登录操作

    var company = await this.companyS.findById(tocompanyid);
    return system.getResult2({ "domainname": company.domainname, "env": settings.env });
  }
  //管理员新增用户，设置默认密码
  async create(queryobj, qobj, req) {
    //  if(qobj.password && qobj.password!=""){
    //   qobj.password = super.encryptPasswd(qobj.password);
    //  }
    qobj.password = super.encryptPasswd("123");
    return super.create(queryobj, qobj, req);
  }
  //管理员修改用户信息，设置默认密码
  async update(queryobj, qobj, req) {
    // qobj.password = super.encryptPasswd("123");
    return super.update(queryobj, qobj, req);
  }
  async login(qobj, pobj, req) {
    //state为p_app表中appkey
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    //获取当前公司id
    const cid = req.companyid;
    pobj.u.cid = cid;
    var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
    if (existedUser != null) {
      req.session.user = existedUser;
    }
    return system.getResult2(existedUser);
  }
  async getUserByMobile(pobj, obj, req) {
    console.log(req);
    console.log("--------------------");
    console.log(req.companyid);
    var params = { mobile: obj.mobile, cid: req.companyid };
    var existedUser = await this.service.getUserByMobile(params);
    if (existedUser) {
      return { code: 0, msg: "用户存在" }
    } else {
      return { code: -1, msg: "用户尚未注册" }
    }
  }
  async resetPassword(pobj, obj, req) {
    const cid = req.companyid;
    obj.cid = cid;
    var existedUser = await this.service.getUserByMobile(obj);
    if (existedUser != null) {
      obj.password = super.encryptPasswd(obj.password);
      var params = {
        id: existedUser.id,
        mobile: obj.mobile,
        password: obj.password
      };
      var result = await this.service.update(params);
      return { status: 0, msg: "密码重置成功" }
    }
  }
  async submitregister(pobj, obj, req) {
    if (req.companyid && req.companyid != "") {
      var user = await this.service.findOne({ mobile: obj.mobile, company_id: req.companyid });
      if (user != null) {
        return { status: 1, msg: "用户已存在, 请修改并重试" };
      } else {
        obj.password = super.encryptPasswd(obj.password);
        var params = {
          userName: obj.mobile,
          nickName: obj.mobile,
          mobile: obj.mobile,
          password: obj.password,
          company_id: req.companyid
        };
        var result = await this.service.create(params);
        return system.getResult2(result);
      }
    } else {
      return system.getResult2(null);
    }
  }
  async getUserInfo(accessToken, openId) {
    let reqUrl = 'https://api.weixin.qq.com/sns/userinfo';
    let params = {
      access_token: accessToken,
      openid: openId,
      lang: 'zh_CN'
    };

    var data = querystring.stringify(params);
    var rtn = await this.restS.execGet(data, reqUrl);
    return JSON.parse(rtn.stdout);
  }
  async getToken(code, req, state) {
    if (settings.env == "prod") {
      let reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
      console.log(state);
      var appobj = await this.cacheManager["AppCache"].cacheApp(state);
      console.log(appobj);
      let params = {
        appid: appobj.appid,
        secret: appobj.secret,
        code: code,
        grant_type: 'authorization_code'
      };
      var data = querystring.stringify(params);
      var rtn = await this.restS.execGet(data, reqUrl);
      return JSON.parse(rtn.stdout);
    } else {
      var rtn = {
        "access_token": "ACCESS_TOKEN",
        "expires_in": 7200,
        "refresh_token": "REFRESH_TOKEN",
        "openid": "xxyy",
        "scope": "SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
      }
      return rtn;
    }
  }
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  //修改用户昵称
  async putNickName(gobj, pobj, req) {
    var result = {
      code: 1,
      msg: "ok",
      data:{ }
    };
    try {
      var user = req.session.user;
      if (!user) {
        result.code = -100;
        result.msg = "用户未登录";
        return result;
      }
      await this.service.updateByWhere({
          nickName: pobj.nick_name }, {
          where:{ id: user.id }
        });
      req.session.user.nickName = pobj.nick_name;
      result.data = req.session.user
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "修改用户昵称错误---error",
        op: "/igirl-web/app/base/controller/impl/userCtl.js/putNickName",
        content: e.stack,
        clientIp: req.clientIp
      });
    }
  }
  //修改用户基本信息 --- h5
  //nickName 昵称, headUrl 头像, sex 性别, email 邮箱.
  async editUserBaseInfo(pobj,obj,req){
    var user = {id:176};//req.session.user;
    if(user){
      obj["user"]=user;
      try {
        var result = await this.service.editUserBaseInfo(obj);
        return result;
      } catch (e) {
        //日志记录
        logCtl.error({
          optitle: "修改用户基本信息错误---error",
          op: "/igirl-web/app/base/controller/impl/userCtl.js/editUserBaseInfo",
          content: e.stack,
          clientIp: ""
        });
        return {code:-200,msg:"操作失败"};
      }
    }else{
      return {code:-100,msg:"用户未登录"};
    }
  }

}
module.exports = UserCtl;
// var task = new UserCtl();
// var obj = {nickName:"庄冰test",email:"2577638904@qq.com"};
// task.editUserBaseInfo({},obj,null).then(d=>{
//   console.log("ddddddddddddddddddddddddddddddddd");
//   console.log(d);
// })
