import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import center from './images/center.png';
import btnBg from './images/btn-bg.png';
import { browser } from '@/helpers/utils';
import wxBg from './images/wx_bg.png';
import { showToast } from 'vant';
import request from '@/helpers/request';
import { decode } from 'js-base64';

export default defineComponent({
  name: 'download-page',
  setup() {
    const state = reactive({
      wxStatus: false,
      type: 'student',
      androidUrl: '',
      buttonText: '下载学校端'
    });

    const onDownload = () => {
      if (browser().weixin) {
        state.wxStatus = true;
        return;
      }

      let urlIos = '';
      let urlAndroid = '';
      if (location.origin.indexOf('manonline') > -1) {
        urlIos = 'https://itunes.apple.com/cn/app/id6449429354';
        urlAndroid = state.androidUrl; // 'https://oss.dayaedu.com/appstore/manage-domain.apk';
      } else {
        urlIos = 'https://www.pgyer.com/gnTDCk';
        urlAndroid = state.androidUrl; // 'https://www.pgyer.com/Jg6K';
      }

      if (
        browser().ios ||
        /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)
      ) {
        urlIos && (window.location.href = urlIos);
      } else if (/(Android)/i.test(navigator.userAgent)) {
        window.location.href = urlAndroid;
      } else {
        showToast('请用手机或移动设备打开');
      }
    };

    onMounted(async () => {
      try {
        const { data } = await request.get(
          '/api-web/open/appVersionInfo/queryLatestByPlatform',
          {
            params: {
              platform: 'android-education',
              status: 'history'
            }
          }
        );
        state.androidUrl = decode(data.downloadUrl);
      } catch {
        //
      }
    });

    return () => (
      <div class={styles.download}>
        <img src={center} class={styles.center} />
        <img src={btnBg} class={styles.btn} onClick={onDownload} />

        {state.wxStatus && (
          <div
            class={styles.wxpopup}
            onClick={() => {
              state.wxStatus = false;
            }}>
            <img src={wxBg} alt="" />
          </div>
        )}
      </div>
    );
  }
});
