export default function createshowRewardedVideoAd() {
  let videoAd = null;
  return function showRewardedVideoAd() {
    uni.showLoading({ title: "拉取广告中", mask: true });
    return new Promise((resolve, reject) => {
      if (!videoAd) {
        videoAd = wx.createRewardedVideoAd({
          adUnitId: "adunit-fe42214ae308ac05",
        });
        videoAd.onError = (e) => {
          console.log(e);
        };
      }

      const onError = (err) => {
        switch (err?.errCode) {
          case 1000:
            err.errMsg = "后端接口调用失败";
            break;
          case 1001:
            err.errMsg = "参数错误";
            break;
          case 1002:
            err.errMsg = "广告单元无效";
            break;
          case 1003:
            err.errMsg = "内部错误";
            break;
          case 1004:
            err.errMsg = "无合适的广告";
            break;
          case 1005:
            err.errMsg = "广告组件审核中";
            break;
          case 1006:
            err.errMsg = "广告组件被驳回";
            break;
          case 1007:
            err.errMsg = "广告组件被封禁";
            break;
          case 1008:
            err.errMsg = "广告单元已关闭";
            break;
        }
        console.log(err);
        uni.hideLoading();
        reject(err);
        offAll();
      };

      const onClose = (res) => {
        console.log(res);
        offAll();
        resolve(res);
      };

      function offAll() {
        videoAd.offClose(onClose);
        videoAd.offError(onError);
      }

      videoAd
        .load()
        .then(() => videoAd.show())
        .then(() => uni.hideLoading())
        .catch((err) => {
          onError(err);
        });

      videoAd.onError(onError);

      videoAd.onClose(onClose);
    });
  };
}
