import { mapMutations } from 'vuex'
import jwt from 'jsonwebtoken'

export default function (context) {
  const {app, route, store, req, res, requset, redirect, next} = context;
  let isClient = process.client;
  let isServer = process.server;
  let token, path;

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

  token = store.state.token;

  // console.log("cookies", cook);
  //在服务端
  if (isServer) {
    path = req.originalUrl;
  }
  //在客户端判读是否需要登陆
  if (isClient) {
    path = route.path;
  }

  console.log("path:"+path);
  let mainPath = path.split("?")[0];
  console.log('mainPath', mainPath);

  if(mainPath === "/setToken"){
    try{
      const params = path.split("?")[1].split('&');
      let obj = {};
      if(params.length !== 5
        || params[0].split("=")[0] !== "origin_path"
        || params[1].split("=")[0] !== "token"
        || params[2].split("=")[0] !== "id"
        || params[3].split("=")[0] !== "name"
        || params[4].split("=")[0] !== "phone"
      ){
        redirect('/error');
      }else{
        for(let i = 0; i < 5 ; i++){
          obj[params[i].split("=")[0]] = params[i].split("=")[1];

        }
        console.log('obj', obj);
        let new_token = obj['token'];
        let origin_path = obj['origin_path'];
        let user = {id: obj['id'], name: obj['name'], phone: obj['phone']};

        app.$cookies.set('token', new_token);
        app.$cookies.set('user', user);

        redirect(origin_path);
      }

    }catch (e) {
      console.log("e: ", e);
      redirect('/error');
    }
  }

  else if (!token && mainPath !== "/" && mainPath !=="/login" && mainPath !== "/register" && mainPath !=="/error" && mainPath !== "/api/receiveIDToken") {
    redirect('/api/authenticate?path=' + mainPath);

  }

}
