import request from '@/utils/request';
import { getSSOConfig, setPlatformToken } from '@/utils/auth';
import { defaults, omit } from 'lodash-es';
const baseURL = process.env.VUE_APP_BASE_API;
const APP_PORT = process.env.port || process.env.npm_config_port || 8008; // 端口
const PTS_PORT = 7000;

const locationUrl = location.protocol + '//' + location.hostname;

let isUpdatedSSOConfig = false;
export let ssoConfig = {
  appId: process.env.VUE_APP_SYS_ID,
  ssoEnabled: process.env.VUE_APP_SSO_ENABLED === 'TRUE',
  verifyTokenUrl: '/sso/verifyToken',
  ssoLoginUrl: `${locationUrl}:${PTS_PORT}/portal/login?redirect=`,
  appRedirectUrl: `${locationUrl}:${APP_PORT}/fms/index`,
  appLocalUrl: `/fms/index`,
  isRedirect: false
};

const updateSSOConfig = () => {
  if (isUpdatedSSOConfig) {
    return;
  }

  try {
    let configInfo = getSSOConfig();
    if (configInfo) {
      configInfo = JSON.parse(configInfo);
    }

    const { ssoEnabled, appName, ssoLoginUrl } = configInfo || {};
    ssoConfig = defaults(
      {
        appId: appName,
        ssoEnabled:
          process.env.NODE_ENV === 'development'
            ? undefined
            : ssoEnabled === '1',
        ssoLoginUrl:
          process.env.NODE_ENV === 'development' ? undefined : ssoLoginUrl
      },
      ssoConfig
    );
    //alert("开关=" + ssoConfig.ssoEnabled);
    isUpdatedSSOConfig = true;
  } catch (error) {
    alert('解析ssoConfig错误=' + error);
    console.error(error, '解析configinfo 出错');
  }
};

const parseTarget = (target) => {
  if (/(http|https):\/\/([\w.]+\/?)\S*/.test(target)) {
    return target;
  }
  return target;
};

const goTarget = function (href) {
  window.open(href, '_blank');
};
const goUrl = function (href) {
  window.location.href = href;
};

// 获取portal配置
export async function getSsoInfo() {
  let res = await axios({ method: 'get', url: baseURL + '/portal/cfg/cfg' });
  let cfg =
    res.status === 200 &&
    res.data &&
    res.data.code === '000000' &&
    res.data.data;

  return cfg;
}

const getQueryData = () => {
  let oSearchItem = {};
  let searchString = window.location.search;
  let reg = /[?&][^?&]+=[^?&]+/g;
  let arr = searchString.match(reg);
  if (arr) {
    arr.forEach((item) => {
      let tempArr = item.substring(1).split('=');
      let key = decodeURIComponent(tempArr[0]);
      let value = decodeURIComponent(tempArr[1]);
      oSearchItem[key] = value;
    });
  }
  return oSearchItem;
};

export function authSSoToken(ssoToken) {
  //alert( "请求ssoToken=" + ssoToken );

  return request({
    url: ssoConfig.verifyTokenUrl,
    method: 'post',
    data: {
      ptsToken: ssoToken,
      sysName: ssoConfig.appId,
      sysId: ssoConfig.appId
    }
  });
}

export function resdirectApp(redirect, ssoToken) {
  if (ssoConfig.appId === 'PTS') {
    if (/(http|https):\/\/([\w.]+\/?)\S*/.test(redirect)) {
      return redirect + '?token=' + ssoToken;
    }
    return redirect + '';
  } else {
    return parseTarget('/');
  }
}

export function getResdirectAppUrl(ssoToken) {
  updateSSOConfig();

  if (!ssoToken) {
    const currentUrl = location.href;
    const isIndex =
      location.pathname === '/index' || location.pathname === '/fms';
    let backUrl = '/';
    if (ssoConfig.isRedirect) {
      backUrl = isIndex ? '/' : currentUrl || ssoConfig.appRedirectUrl;
    }

    let redirectUrl = ssoConfig.ssoEnabled
      ? parseTarget(
          ssoConfig.ssoLoginUrl + backUrl + `&appid=${ssoConfig.appId}`
        )
      : '/water/login';
    // alert(  ssoConfig.ssoEnabled );
    // alert(redirectUrl);
    // alert(ssoConfig.ssoLoginUrl);
    goUrl(redirectUrl);
  }
}

export function parseSSoToken(store, next, to) {
  updateSSOConfig();
  const { token, siblingToken, redirect } = to.query;

  if (token) {
    let ssoToken = token;
    // alert('全局ssoToken=' + ssoToken);
    if (typeof ssoToken === 'undefined') {
      if (ssoConfig.appId !== 'PTS') {
        if (ssoConfig.ssoEnabled) {
          goUrl(
            `${ssoConfig.ssoLoginUrl}${ssoConfig.appRedirectUrl}${to.fullPath}`
          ); // 否则全部重定向到登录页
        } else {
        }
      }
    } else {
      //请求post地址验证Token
      return authSSoToken(ssoToken)
        .then((response) => {
          //alert("response="+ JSON.stringify(response)  );
          if (response.code === '000000') {
            response = response.data;
            console.log('子系统返回=' + JSON.stringify(response));
            console.log('ssoToken=' + response.token);
            console.log('userBind对象=' + JSON.stringify(response.userBind));
            console.log('userBindToken=' + response.userBind.userBindToken);
            setPlatformToken(ssoToken);
            //alert("response.userBind.userBindToken=" + response.userBind.userBindToken );
            //写入cookie Token
            store
              .dispatch('SaveBindToken', response.userBind.userBindToken)
              .then(() => {
                //冲定向刚才的地址,后台需要带回来
                //alert(location.pathname)
                // router.replace(to.path);

                next({
                  path: to.path,
                  query: omit(to.query, ['token']),
                  replace: true
                });
              });

            return true;
          } else {
            //可能token失效
            // alert('可能token失效');
            return false;
          }
        })
        .catch((error) => {
          console.error(error);
          goUrl(`${ssoConfig.ssoLoginUrl}${ssoConfig.appRedirectUrl}&noToken=`); // 否则全部重定向到登录页
          return false;
        });
    }
  } else if (siblingToken) {
    //
    return store.dispatch('SaveSiblingToken', siblingToken).then(() => {
      router.replace(to.path);
      return true;
    });
  } else {
    return Promise.resolve(false);
  }
}
