/*
 * @Author: your name
 * @Date: 2021-06-23 22:15:11
 * @LastEditTime: 2021-06-25 00:23:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Mina_B_T\miniprogram\utils\util.ts
 */
import { getHwUserInfoApi } from "../service/hwUser";
import { apiUrl } from "../config"; // 加载接口地址文件

/**
 * 执行跳转登录页面操作
 */
export function login(message: string = '你还未登录，请立即登录') {
  wx.showModal({
    title: '提示',
    content: message,
    cancelColor: '#888A8E',
    confirmColor: '#31364C',
    success: res => {
      if (res.confirm) {
        wx.reLaunch({
          url: '/pages/login/login',
        })
      }
    }
  })
}

/* 
   格式化时间
   @date {Date} 传入的时间
   @status {Boolean} 是否需要时分秒开关 true 关闭时分秒选项  false  打开时分秒选项
  */
export function formatTime(date: string, status: boolean = false) {
  date = date.replace(RegExp('-', 'g'), '/');
  const _date = new Date(date);
  const year = _date.getFullYear();
  const month = _date.getMonth() + 1;
  const day = _date.getDate();
  const hour = _date.getHours();
  const minute = _date.getMinutes();
  const second = _date.getSeconds();
  if (status) {
    return [year, month, day].map(formatNumber).join('/');
  }
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

/* 格式化数字 */
export function formatNumber(n: number | string): string {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

/* 
 获取实际数据类型 
 @data {any} 数据
*/
export function getDataType(data: any) {
  const result = /^\[object (.*)\]$/.exec(Object.prototype.toString.call(data));
  if (result) {
    return result[1]
  }
  return ''
}

/* 
    获取url 
    @url {String} 待处理的URL
    @return {String} 处理过的字符串 
    根据URL是否有http或者https判断是否拼接字符串
  */
export function getUrl(url: string): Promise<string> {
  return new Promise(resolve => {

    if (url.indexOf('https://') === -1 && url.indexOf('http://') === -1) {
      resolve(apiUrl + url)
    } else {
      if (url.indexOf('http://') === -1) {
        resolve(url)
        return
      }
      resolve(url.replace('http://', 'https://'))
    }
  })
}

/**
   * 获取网络状态
   */
export function getNetworkType(): Promise<string> {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success: function (res) {
        if (res.networkType === 'none') {
          resolve('offline')
        } else {
          resolve(res.networkType)
        }
      },
      fail: function () {
        reject('fail')
      }
    })
  })
}

/**
   * 获取userid与userToken
   * @options {Object} 传入的对象参数
   * @return 返回参数对象
   * 设置request参数中的userID和usertoken
   */
export function getUserId(data: any) {
  return new Promise((reslove) => {
    const userId = wx.getStorageSync('userId');
    const userToken = wx.getStorageSync('userToken');
    data.user_id = userId;
    data.user_token = userToken;
    reslove(data)
  })
}

export function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
  return key in object;
}

/**
 * 上传图片
 * @pic_arr {Array} 图片数组 
 * @return {Array} 
 */
export function upLoadImage(options: { files: string[]; formData?: {}; url: string; name: string; }): Promise<any> {
  const _type = getDataType(options.files);
  options.formData = options.formData || {};
  const formData = {
    user_id: wx.getStorageSync('userId'),
    user_token: wx.getStorageSync('userToken'),
    ...options.formData
  };
  wx.showLoading({
    mask: true,
    title: '上传中...'
  })
  return new Promise(async (resolve, reject) => {
    if (_type === "Array") {
      const _arr: string[] = [];
      const _files = options.files;
      const _len = _files.length - 1;
      const _url: string = await getUrl(options.url);
      _files.forEach((val: string, key: number) => {
        wx.uploadFile({
          url: _url,
          filePath: val,
          name: options.name,
          formData,
          success: res => {
            if (res.statusCode === 200) {
              const data = JSON.parse(res.data);
              if (data.errcode === 0) {
                _arr.push(data.data);
                if (_len === key) {
                  wx.hideLoading()
                  resolve(_arr)
                }
              }
            }
          },
          fail: (e: any) => {
            console.log(e)
            reject({
              type: getDataType(val)
            })
            wx.hideLoading()
            throw new Error(e)
          }
        })
      })
    } else {
      reject({
        type: _type
      })
      wx.hideLoading()
      throw new Error('输入格式有误')
    }
  })
}

/**
 * 获取用户信息
 */
export function getHwUserInfo() {
  return new Promise(resolve => {
    getHwUserInfoApi().then(data => {
      const res = <responseOptionsType>data
      if (res.data) {
        //成功后存入缓存
        wx.setStorageSync('userInfo', res.data.hwUser);
        resolve(res.data.hwUser)
      }
    }).catch(error => {
      console.error(error);
    })
  })
}

/**
 * 设置可过期的缓存
 * @param key 
 * @param value 
 * @param time 
 */
export function putStorageSync(key: string, value: any, time: number = 86400000): void {
  wx.setStorageSync(key, value)
  const _time: number = Date.now()
  wx.setStorageSync(key + 'redis', _time + time)
}

/**
 * 获取可过期缓存
 * @param key 
 */
export function getStorageSync(key: string): any {
  const time: number = wx.getStorageSync(key + 'redis')
  if (!time || Date.now() > time) {
    wx.removeStorageSync(key)
    wx.removeStorageSync(key + 'redis')
    return ''
  } else {
    return wx.getStorageSync(key)
  }
}