let $ = jQuery;

// jQuery 存储 到localStorage，临时数据，当过期返回NULL。
const tempStorage = {
  // 设置临时数据（key: 键名, value: 值, expiresInMinutes: 过期时间（小时））
  set(key, value, expiresInMinutes) {
    try {
      // const expiresAt = Date.now() + (expiresInMinutes * 60 * 60 * 1000);
      const expiresAt = Date.now() + (expiresInMinutes * 60 * 60 * 1000);
      const storageObject = {
        value,
        expiresAt
      };
      localStorage.setItem(key, JSON.stringify(storageObject));
      return true;
    } catch (error) {
      console.error('无法存储到 localStorage:', error);
      return false;
    }
  },

  // 获取临时数据（过期或不存在返回 null）
  get(key) {
    try {
      const item = localStorage.getItem(key);
      if (!item) return null;

      const storageObject = JSON.parse(item);
      if (Date.now() > storageObject.expiresAt) {
        localStorage.removeItem(key);
        return null;
      }

      return storageObject.value;
    } catch (error) {
      console.error('无法从 localStorage 获取数据:', error);
      localStorage.removeItem(key);
      return null;
    }
  },

  // 删除数据
  remove(key) {
    localStorage.removeItem(key);
  },

  // 清空所有临时存储
  clear() {
    localStorage.clear();
  }
};

