import {
  defineComponent,
  onBeforeUnmount,
  reactive,
  ref,
  onMounted
} from 'vue';
import loginStyles from './images/login_styles.png';
import loginLeft from './images/login-left.png';
import loginRight from './images/loginright.png';
import colLogo from './images/colLogo.png';
import CodeLogin from './components/codeLogin';
import PwdLogin from './components/pwdLogin';
import {
  NTabs,
  NTabPane,
  useDialog,
  NModal,
  NButton,
  NSpace,
  NAlert,
  NImage
} from 'naive-ui';
import styles from './index.module.less';
import ForgotPassword from './components/forgotPassword';
import moveTop from './images/moveTopBg.png';
import dingPng from './images/ding.png';
import closeAble from './images/closeAble.png';
import infoIcon from './images/infoIcon.png';
import { modalClickMask, state } from '/src/state';
import TheAuth from '/src/components/TheAuth';
import { mutualTLSQuery } from './api';
export default defineComponent({
  name: 'login-page',
  setup() {
    const isForgot = ref(false);
    const NavsValue = ref('pwdLogin');
    const pwdLoginRef = ref();
    const forgotPasswordRef = ref();
    const popEvent = ref();
    const dialog = useDialog();
    const userPhone = ref(); // 用户手机号
    const showModalMask = ref(false);
    const showAuthStatus = ref(false);
    const showAuthMask = ref(false);
    const checkInstall = async (event: any) => {
      event.preventDefault();
      console.log('checkInstall', event);
      popEvent.value = event;
      console.log('beforeoutcome');
      // const { outcome } = await event.userChoice;
      // console.log(outcome, 'outcome')
      // setTimeout(async function () {
      //   try {
      //     const { outcome } = await event.userChoice;
      //     console.log(outcome, 'outcome')
      //   } catch (e) {
      //     console.log(e)
      //   }

      // }, 2000)

      if (window.matchMedia('(display-mode: standalone)').matches) {
        state.application = window.matchMedia(
          '(display-mode: standalone)'
        ).matches;
      } else {
        console.log(popEvent.value, 'popEvent.value');
        if (popEvent.value) {
          showModalMask.value = true;
          setTimeout(() => {
            const btn = document.querySelector('#submitBtn');
            // console.log(btn);
            if (btn) {
              btn.addEventListener('click', () => {
                showModalMask.value = false;
                if (!popEvent.value) {
                  return;
                }
                popEvent.value.prompt();
                popEvent.value.userChoice.then((choiceResult: any) => {
                  if (choiceResult.outcome === 'accepted') {
                    console.log('用户已同意添加到桌面');
                    showModalMask.value = false;
                    checkAuthShow();
                  } else {
                    console.log('用户已取消添加到桌面');
                    showModalMask.value = false;
                    checkAuthShow();
                  }
                });
              });
            }
          }, 500);
        }
      }

      // 是否显示桌面安装，是否安装了证书
      await checkAuthError();
      if (!showModalMask.value && showAuthStatus.value) {
        showAuthMask.value = true;
      }
    };

    const checkAuthShow = () => {
      if (showAuthStatus.value) showAuthMask.value = true;
    };

    window.addEventListener('beforeinstallprompt', checkInstall, {
      once: true
    });
    onBeforeUnmount(() => {
      window.removeEventListener('beforeinstallprompt', checkInstall);
    });

    const checkAuthError = async () => {
      try {
        await mutualTLSQuery({});
      } catch (err: any) {
        if (err.message.indexOf('511')) {
          // showAuthMask.value = true;
          showAuthStatus.value = true;
        }
      }
    };

    onMounted(async () => {
      // 已经安装 pwa 不会触发 beforeinstallprompt， 所以加上以下判断
      if (
        window.matchMedia('(display-mode: standalone)').matches ||
        (window.navigator as any).standalone === true
      ) {
        // 是否显示桌面安装，是否安装了证书
        await checkAuthError();
        if (!showModalMask.value && showAuthStatus.value) {
          showAuthMask.value = true;
        }
      }
      // 删除打谱里面上传记录
      sessionStorage.removeItem('task-upload-music');
      // const relatedApps = await navigator?.getInstalledRelatedApps();
    });
    const downChrome = () => {
      const agent = navigator.userAgent.toLowerCase();
      const isMac = (function () {
        return /macintosh|mac os x/i.test(navigator.userAgent);
      })();
      if (agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0) {
        // window.open(
        //   'https://oss.dayaedu.com/appstore/ChromeStandaloneSetup32.exe'
        // );
        window.open('https://www.google.cn/intl/zh-CN_ALL/chrome/fallback/');
      }
      if (agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0) {
        // window.open(
        //   'https://oss.dayaedu.com/appstore/ChromeStandaloneSetup64.exe'
        // );
        window.open('https://www.google.cn/intl/zh-CN_ALL/chrome/fallback/');
      }
      if (isMac) {
        // window.open('https://oss.dayaedu.com/appstore/googlechrome-mac.dmg');
        window.open('https://www.google.cn/intl/zh-CN_ALL/chrome/fallback/');
      }
    };

    return () => (
      <div class={styles['view-account']}>
        <div class={styles['view-account-container']}>
          <img src={loginLeft} class={styles.loginLeft} alt="" />
          <img src={loginRight} class={styles.loginRight} alt="" />
          <div class={styles['stylesWrap']}>
            <img src={loginStyles} alt="" />
          </div>
        </div>
        <div class={styles['view-account-form']}>
          <img class={styles.colLogo} src={colLogo}></img>
          {isForgot.value ? (
            <NTabs
              key="forgotPassword"
              default-value={NavsValue.value}
              class={[styles.loginTabs, styles.loginForgot]}
              ref={forgotPasswordRef}
              justify-content="center">
              <NTabPane name="forgotPassword" tab="重置密码">
                <ForgotPassword
                  v-model:phone={userPhone.value}
                  onChangType={() => {
                    isForgot.value = false;
                    NavsValue.value = 'pwdLogin';
                    // pwdLoginRef.value.syncBarPosition();
                  }}></ForgotPassword>
              </NTabPane>
            </NTabs>
          ) : (
            <NTabs
              key="pwdLogin"
              ref={pwdLoginRef}
              default-value={NavsValue.value}
              class={[styles.loginTabs]}
              justify-content="center">
              <NTabPane name="pwdLogin" tab="密码登录">
                <PwdLogin
                  v-model:phone={userPhone.value}
                  onChangType={() => {
                    isForgot.value = true;
                    NavsValue.value = 'forgotPassword';
                    // forgotPasswordRef.value.syncBarPosition();
                  }}></PwdLogin>
              </NTabPane>
              <NTabPane name="codeLogin" tab="短信验证">
                <CodeLogin v-model:phone={userPhone.value}></CodeLogin>
              </NTabPane>
            </NTabs>
          )}
          <div class={styles.alertWrap}>
            <div class={styles.alertInfo}>
              <NImage
                src={infoIcon}
                class={styles.infoIcon}
                previewDisabled></NImage>
              为了您更好的上课体验，推荐使用Chrome浏览器
            </div>
            <div class={styles.down} onClick={downChrome}>
              立即下载
            </div>
          </div>
        </div>
        <NModal
          maskClosable={modalClickMask}
          v-model:show={showModalMask.value}
          onMaskClick={() => {
            checkAuthShow();
          }}
          onClose={() => {
            checkAuthShow();
          }}>
          <div class={styles.downMove}>
            <img src={dingPng} class={styles.dingPng} alt="" />
            <img src={moveTop} class={styles.downMoveBg} alt="" />
            <img
              src={closeAble}
              class={styles.closeAble}
              onClick={() => {
                showModalMask.value = false;
                checkAuthShow();
              }}
              alt=""
            />
            <h2>温馨提示</h2>
            <p>
              检测到您尚未安装“音乐数字课堂”应用程序，为了更好的使用体验，是否立即下载？
            </p>
            {/* <NButton>确定</NButton> */}
            <NSpace style={{ padding: '25px 0 0 0' }} justify="center">
              <NButton
                {...{ id: 'submitBtn' }}
                class={styles.submitAppBtn}
                round
                type="primary">
                立即下载
              </NButton>
            </NSpace>
          </div>
        </NModal>

        <NModal
          v-model:show={showAuthMask.value}
          closeOnEsc={false}
          maskClosable={false}>
          <TheAuth onClose={() => (showAuthMask.value = false)} />
        </NModal>
      </div>
    );
  }
});
