import store from "@/store/index.js";
import config from "@/common/config";
import api from "@/common/api.js";

export default {
  isGoLogin(isBack = true) {
    if (!uni.getStorageSync("user_account")) {
      uni.navigateTo({
        url: "/pages4/login/login?isBack=" + isBack,
      });
      return true;
    } else {
      return false;
    }
  },
  isLogin() {
    if (uni.getStorageSync("user_account")) {
      return true;
    } else {
      return false;
    }
  },
  isLogout() {
    // uni.removeStorageSync('user_account')
    // uni.removeStorageSync('token')
  },
  //提示
  showToast(title, icon = "none", time = 2000) {
    return setTimeout(() => {
      uni.showToast({
        title: title,
        icon: icon,
        duration: time,
      });
    }, 500);
  },
  //图片路径填补
  splitImgHost(url, scale = false, width = 250) {
    if (!url) {
      return "";
    } else if (
      url.indexOf("http") != -1 ||
      url.indexOf("https") != -1 ||
      url.indexOf("wxfile") != -1
    ) {
    } else {
      url = config.BASE_IMG_URL + url;
    }
    if (scale) {
      url = url + "?x-oss-process=image/resize,w_" + width;
    }
    return url;
  },
  setUuid(id) {
    uni.setStorageSync("uuid", id);
  },

  getUuid() {
    return uni.getStorageSync("uuid");
  },
  exit() {
    uni.removeStorageSync("user_account");
    uni.removeStorageSync("token");
    uni.removeStorageSync("h5_code");
    store.state.userInfo = null;
    uni.reLaunch({
      url: "/pages/index/index",
    });
  },
  /* 时间戳转换成日期
   * @param timestamp
   * @returns {*}
   */
  timestampToTime(timestamp, isDay = true, hasChinese, line) {
    if (!timestamp) {
      return "";
    }
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + (hasChinese ? "" : "-");
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + (hasChinese ? "" : "-");
    var D =
      date.getDate() < 10
        ? "0" + date.getDate() + (hasChinese ? "" : " ")
        : date.getDate() + (hasChinese ? "" : " ");
    var h =
      date.getHours() < 10
        ? "0" + date.getHours() + ":"
        : date.getHours() + ":";
    var m =
      date.getMinutes() < 10
        ? "0" + date.getMinutes() + ":"
        : date.getMinutes() + ":";
    var s =
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    if (isDay) {
      if (hasChinese) {
        return Y + "年" + M + "月" + D + "日";
      } else {
        return Y + M + D;
      }
    }
    if (line) {
      return h + m + s;
    }

    if (hasChinese) {
      return Y + "年" + M + "月" + D + "日" + h + m + s;
    } else {
      return Y + M + D + h + m + s;
    }
  },
  // 时间戳转换日期
  formDate(time, formate = "yyyy-mm-dd hh:mm:ss") {
    var padDate = function (va) {
      va = va < 10 ? "0" + va : va;
      return va;
    };
    if (time) {
      var value = new Date(time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      // var value = new Date(parseFloat(time))
      var year = value.getFullYear();
      var month = padDate(value.getMonth() + 1);
      var day = padDate(value.getDate());
      var hour = padDate(value.getHours());
      var minutes = padDate(value.getMinutes());
      var seconds = padDate(value.getSeconds());
      let res = "";
      switch (formate) {
        case "mm-dd": {
          res = month + "-" + day;
          break;
        }
        case "yyyy-mm-dd": {
          res = year + "-" + month + "-" + day;
          break;
        }
        case "yyyy-mm": {
          res = year + "-" + month;
          break;
        }
        case "mm月dd日": {
          res = month + "月" + day + "日";
          break;
        }
        case "yyyy年mm月dd日": {
          res = year + "年" + month + "月" + day + "日";
          break;
        }
        case "yyyy年mm月": {
          res = year + "年" + month + "月";
          break;
        }
        case "hh:mm": {
          res = hour + ":" + minutes;
          break;
        }
        case "yyyy-mm-dd hh:mm": {
          res = year + "-" + month + "-" + day + " " + hour + ":" + minutes;
          break;
        }
        case "yyyy.mm.dd":
          res = year + "." + month + "." + day;
          break;
        case "yyyy-mm-dd hh:mm:ss":
        default: {
          res =
            year +
            "-" +
            month +
            "-" +
            day +
            " " +
            hour +
            ":" +
            minutes +
            ":" +
            seconds;
          break;
        }
      }
      return res;
    }
    return "--";
  },
  //当前时间距离目标时间还有多久
  GetRTime(EndTime, isDay = true) {
    var EndTime = EndTime; //结束时间
    var NowTime = new Date(); //当前时间
    //后台给我的是10位 精确到秒的 所有下面我就除以了1000，不要小数点后面的
    var t = EndTime - (NowTime.getTime() / 1000).toFixed(0);

    if (t <= 0) {
      return "已结束";
    }
    //如果后台给的是毫秒 上面不用除以1000 下面的计算时间也都要除以1000 这里我去掉1000了
    var d = Math.floor(t / 60 / 60 / 24); //天 var d=Math.floor(t/1000/60/60/24)
    var h = Math.floor((t / 60 / 60) % 24); //时 var h=Math.floor(t/1000/60/60%24)
    var m = Math.floor((t / 60) % 60); //分 var m=Math.floor(t/1000/60%60)
    var s = Math.floor(t % 60); //秒 var s=Math.floor(t/1000%60)
    if (parseInt(d) < 10) {
      d = "0" + d;
    }
    if (parseInt(h) < 10) {
      h = "0" + h;
    }
    if (parseInt(m) < 10) {
      m = "0" + m;
    }
    if (parseInt(s) < 10) {
      s = "0" + s;
    }
    if (isDay) {
      return d;
    }
    return d + "天" + h + "小时" + m + "分" + s + "秒";
  },
  TimeTotimestamp(date) {
    var date = date.replace(/-/g, "/");
    var newDate = new Date(date);
    return newDate.getTime() / 1000;
  },
  timest() {
    var tmp = Date.parse(new Date()).toString();
    tmp = tmp.substr(0, 10);
    return tmp;
  },
  //压缩图片
  imageInfos(url) {
    var self = this;
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: url,
        success: async (res) => {
          let canvasWidth = res.width; //图片原始长宽
          let canvasHeight = res.height;
          if (canvasWidth > 2000 || canvasHeight > 2000) {
            uni.compressImage({
              src: url,
              quality: 75,
              width: "35%",
              height: "35%",
              success: async (rest) => {
                const waitUpload = await self.uploadFile(rest.tempFilePath, 0);
                console.log(waitUpload, "waitUpload");
                resolve(waitUpload);
              },
            });
          } else if (canvasWidth > 1000 || canvasHeight > 1000) {
            uni.compressImage({
              src: url,
              quality: 75,
              width: "50%",
              height: "50%",
              success: async (rest) => {
                const waitUpload = await self.uploadFile(rest.tempFilePath, 0);
                console.log(waitUpload, "waitUpload");
                resolve(waitUpload);
              },
            });
          } else {
            const waitUpload = await self.uploadFile(url, 0);
            console.log(waitUpload, "waitUpload");
            resolve(waitUpload);
            // console.log('无需压缩', url);
            // resolve(url);
          }
        },
      });
    });
  },
  //上传图片
  uploadFile(options, int) {
    return new Promise((resolve, reject) => {
      var self = this;
      if (options.indexOf("//tmp") === -1 && options.indexOf("//temp") === -1) {
        resolve(options);
        return;
      }
      var data = {
        imageStatus: int,
      };
      api.aliyunpolicy(data).then((res) => {
        var ossToken = res.data.data.resultContent;
        uni.uploadFile({
          url: ossToken.host,
          name: "file",
          filePath: options,
          fileType: "image",
          header: {
            AuthorizationToken: "WX " + uni.getStorageSync("token"),
          },
          formData: {
            key: ossToken.dir,
            OSSAccessKeyId: ossToken.accessid,
            policy: ossToken.policy,
            Signature: ossToken.signature,
            // callback: ossToken.callback,
            success_action_status: 200,
          },
          success: (result) => {
            // if (result.statusCode === 200) {
            resolve(ossToken.dir);
            // } else {
            // 	uni.showToast({
            // 		title: '上传失败',
            // 		icon: 'none'
            // 	});
            // 	return;
            // }
          },
          fail: (error) => {
            uni.showToast({
              title: "上传接口报错",
              icon: "none",
            });
            return;
          },
        });
      });
    });
  },
  getYears(strBirthday) {
    if (!strBirthday) {
      return "-";
    }
    var returnAge;
    var strBirthdayArr = strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];
    var d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();

    if (nowYear == birthYear) {
      returnAge = 0; //同年 则为0岁
    } else {
      var ageDiff = nowYear - birthYear; //年之差
      if (ageDiff > 0) {
        if (nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay; //日之差
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          var monthDiff = nowMonth - birthMonth; //月之差
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
      }
    }
    return returnAge; //返回周岁年龄
  },
  getDate() {
    let nowDate = new Date();
    let date = {
      year: nowDate.getFullYear(),
      month: nowDate.getMonth() + 1,
      date: nowDate.getDate(),
    };
    return date.year + "-" + date.month + "-" + date.date;
  },
  getZeroTime() {
    return Number(new Date(new Date().toLocaleDateString()).getTime() / 1000);
  },
  setClock: function (time) {
    var that = this,
      sec = parseInt(time),
      clockCount = {},
      strTimer = "";
    clockCount = setInterval(function () {
      if (sec == 0) {
        $(".js-count-down").html("活动已经结束");
        clearInterval(clockCount);
        return false;
      }
      strTimer = that.secondToDate(sec);
      $(".js-count-down").html(strTimer);
      sec--;
    }, 1000);
  },
  secondToDate(result) {
    var h =
      Math.floor(result / 3600) < 10
        ? "0" + Math.floor(result / 3600)
        : Math.floor(result / 3600);
    var m =
      Math.floor((result / 60) % 60) < 10
        ? "0" + Math.floor((result / 60) % 60)
        : Math.floor((result / 60) % 60);
    var s =
      Math.floor(result % 60) < 10
        ? "0" + Math.floor(result % 60)
        : Math.floor(result % 60);
    if (h == 0) {
      result = m + ":" + s;
    } else {
      result = h + ":" + m + ":" + s;
    }
    return result;
  },
  /**
   *
   * @param {int} result
   * @returns {string}
   * @remard 单位S转小时分钟秒
   */
  secondToTime(result, Diszing = true) {
    var h =
      Math.floor(result / 3600) < 10
        ? "0" + Math.floor(result / 3600)
        : Math.floor(result / 3600);
    var m =
      Math.floor((result / 60) % 60) < 10
        ? "0" + Math.floor((result / 60) % 60)
        : Math.floor((result / 60) % 60);
    var s =
      Math.floor(result % 60) < 10
        ? "0" + Math.floor(result % 60)
        : Math.floor(result % 60);
    if (h == 0 && Diszing) {
      result = m + ":" + s;
    } else {
      result = h + ":" + m + ":" + s;
    }
    return result;
  },
  /**
   * @param {Object} length  长度
   * 获取随机字符串
   */
  getRandomString(length) {
    var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = "";
    for (var i = length; i > 0; --i)
      result += str[Math.floor(Math.random() * str.length)];
    return result;
  },
  skipLogin(sign) {
    return api.skipLogin({ sign }).then((res) => {
      if (res.data.code == 200) {
        uni.removeStorageSync("newUser_sc");
        uni.removeStorageSync("shareActivityCode");
        //信息完善，直接进入页面
        uni.setStorageSync("user_account", res.data.data.user_account);
        uni.setStorageSync("token", res.data.data.token);
        store.dispatch("getUserInfo").finally((e) => {
          return Promise.resolve();
        });
      } else {
        uni.navigateTo({
          url: "/pages4/login/login",
        });
        return Promise.reject();
      }
    });
  },
  getCanvas(that, className = ".canvas") {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: (res) => {
          const query = uni.createSelectorQuery().in(that);
          setTimeout(() => {
            query
              .select(className)
              .boundingClientRect()
              .exec((newRes) => {
                resolve({ systemInfo: res, newRes });
              });
          }, 1000);
        },
      });
    });
  },
  toLink(externalLink) {
    if (!externalLink) {
      uni.showModal({
        showCancel: false,
        content: "链接不存在",
      });
      return;
    }
    // #ifdef MP-WEIXIN
    uni.navigateTo({
      url: `/pages/webview/sdlink?url=` + externalLink,
    });
    // #endif
    // #ifdef H5
    window.location.href = externalLink;
    // #endif
  },
};