if (window.self == window.top) {
  $(function () {
    //======公共变量
    const wztkj_ScreenWidth = $(window).width(); //当前屏幕的宽度
    let footerAdvertisingFun; //底部广告倒计时开启函数


    // 滚动控制函数
    function stopRoll() {
      $('body').css('overflow', 'hidden');
    }

    function openRoll() {
      $('body').css('overflow', '');
    }

    // 广告函数
    function vdvertise(ad) {
      if (!ad) { return }
      console.log('广告内容--->', ad);
      let close = ad.imgbaiLink
      //左侧广告(PC显示)
      if (ad.left == 1 && ad.leftad && ad.leftad.length > 0 && wztkj_ScreenWidth > 750) {
        $("body").append(`
          <!-- 左侧内容 -->
          <div class="wztkj_guanggao_left-side">
          </div>
        `);

        let adstr = '';
        ad.leftad.filter((item) => {
          if (item.pic != '') {
            adstr += `
              <div class="wztkj_guanggao_a wztkj_advertisement_mark">
                <a class="wztkj_guanggao_a" href="${item.link}">
                  <img src="${item.pic}" alt="左侧图片1" />
                </a>
                <img class="wztkj_posi_Closeicon" src="${close}" alt="关闭" title="关闭广告" />
              </div>
            `;
          }
        });

        $(".wztkj_guanggao_left-side").append(adstr);
      }

      //右侧广告(PC显示)
      if (ad.right == 1 && ad.rightad && ad.rightad.length > 0 && wztkj_ScreenWidth > 750) {
        let adstr = '';
        $("body").append(`
          <!-- 右侧内容 -->
          <div class="wztkj_guanggao_right-side">
          </div>
        `);

        ad.rightad.filter(item => {
          if (item.pic != '') {
            adstr += `
              <div class="wztkj_guanggao_a wztkj_advertisement_mark">
                <a class="wztkj_guanggao_a" href="${item.link}">
                  <img class="wztkj_posi_img" src="${item.pic}" alt="右侧图片1" />
                </a>
                <img src="${close}" alt="关闭" class="wztkj_posi_Closeicon" title="关闭广告" />
              </div>
            `;
          }
        });

        $(".wztkj_guanggao_right-side").append(adstr);
      }

      //关闭广告事件处理
      $(".wztkj_posi_Closeicon").click(function (e) {
        e.stopPropagation();
        $(this).parent().hide();
      });

      $('.wztkj_posi_img').click(function (e) {
        e.stopPropagation();
      });

      // 底部广告和移动端广告
      boot(ad);
      mobilePage(ad);
    }

    // 底部广告处理
    function boot(ad) {

      if (!ad) { return }
      let close = ad.imgLink
      // 显示时间控制逻辑
      // if (shouldSkipAd(ad.bottad.showtime, 'BF')) {
      //   return;
      // }
      // 循环执行，所以添加的
      if (ad.bottad.showtime == '6') {
        try {
          const value = localStorage.getItem('TAN_BFSHOWTIME6');
          if (value == '6') {
            return
          }
        } catch (error) { }
        localStorage.setItem('TAN_BFSHOWTIME6', '6')
      }
      // 24小时执行一次
      if (ad.bottad.showtime == '5') {
        let token = false;
        try {
          token = tempStorage.get('TAN_BFSHOWTIME5');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_BFSHOWTIME5'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_BFSHOWTIME5'));
        }
        tempStorage.set('TAN_BFSHOWTIME5', 'true', 24);
      }
      // 12小时执行一次
      if (ad.bottad.showtime == '4') {
        let token = false;
        try {
          token = tempStorage.get('TAN_BFSHOWTIME4');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_BFSHOWTIME4'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_BFSHOWTIME4'));
        }
        tempStorage.set('TAN_BFSHOWTIME4', 'true', 12);
      }

      // 6小时执行一次
      if (ad.bottad.showtime == '3') {
        let token = false;
        try {
          token = tempStorage.get('TAN_BFSHOWTIME3');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_BFSHOWTIME3'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_BFSHOWTIME3'));
        }
        tempStorage.set('TAN_BFSHOWTIME3', 'true', 6);
      }
      // 3小时执行一次
      if (ad.bottad.showtime == '2') {
        let token = false;
        try {
          token = tempStorage.get('TAN_BFSHOWTIME2');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_BFSHOWTIME2'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_BFSHOWTIME2'));
        }
      }
      // 1小时执行一次
      if (ad.bottad.showtime == '1') {
        let token = false;
        try {
          token = tempStorage.get('TAN_BFSHOWTIME1');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_BFSHOWTIME1'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_BFSHOWTIME1'));
        }
        tempStorage.set('TAN_BFSHOWTIME1', 'true', 1);
      }

      //底部广告
      if (ad.bottom == 1 && ad.bottad.pic !== "" && wztkj_ScreenWidth <= 750) {
        $("body").append(` 
          <div class="wztkj_guanggao_footer_box">
            <a href="${ad.bottad.link}" class="f_b_img wztkj_advertisement_mark">
              <img class="f_b_imgBack" src="${ad.bottad.pic}" alt="底部广告" />
              <div class="f_b_i_close">
                <span><span id="wztkj_close_title">${ad.bottad.time}</span> 秒后关闭广告</span>
                <img class="f_b_i_close_img" src="${close}" alt="关闭图标" />
              </div>
            </a>
          </div>
        `);

        footerAdvertisingFun = () => {
          const footerAdElement = $('#wztkj_close_title');
          let footerAdElementTime = ad.bottad.time;

          const footerAdElementTimer = setInterval(() => {
            footerAdElementTime--;
            footerAdElement.text(footerAdElementTime);

            if (footerAdElementTime == 0) {
              $('.wztkj_guanggao_footer_box').hide();
              clearInterval(footerAdElementTimer);
            }
          }, 1000);

          $('.f_b_i_close_img').click(function (e) {
            e.preventDefault();
            $('.wztkj_guanggao_footer_box').hide();
            clearInterval(footerAdElementTimer);
          });
        };

        //底部广告在用户开启了开屏广告时，会在开屏广告结束时调用
        if (ad.mobile !== 1) {
          $(".f_b_imgBack").on("load", footerAdvertisingFun);
        }
      }
    }

    // 手机版弹窗广告(开屏广告)
    function mobilePage(ad) {
      if (!ad) { return }
      let close = ad.imgLink
      // 显示时间控制逻辑
      // if (shouldSkipAd(ad.mobtad.showtime, 'MO')) {
      //   return;
      // }

      // 循环执行，所以添加的
      if (ad.mobtad.showtime == '6') {
        try {
          const value = localStorage.getItem('TAN_MOSHOWTIME6');
          if (value == '6') {
            return
          }
        } catch (error) { }
        localStorage.setItem('TAN_MOSHOWTIME6', '6')
      }
      // 24小时执行一次
      if (ad.mobtad.showtime == '5') {
        let token = false;
        try {
          token = tempStorage.get('TAN_MOSHOWTIME5');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_MOSHOWTIME5'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_MOSHOWTIME5'));
        }
        tempStorage.set('TAN_MOSHOWTIME5', 'true', 24);
      }
      // 12小时执行一次
      if (ad.mobtad.showtime == '4') {
        let token = false;
        try {
          token = tempStorage.get('TAN_MOSHOWTIME4');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_MOSHOWTIME4'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_MOSHOWTIME4'));
        }
        tempStorage.set('TAN_MOSHOWTIME4', 'true', 12);
      }

      // 6小时执行一次
      if (ad.mobtad.showtime == '3') {
        let token = false;
        try {
          token = tempStorage.get('TAN_MOSHOWTIME3');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_MOSHOWTIME3'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_MOSHOWTIME3'));
        }
        tempStorage.set('TAN_MOSHOWTIME3', 'true', 6);
      }
      // 3小时执行一次
      if (ad.mobtad.showtime == '2') {
        let token = false;
        try {
          token = tempStorage.get('TAN_MOSHOWTIME2');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_MOSHOWTIME2'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_MOSHOWTIME2'));
        }
      }
      // 1小时执行一次
      if (ad.mobtad.showtime == '1') {
        let token = false;
        try {
          token = tempStorage.get('TAN_MOSHOWTIME1');
          if (token == 'true') {
            console.log(tempStorage.get('TAN_MOSHOWTIME1'), '111111111');
            return
          }
        } catch (error) {
          console.log('存储了Token:', tempStorage.get('TAN_MOSHOWTIME1'));
        }
        tempStorage.set('TAN_MOSHOWTIME1', 'true', 1);
      }

      if (ad.mobile == 1 && ad.mobtad.pic !== "" && wztkj_ScreenWidth <= 750) {
        $("body").append(` 
          <div class="wztkj_guanggao_mobile_box">
            <div class="wztkj_guanggao_mobile_shade"></div>
            <div class="wztkj_guanggao_mobile_con">
              <a href="${ad.mobtad.link}">
                <img class="w_g_m_back" src="${ad.mobtad.pic}" alt="开屏广告" />
                <div class="w_g_m_top" style="display:none">
                  <span><span id="wztkj_guanggao_mobile_time">${ad.mobtad.time}</span>秒后关闭广告</span>
                  <img class="w_g_close" src="${close}" alt="关闭图标" />
                </div>
              </a>
            </div>
          </div>
        `);

        $(".w_g_m_back").on("load", function () {
          stopRoll(); //显示开屏广告的同时禁用滚动条
          $(".w_g_m_top").css("display", "flex");

          // 显示时间倒计时
          let mobileAdElementTime = ad.mobtad.time;
          const mobileAdElement = $('#wztkj_guanggao_mobile_time');

          const mobileAdElementTimer = setInterval(() => {
            mobileAdElementTime--;
            mobileAdElement.text(mobileAdElementTime);

            if (mobileAdElementTime == 0) {
              $('.wztkj_guanggao_mobile_box').hide();
              clearInterval(mobileAdElementTimer);
              openRoll(); //恢复滚动

              if (ad.bottom == 1) {
                footerAdvertisingFun(); //结束后调用底部广告
              }
            }
          }, 1000);

          $('.wztkj_guanggao_mobile_box .w_g_close').click(function (e) {
            e.preventDefault();
            $('.wztkj_guanggao_mobile_box').hide();
            clearInterval(mobileAdElementTimer);
            openRoll(); //恢复滚动

            if (ad.bottom == 1) {
              footerAdvertisingFun(); //结束后调用底部广告
            }
          });
        });
      }
    }

    // // 广告显示时间控制函数
    // function shouldSkipAd(showtime, prefix) {
    //   if (!showtime) return false;

    //   console.log(showtime);
    //   const storageKey = `TAN_${prefix}SHOWTIME${showtime}`;

    //   try {
    //     if (showtime == '6') {
    //       const value = localStorage.getItem(storageKey);
    //       if (value == '6') return true;
    //       localStorage.setItem(storageKey, '6');
    //       return false;
    //     }

    //     // 使用tempStorage的情况
    //     let token = tempStorage.get(storageKey);
    //     if (token == 'true') {
    //       console.log(tempStorage.get(storageKey), '广告已显示，跳过');
    //       return true;
    //     }

    //     // 设置新的存储值
    //     let hours = parseInt(showtime);
    //     if (hours >= 1 && hours <= 24) {
    //       tempStorage.set(storageKey, 'true', hours);
    //     }

    //     return false;
    //   } catch (error) {
    //     console.log('存储操作出错:', error);
    //     return false;
    //   }
    // }

    // 检查广告数据是否存在并执行渲染
    if (typeof advertData !== 'undefined' && advertData) {
      ad = JSON.parse(advertData)
      vdvertise(ad.ad);
    }
  });


}