import dayjs from 'dayjs';
import numeral from 'numeral';
import { Toast } from 'vant';
import { state as helpState } from './helpState';
import qs from 'query-string';

export const browser = () => {
  const u = navigator.userAgent;
  //   app = navigator.appVersion;
  return {
    trident: u.indexOf('Trident') > -1, //IE内核
    presto: u.indexOf('Presto') > -1, //opera内核
    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/Mac OS X/), //ios终端
    // ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    android: u.indexOf('DAYAAPPA') > -1 || u.indexOf('Adr') > -1, //android终端
    iPhone: u.indexOf('DAYAAPPI') > -1, //是否为iPhone或者QQHD浏览器
    isApp:
      u.indexOf('DAYAAPPI') > -1 ||
      u.indexOf('DAYAAPPA') > -1 ||
      u.indexOf('Adr') > -1,
    iPad: u.indexOf('iPad') > -1, //是否iPad
    webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
    alipay: u.indexOf('AlipayClient') > -1, //是否支付宝
    huawei: !!u.match(/huawei/i) || !!u.match(/honor/i),
    xiaomi: !!u.match(/mi\s/i) || !!u.match(/redmi/i) || !!u.match(/mix/i)
  };
};

// 获取授权的code码
export const getUrlCode = (name = 'code') => {
  // 截取url中的code方法
  const url = location.search;
  const theRequest: any = new Object();
  if (url.indexOf('?') != -1) {
    const str = url.substr(1);
    const strs = str.split('&');
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
    }
  }
  console.log(theRequest, 'theRequest');
  return theRequest[name];
};

export const getQuery = (name = 'code') => {
  let search: any = {};
  try {
    search = {
      ...qs.parse(location.search),
      ...qs.parse(location.hash.split('?')[1])
    };
  } catch (error) {
    //
  }
  return search[name];
};
export const getRandomKey = () => {
  const key = '' + new Date().getTime() + Math.floor(Math.random() * 1000000);
  return key;
};

/**
 * 删除token
 */
export const removeAuth = () => {
  sessionStorage.removeItem('Authorization');
};

/**
 * 设置token
 * @param token
 * @returns {void}
 */
export const setAuth = (token: any) => {
  sessionStorage.setItem('Authorization', token);
};

/**
 * 获取token
 */
export const getAuth = () => {
  sessionStorage.getItem('Authorization');
};

/**
 * 开始加载
 */
export const openLoading = () => {
  if (helpState.loadingCount === 0) {
    helpState.loadingCount++;
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
      duration: 0
    });
  }
};

/**
 * 关闭加载
 */
export const closeLoading = () => {
  // console.log(helpState.loadingCount, +new Date());
  if (helpState.loadingCount <= 0) return;
  setTimeout(() => {
    helpState.loadingCount--;
    if (helpState.loadingCount === 0) {
      Toast.clear();
    }
  }, 200);
};

export const getWeekCh = (week: number, type = 0) => {
  const template = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const template2 = [
    '星期天',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六'
  ];
  return type ? template2[week] : template[week];
};

export const numberFormat = (num: number, type?: string) => {
  if (type === 'percent') {
    return numeral(num).format('0.0%');
  }
  return numeral(num).format('0,0');
};

export const moneyFormat = (value: number, format = '0,0.00') => {
  return numeral(value).format(format);
};
export const dateFormat = (
  value: string | Date,
  format = 'YYYY-MM-DD HH:mm:ss'
) => {
  return dayjs(value).format(format);
};

// 秒转分
export const getSecondRPM = (second: number, type?: string) => {
  if (isNaN(second)) return '00:00';
  const mm = Math.floor(second / 60)
    .toString()
    .padStart(2, '0');
  const dd = Math.floor(second % 60)
    .toString()
    .padStart(2, '0');
  if (type === 'cn') {
    return mm + '分' + dd + '秒';
  } else {
    return mm + ':' + dd;
  }
};

/**
 * @description 格式化日期控件显示内容
 * @param type
 * @param option
 * @returns OBJECT
 */
export const formatterDatePicker = (type: any, option: any) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  if (type === 'day') {
    option.text += '日';
  }
  return option;
};
