import { ref, unref, defineEmits } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useGlobSetting } from '/@/hooks/setting';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStore } from '/@/store/modules/user';
import { setThirdCaptcha, getCaptcha } from '/@/api/sys/user';
import { useI18n } from '/@/hooks/web/useI18n';

export function useThirdLogin(emit) {
  const { createMessage, notification } = useMessage();
  const { t } = useI18n();
  const glob = useGlobSetting();
  const userStore = useUserStore();
  //第三方类型
  const thirdType = ref('');
  //第三方登录相关信息
  const thirdLoginInfo = ref<any>({});
  //状态
  const thirdLoginState = ref(false);
  //注册或者绑定账户
  const bindingAccount = ref(false);
  //第三方用户UUID
  const thirdUserUuid = ref('');
  //提示窗
  const thirdConfirmShow = ref(false);
  //绑定手机号
  const thirdPhone = ref('');
  //验证码
  const thirdCaptcha = ref('');
  //第三方登录
  function onThirdLogin(source) {
    let url = `${glob.uploadUrl}/sys/thirdLogin/render/${source}`;
    window.open(
      url,
      `login ${source}`,
      'height=500, width=500, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no'
    );
    thirdType.value = source;
    thirdLoginInfo.value = {};
    thirdLoginState.value = false;
    let receiveMessage = function (event) {
      let token = event.data;
      if (typeof token === 'string') {
        //如果是字符串类型 说明是token信息
        if (token === '登录失败') {
          createMessage.warning(token);
        } else if (token.includes('绑定手机号')) {
          bindingAccount.value = true;
          let strings = token.split(',');
          thirdUserUuid.value = strings[1];
          emit('type', { loginType: 'thirdLogin' });
        } else {
          doThirdLogin(token);
        }
      } else if (typeof token === 'object') {
        //对象类型 说明需要提示是否绑定现有账号
        if (token['isObj'] === true) {
          thirdConfirmShow.value = true;
          thirdLoginInfo.value = { ...token };
        }
      } else {
        createMessage.warning('不识别的信息传递');
      }
      //update-begin---author:wangshuai---date:2024-02-20---for:【QQYUN-8156】连续登录失败，导致失败提醒累加---
      window.removeEventListener('message', unref(receiveMessage),false);
      //update-end---author:wangshuai---date:2024-02-20---for:【QQYUN-8156】连续登录失败，导致失败提醒累加---
    };
    window.addEventListener('message', receiveMessage, false);
  }
  // 根据token执行登录
  function doThirdLogin(token) {
    if (unref(thirdLoginState) === false) {
      thirdLoginState.value = true;
      userStore.ThirdLogin({ token, thirdType: unref(thirdType) }).then((res) => {
        console.log('res====>doThirdLogin', res);
        if (res && res.userInfo) {
          notification.success({
            message: t('sys.login.loginSuccessTitle'),
            description: `${t('sys.login.loginSuccessDesc')}: ${res.userInfo.realname}`,
            duration: 3,
          });
        } else {
          requestFailed(res);
        }
      });
    }
  }

  function requestFailed(err) {
    notification.error({
      message: '登录失败',
      description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
      duration: 4,
    });
  }

  //绑定手机号点击确定按钮
  function thirdHandleOk() {
    if (!unref(thirdPhone)) {
      cmsFailed('请输入手机号');
    }
    if (!unref(thirdCaptcha)) {
      cmsFailed('请输入验证码');
    }
    let params = {
      mobile: unref(thirdPhone),
      captcha: unref(thirdCaptcha),
      thirdUserUuid: unref(thirdUserUuid),
    };
    defHttp.post({ url: '/sys/thirdLogin/bindingThirdPhone', params }, { isTransformResponse: false }).then((res) => {
      if (res.success) {
        bindingAccount.value = false;
        doThirdLogin(res.result);
      } else {
        createMessage.warning(res.message);
      }
    }).catch((e)=>{
      createMessage.warning(e.message);
    });
  }
  function cmsFailed(err) {
    notification.error({
      message: '登录失败',
      description: err,
      duration: 4,
    });
    return;
  }

  /**
   * 登录并绑定
   */
  function loginAccountClick() {
    emit('type', { loginType: 'login' });
  }

  /**
   * 创建新账号
   */
  function registerAccountClick() {
    emit('type', { loginType: 'register' });
  }

  /**
   * 隐藏绑定页面
   */
  function hideBindThirdAccount() {
    bindingAccount.value = false;
  }

  /**
   * 注册用户并且绑定第三方
   */
  async function createAccountBindThird(values) {
    let params = { ...values };
    params.thirdUserUuid = unref(thirdUserUuid);
    await defHttp
      .put({ url: '/sys/thirdLogin/registerBindThirdAccount', params }, { isTransformResponse: false })
      .then((res) => {
        if (res.success) {
          bindingAccount.value = false;
          doThirdLogin(res.result);
        } else {
          createMessage.warning(res.message);
        }
      })
      .catch((e) => {
        createMessage.warning(e.message);
      })
  }

  /**
   * 绑定手机号
   * @param values
   */
  function bindThirdAccount(values) {
    thirdPhone.value = values.mobile;
    thirdCaptcha.value = values.sms;
    thirdHandleOk();
  }

  //返回数据和方法
  return {
    thirdConfirmShow,
    bindingAccount,
    thirdHandleOk,
    thirdPhone,
    thirdCaptcha,
    onThirdLogin,
    loginAccountClick,
    registerAccountClick,
    hideBindThirdAccount,
    bindThirdAccount,
    createAccountBindThird,
  };
}
