const Response = require('../util/response');
const jwt = require('jsonwebtoken');

class AuthController{
    static processIDToken(ctx){
      const query = ctx.query;
      const {id_token} = query;
      if(!id_token){
        ctx.body = Response.failed("非法请求！")
      }else{
        jwt.verify(id_token, 'SEEC-1919810-OIDC-114514', (err, authData) => {
          if(err) {
            console.log("err:", err);
            ctx.redirect("/error");
          }
          else {
            const { iss, sub, aud, auth_time, iat, exp} = authData;
            if(!iss || !sub || !aud || !auth_time || !iat || !exp){
              ctx.redirect("/error");
            }
            else if(iss !== "http://localhost" || aud!=='seec-portal' ){
              ctx.redirect("/error");
            }
            else{
              let claims = sub.split('%26');
              let origin_path = ctx.cookies.get('origin_path');
              let user = {
                id: parseInt(claims[0]),
                name: claims[1],
                phone: claims[2]
              };
              let my_token = jwt.sign(
                user,'seec-portal',{ expiresIn: '1day' }
              );

              console.log('ctx', ctx);
              // console.log('$cookies', ctx.app.$cookies);

              // ctx.res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
              // ctx.res.setHeader("Access-Control-Allow-Credentials", true);

              // ctx.cookies.user = user;
              // ctx.cookies.token = my_token;
              //
              // console.log("origin_path", origin_path)
              //
              // ctx.redirect(origin_path);

              let url = '/setToken?origin_path=' + origin_path + '&token=' + my_token + '&id=' + user.id + '&name=' + user.name + '&phone=' + user.phone;
              // store.commit("saveUser", user);
              // store.commit("saveToken", my_token);
              ctx.redirect(url);
            }
          }
        });

      }

    }

  static authenticate(ctx){
    const query = ctx.query;
    const {path} = query;

    let return_uri = encodeURIComponent("http://localhost:8000/api/receiveIDToken");
    let url = 'http://localhost:3000/api/interaction?'+
      'client_id='+ 'seec-portal' +
      '&scope=openid' +
      '&redirect_uri=' + return_uri +
      '&response_type=code';

    // ctx.cookies.set("origin_path", path);

    console.log("redirect to " + url);

    return ctx.redirect(url);
  }

}

module.exports = AuthController;
