import Taro from "@tarojs/taro";
import dayjs from "dayjs";
export const goOpenSetting = () => {
  //去设置页的弹框
  return new Promise((reslove, reject) => {
    Taro.showModal({
      title: "提示",
      content: "请点击授权地址",
      success(res) {
        if (res.confirm) {
          Taro.openSetting();
        }
      },
    });
  });
};

export const goOpenSettingPhotos = () => {
  //去设置页的弹框
  return new Promise((reslove, reject) => {
    Taro.showModal({
      title: "提示",
      content: "请点击打开权限",
      success(res) {
        if (res.confirm) {
          Taro.openSetting();
        }
      },
    });
  });
};

export const authorize = (scope) => {
  return new Promise((reslove, reject) => {
    Taro.authorize({
      scope: scope,
      success(res) {
        console.log("authorize授权状态");
        reslove(res);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const back = (delta) => {
  Taro.navigateBack({
    delta,
  });
};

export const msg = (title, mask, icon) => {
  Taro.showToast({
    title,
    mask,
    icon: icon || "none",
    duration: 2000,
  });
};

export const go = (url) => {
  Taro.navigateTo({
    url,
  });
};

// jumpType 0轮播图跳转 1消息列表跳转
export const goJump = (data, jumpType = 0) => {
  // 跳转类型：0无跳转、1跳转内部链接、3跳转外部链接、4跳转小程序、5导向视频号、6导向视频号直播间',
  /**
     *  `link`  ： '跳转链接（跳转外部链接、跳转内部链接）',
        `link_params` ： '跳转链接参数（跳转内部链接）',
        `redirect_appid` ： '外链小程序appid（跳转小程序）',
        `redirect_url` ： '外链小程序url（跳转小程序）',
        `video_no` ： '视频号（导向视频号、导向视频号直播间）',
        `feed_id` ： '视频号feedId（导向视频号）',
    */
  let { type } = data;
  if (type === 0) {
    return;
  }
  jupmFun(type, data);
  // if (jumpType === 0) {
  //   let { type } = data;
  //   if (type === 0) {
  //     return;
  //   }
  //   jupmFun(type, data);
  // } else if (jumpType === 1) {
  //   let { messageType } = data;
  //   if (messageType === 0) {
  //     return;
  //   }
  //   jupmFun(messageType, data);
  // }
};

const jupmFun = (type, data) => {
  try {
    switch (type) {
      case 1: // 跳转内部链接
        let tabbar = [
          "/pages/index/index",
          "/pages/activity/activity",
          "/pages/detect/detect",
          "/pages/shop/shop",
          "/pages/user/user",
        ];
        if (tabbar.includes(data.link)) {
          // tabbar页不能带参数
          Taro.setStorageSync(data.link + "-jupm-params", data.linkParams);
          Taro.switchTab({
            url: data.link,
          });
        } else {
          if (data.linkParams) {
            Taro.navigateTo({
              url: data.link + "?" + data.linkParams,
            });
          } else {
            Taro.navigateTo({
              url: data.link,
            });
          }
        }

        break;
      case 3: // 跳转外部链接
        if (data.linkParams) {
          Taro.navigateTo({
            url:
              "/pages/webViewPage/webViewPage?url=" +
              data.link +
              "?" +
              data.linkParams,
          });
        } else {
          Taro.navigateTo({
            url: "/pages/webViewPage/webViewPage?url=" + data.link,
          });
        }
        break;
      case 4: // 跳转小程序
        Taro.navigateToMiniProgram({
          appId: data.redirectAppid,
          path: data.redirectUrl,
          success: (res) => {
            // 打开成功
            console.log("跳转小程序success", res);
          },
          fail: (res) => {
            console.log("跳转小程序fail", res);
            msg("跳转失败:" + res.errMsg);
          },
        });
        break;
      case 5: // 跳转视频号
        Taro.openChannelsActivity({
          finderUserName: data.videoNo,
          // feedId: data.feedId,
          success: (res) => {
            // 打开成功
            console.log("跳转视频号success", res);
          },
          fail: (res) => {
            console.log("跳转视频号fail", res);
            msg("跳转失败:" + res.errMsg);
          },
        });
        break;
      case 6: // 跳转视频号直播间
        Taro.getChannelsLiveInfo({
          finderUserName: data.videoNo,
          success: (res) => {
            // 打开成功
            console.log("获取直播间信息success", res);

            if (res.status === 3) {
              Taro.showToast({
                title: "直播已结束",
                mask: true,
                icon: icon || "none",
                duration: 2000,
              });
              return;
            }
            Taro.openChannelsLive({
              finderUserName: data.videoNo,
              feedId: res.feedId,
              success: (res) => {
                // 打开成功
                console.log("打开直播间success", res);
              },
              fail: (res) => {
                console.log("打开直播间fail", res);
              },
            });
          },
          fail: (res) => {
            console.log("获取直播间信息fail", res);
          },
        });

        break;
    }
  } catch (error) {
    console.log("error", error);
  }
};

export const loading = (title) => {
  Taro.showToast({
    title,
    mask: true,
    icon: "loading",
  });
};

// 加载中，显示隐藏搭配使用，不能和toast一起用
export const showLoading = (title) => {
  Taro.showLoading({
    title,
    mask: true,
  });
};
export const hideLoading = (title) => {
  Taro.hideLoading();
};

export const showModal = (data) => {
  const {
    t1 = "提示",
    t2 = "",
    btn1show = true,
    btn1text = "取消",
    btn2text = "确定",
    inputshow = false,
    inputtext = "请输入",
  } = data;
  return new Promise((reslove, reject) => {
    Taro.showModal({
      title: t1,
      content: t2,
      showCancel: btn1show,
      cancelText: btn1text,
      confirmText: btn2text,
      editable: inputshow,
      placeholderText: inputtext,
      success(res) {
        if (res.confirm || res.content) {
          reslove(res);
        } else {
          reject(res);
        }
      },
    });
  });
};

export const requestPayment = (data) => {
  //拉起微信支付
  return new Promise((reslove, reject) => {
    Taro.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success(res) {
        reslove(res);
      },
      fail(res) {
        reject(res);
      },
      complete() {
        Taro.hideLoading();
      },
    });
  });
};

// 本地缓存 存
const originSetStorageSync = Taro.setStorageSync;
export const setStorageSync = function (key, data, expires) {
  // 如果没有传第三个有效期参数，就还是用原来的方法
  if (!expires) return originSetStorageSync(key, data);

  if (typeof expires !== "number") {
    console.error("expires is not a number");
    return originSetStorageSync(key, data);
  }
  originSetStorageSync(key, { data, expires: expires });
};

// 本地缓存 取
const originGetStorageSymc = Taro.getStorageSync;
export const getStorageSync = function (key) {
  const data = originGetStorageSymc(key);
  // 如果data不是个对象就说明是没加有效期的，直接返回
  if (typeof data !== "object" || (typeof data === "object" && !data.expires)) {
    return data;
  }
  const now = new Date().getTime();
  // console.log(key, data);
  //

  // console.log("now", now, dayjs(now).format("YYYY-MM-DD hh:mm:ss"));
  // console.log(
  //   "expires",
  //   data.expires,
  //   dayjs(data.expires).format("YYYY-MM-DD hh:mm:ss")
  // );
  // console.log("now < data.expires", now < data.expires);

  if (now < data.expires) {
    //用当前时间和存储的时间对比
    return data.data; // 未过期返回data
  } else {
    // 已过期，移除缓存，返回空
    Taro.removeStorageSync(key);
    return "";
  }
};
