<template>
  <div>
    <div v-if="page2">
      <div id="book" class="book" >
        <div class="page1">
          <img src="/public/static/book.jpg" style="width: 100%;height: 100%;">
        </div>
        <div class="page2"></div>
      </div>
    </div>
    <!-- <div v-if="lo"
      style="position:fixed;right: 0;left:0;width: 100%;z-index: 1500;margin: 0 auto;text-align: center;top: 40%">
      <n-spin size="small" stroke="#999999"></n-spin>
    </div> -->
    <input type="hidden" name="activeDate" id="activeDate" value="" />
    <input type="hidden" id="dataIndex" :value="dataIndex" />
    <div class="contWrapper" v-if="data != ''">
      <div class="headBox">
        <div class="curDate">{{ datetime }}</div>
        <div class="headTitle">{{ data[dataIndex].bm_name }}</div>
      </div>
      <!-- Swiper 报纸轮播区域 -->
      <div
        class="swiper-container newpaper swiper-container-initialized swiper-container-horizontal swiper-container-ios">

        <div class="swiper-wrapper" style="transform: translate3d(0px, 0px, 0px);">
          <!-- 遍历版面列表 开始 -->
          <div v-for="(item, index) in data" class="swiper-slide" style="width: 1884px;">
            <div class="imgBoxCont">
              <img class="pichmask" :src="item.bm_img" style="z-index: 999; opacity: 0;">
              <div class="pinch-zoom-container"
                style="overflow: hidden; position: absolute; top: 0px; height: 2724.26px;">
                <div class="pinch-zoom"
                  style="transform-origin: 0% 0%; position: absolute; transform: scale(0.628, 0.628) translate(0px, 0px);">
                  <img class="paperMap" :src="item.bm_img" usemap="#PagetupMap10" style="z-index: 999; opacity: 1;">
                  <map name="PagetupMap10" style="z-index:999;">
                    <area v-for="(area, idx) in data[dataIndex].news" :key="area.id" class="paperarea"
                      @click="openNews(area)" :coords="area.coordinate" shape="rect" :title="area.new_name">
                  </map>
                </div>
              </div>
            </div>
          </div>
          <!-- 遍历版面列表 结束 -->
        </div>
        <span class="swiper-notification" aria-live="assertive" aria-atomic="true"></span>
      </div>

      <!-- 底部按钮 -->
      <div class="footerWrap" style="z-index: 10">
        <div class="item">
          <img src="/public/static/banmian.png" alt="">
          <div class="text layoutBtn">版面</div>
          <!-- 三角形 -->
          <!-- <div class="articletips"></div> -->
          <!-- <div class="articletipsDown"></div> -->
        </div>
        <div class="item">
          <img src="/public/static/mulu.png" alt="">
          <div class="text articleBtn">目录</div>
          <!-- 三角形 -->
          <!-- <div class="articletips"></div> -->
        </div>
        <div class="item">
          <img src="/public/static/wangqi.png" alt="">
          <div class="text datetimeBtn">往期</div>
          <!-- 三角形 -->
        </div>
      </div>
      <!-- //分享按钮 -->
      <div class="synthesis" style="z-index: 10">
        <div class="item">
          <img src="/public/static/fenxiang.png" alt="">
          <div class="text">分享</div>
        </div>
        <!--<div class="dropup">
            <button class="btn btn-default dropdown-toggle shareBtn" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <img src="../../../image20/fenxiang.png" alt="">分享
              <span class="caret"></span>
            </button>
            <ul id="synthesisOpt" class="dropdown-menu shareBtnDropdown"  aria-labelledby="dropdownMenu2">
              <li><a href="#">单版分享</a></li>
              <li class="divider"></li>
              <li><a href="#">多版分享</a></li>
            </ul>
          </div>-->
      </div>

      <div class="zonglan" @click="openZongLan">
        <img src="/public/static/zonglan1.png" alt="">
      </div>
      <!-- 版面列表2 -->
      <div class="layoutList layoutStyleTwo">
        <h2>版面导航</h2>
        <div class="listWrapBox">
          <div v-for="(item, index) in data" :class="['listWrap', index == dataIndex ? 'action' : '']"
            @click.prevent="openBm(index)">
            <img :src="item.bm_img" alt="">
            <a class="" href="#">{{ item.bm_name }}</a>
          </div>
        </div>
      </div>
      <div class="articletips"></div>

      <div class="articleList">
        <div class="listWrap">
          <!-- 文章目录 -->

          <div class="item itemActive">
            <div class="title">
              <h1>{{ data[dataIndex].bm_name }}</h1>
              <span class="tips"></span>
            </div>
            <div class="listTitle">
              <a v-for="(item, index) in data[dataIndex].news" @click.prevent="openNews(item)" class="articleItem"
                href="#">{{ item.new_name }}</a>
            </div>
          </div>
        </div>
        <!-- 下面的三角形 -->
        <div class="articletips"></div>
      </div>
      <!-- 日历层 -->
      <input type="text" class="form_date">
      <!-- 取消按钮 -->
      <div class="cancelBox">
        <button class="cancelBtn">取消</button>
      </div>
      <!-- 下载层 -->
      <div class="synthPage"></div>
      <!-- 遮罩 -->
      <div class="mask"></div>
    </div>
    <div style="display:none;" id="publishVersion">3</div>
    <div style="display:none;" id="publishDateTime">{{ datetime }}</div>
    <table style="display: none;">
      <tbody>
        <tr>
          <td>
            <span id="NewsPaperName">固始日报</span> <span id="NewsEditionName">头版</span>
            <span id="NewsEditionNumber">01</span> <span id="NewsArticleTitle"></span>
            <span id="NewsArticleAuthor"></span><span id="NewsArticleTime">{{ datetimeNumber }}</span>
            <span id="Class">1</span> <span id="jbdata">{{ datetime }}</span>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="datetimepicker datetimepicker-dropdown-top-right dropdown-menu">
    </div>

  </div>
</template>

<script>
import axios from 'axios';
import $ from 'jquery';
import jquery from 'jquery'
import router from "@/router/routes";
import turn from '@/api/turn.js'
export default {
  data() {
    return {
      page2: true,
      data: '',
      dataIndex: 0,
      lo: true,
      datetime: '',
      datetimeNumber: '',
      typeId: '',
      typeList: [],
      dataInfo: {}
    }
  },
  watch: {
    dataIndex(newVal, oldVal) {
      this.dataIndex = newVal;
      console.log('dataIndex changed from', oldVal, 'to', newVal);
      // 在这里添加你需要执行的逻辑
    }
  },
  // created() {
  //   window.addEventListener('popstate', this.handlePopState);
  // },
  // beforeDestroy() {
  //   // 组件销毁时移除事件监听器
  //   window.removeEventListener('popstate', this.handlePopState);
  // },
  // activated() {
  //   console.log('Component activated+++++++++++++++');
  //   // 在这里执行返回页面时需要的操作
  // },
  // deactivated() {
  //   console.log('Component deactivated++++++++++++++++');
  // },
  mounted() {
    var page=sessionStorage.getItem('page');
    if(page==1){
        this.page2=false;
    }else{
      this.onTurn();
    }
    
    //window.addEventListener('popstate', this.handlePopState);
    console.log(this.data);
    if (this.$route.query) {
      if (this.$route.query.date) {
        $('#activeDate').val(this.$route.query.date);
        var time = new Date(this.$route.query.date);
        var initYear = time.getFullYear();
        var initMonth = String(time.getMonth() + 1).padStart(2, '0');
        var initDay = String(time.getDate()).padStart(2, '0');
        sessionStorage.setItem("year", initYear);
        sessionStorage.setItem("month", initMonth);
        sessionStorage.setItem("day", initDay);
      }
      if (this.$route.query.index) {
        this.dataIndex = this.$route.query.index;
      }
      if (typeof (this.$route.query.id) != 'undefined') {
        router.push('/info?id=' + this.$route.query.id);
      }
    }
    this.getCurrentDateMaxDay();
    //获取当前日期
    window.addEventListener('dataIndexChanged', (event) => {
      console.log('dataIndex changed to', event);
      this.dataIndex = event.detail; // 更新 dataIndex
      sessionStorage.setItem("index", event.detail);
      //document.title = '《今日固始》-' + this.data[event.detail].bm_name;
    });
    this.hideAll();
    setTimeout(() => {
      this.lo = false;
    }, 1500);

  },
  methods: {
    hideAll() {
      $('.layoutList').removeClass('active');
      $('.footerWrap .item .text').removeClass('active')
      $('.mask').removeClass('active');
      $('.articleList').removeClass('active');
      $('.exareBox').removeClass('active')
      $(".cancelBox").hide()
    },
    openBm(d) {
      this.dataIndex = d;
      sessionStorage.setItem("index", d);
      sessionStorage.setItem("H5Index", d);
      // document.title = '《今日固始》-' + this.data[d].bm_name;
      window.swiper.slideTo(d)
      this.hideAll();
    },
    openNews(d) {
      console.log(d);
      // sessionStorage.setItem("index", this.dataIndex);
      // sessionStorage.setItem("newInfo", JSON.stringify(this.data[this.dataIndex].news[index]));
      //
      // var activeDate = $('#activeDate').val();
      // var storageTimeYear = sessionStorage.getItem("year");
      // var storageTimeMonth = sessionStorage.getItem("month");
      // var storageTimeDay = sessionStorage.getItem("day");
      // if (storageTimeYear && storageTimeMonth && storageTimeDay) {
      //   activeDate = storageTimeYear + "-" + storageTimeMonth + "-" + storageTimeDay;
      // } else {
      //   var time = activeDate ? new Date(activeDate) : new Date();
      //   var initYear = time.getFullYear();
      //   var initMonth = time.getMonth() + 1;
      //   var initDay = String(time.getDate()).padStart(2, '0');
      //   activeDate = initYear + "-" + initMonth + "-" + initDay;
      // }
      router.push('/info?id=' + d.id)
    },
    removeScripts() {
      const scripts = document.querySelectorAll('script[src^="/h5/public/static/js/"]');
      const styles = document.querySelectorAll('style[src^="/public/static/css/"]');
      styles.forEach(styles => styles.remove());
      scripts.forEach(script => script.remove());
    },
    openZongLan() {
      //window.addEventListener('popstate', this.handlePopState);
      var info = this.dataInfo;
      //this.removeScripts();
      sessionStorage.setItem("ListShow", 1);
      router.push('/list?time=' + info.datetime);
    },
    getTypeList() {
      axios.post("https://jinrigushitwo.gushitv.com/api/dzb/type/index")
        .then(response => {
          console.log(response);
          this.typeList = response.data.data;
          var typeId = sessionStorage.getItem("typeId");
          if (typeId) {
            this.typeId = typeId;
          } else {
            this.typeId = response.data.data[0].id;
          }
          this.getCurrentDateMaxDay();
        })
        .catch(error => console.error('Error loading the JSON file:', error))
    },
    getCurrentDateMaxDay() {
      var activeDate = $('input[name="activeDate"]').val();
      var querySatus = '';
      var storageTimeYear = sessionStorage.getItem("year");
      var storageTimeMonth = sessionStorage.getItem("month");
      var storageTimeDay = sessionStorage.getItem("day");
      if (storageTimeYear && storageTimeMonth && storageTimeDay) {
        activeDate = storageTimeYear + "-" + this.getMd(storageTimeMonth) + '-' + this.getMd(storageTimeDay);
      }
      if (typeof (this.$route.query.status) != 'undefined') {
        querySatus = this.$route.query.status;
      }
      console.log(activeDate);
      axios.post("https://jinrigushitwo.gushitv.com/api/dzb/date/index", { date: activeDate, status: querySatus })
        .then(response => {
          // 使用导入的数据
          var resIndex = response.data.data.length - 1;
          console.log('********', resIndex);
          sessionStorage.setItem('DateListH5', JSON.stringify(response.data.data));
          sessionStorage.setItem('DateIndexH5', resIndex);
          console.log(response.data.data[resIndex]);
          if (activeDate == '') {
            this.datetime = this.getCurrentDateFormatted(response.data.data[resIndex].datetime);
            document.title = '《今日固始》电子版-' + this.datetime;
          } else {
            document.title = '《今日固始》电子版-' + storageTimeYear + "年" + this.getMd(storageTimeMonth) + "月" + this.getMd(storageTimeDay) + "日";
          }

          this.getBm();
        })
        .catch(error => console.error('Error loading the JSON file:', error))
    },
    getMd(num) {
      return ('0' + num).slice(-2);
    },
    getBm() {
      var list = JSON.parse(sessionStorage.getItem('DateListH5'));
      var storageTimeYear = sessionStorage.getItem("year");
      var storageTimeMonth = sessionStorage.getItem("month");
      var storageTimeDay = sessionStorage.getItem("day");
      if (storageTimeYear && storageTimeMonth && storageTimeDay) {
        var activeDate = storageTimeYear + "-" + this.getMd(storageTimeMonth) + '-' + this.getMd(storageTimeDay);
        var targetData = list.find(item => item.datetime == activeDate);
      } else {
        var index = sessionStorage.getItem('DateIndexH5');
        var targetData = list[index];
      }
      var id = targetData.id;
      $('input[name="activeDate"]').val(targetData.datetime);
      this.datetime = this.getCurrentDateFormatted(targetData.datetime);
      this.datetimeNumber = targetData.datetime;
      this.dataInfo = targetData;
      axios.post("https://jinrigushitwo.gushitv.com/api/dzb/bm/index", { date_id: id })
        .then(response => {
          console.log(response);
          this.data = response.data.data;
          //document.title = '《今日固始》-' + this.data[this.dataIndex].bm_name;
          // if(typeof (swiper) == 'undefined'){
          //   this.getScript();
          // }
          this.getScript();
        })
        .catch(error => console.error('Error loading the JSON file:', error))
    },
    getCurrentDateFormatted(d) {
      const date = new Date(d);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}年${month}月${day}日`;
    },
    getScript() {
      this.loadScripts([
        '/h5/public/static/js/jquery.min.js',
        '/h5/public/static/js/jquery.mobile.custom.min.js',
        '/h5/public/static/js/swiper.min.js',
        '/h5/public/static/js/jquery.rwdImageMaps.min.js',
        '/h5/public/static/js/bootstrap.min.js',
        '/h5/public/static/js/bootstrap-datetimepicker.min.js',
        '/h5/public/static/js/bootstrap-datetimepicker.zh-CN.js',
        '/h5/public/static/js/jquery.qrcode.min.js',
        '/h5/public/static/js/pinchzoom.min.js',
        '/h5/public/static/js/html2canvas.min.js',
        '/h5/public/static/js/index.js',
        '/h5/public/static/js/qfstatH5.js',
        '/h5/public/static/js/posterShare.js',
        '/h5/public/static/js/bigHaiBao.js'
      ]).then(() => {
        if (window.swiper) {
          window.swiper.slideTo(this.dataIndex);
        } else {
          setTimeout(() => {
            window.swiper.slideTo(this.dataIndex);
          }, 500);
        }
      });
    },
    loadScripts(urls) {
      const loadScript = (url) => {
        return new Promise((resolve) => {
          const script = document.createElement('script');
          script.src = url;
          script.type = 'text/javascript';
          script.onload = resolve; // 确保脚本加载完成后再继续
          document.head.appendChild(script);
        });
      };

      // 依次加载所有脚本
      // 依次加载所有脚本并返回一个 Promise
      return urls.reduce((promise, url) => {
        return promise.then(() => loadScript(url));
      }, Promise.resolve());
    },

    onTurn() {
      this.$nextTick(() => {
        $('#book').turn({
          acceleration: true, //启用硬件加速,移动端有效
          display: 'single', //显示：single=单页，double=双页，默认双页
          duration: 800, // 翻页撒开鼠标，页面的延迟
          elevation: 1000,
          gradients: true, // 折叠处的光泽渐变，主要体现翻页的立体感、真实感
          autoCenter: true, //
          turnCorners: 'br', // 设置可翻页的页角(都试过了，乱写 4个角都能出发卷起)， bl,br   tl,tr   bl,tr 
          height: '100vh', //页面高度
          width: '100%' //翻书范围宽度，总宽度
        });
        // 添加自动翻页功能
        setTimeout(() => {
          this.startAutoTurn();
        }, 1500)

      })
    },
    // 添加自动翻页相关方法
    startAutoTurn() {
      const book = $('#book');
      book.turn('next');
      setTimeout(() => {
        this.page2 = false;
        sessionStorage.setItem('page',1);
      }, 1000)

    },
  }
}
</script>
<style src="/public/static/css/swiper.min.css"></style>
<style src="/public/static/css/bootstrap.min.css"></style>
<style src="/public/static/css/bootstrap-datetimepicker.min.css"></style>
<style src="/public/static/css/global.css"></style>
<style src="/public/static/css/index.css"></style>
<style scoped>
.book {
  position: fixed !important;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
}

/* .page1 {
  background-image: url(/public/static/book.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
} */

.page2 {
  background: transparent;
}

#_copy {
  align-items: center;
  background: #4494d5;
  border-radius: 3px;
  color: #fff;
  cursor: pointer;
  display: flex;
  font-size: 13px;
  height: 30px;
  justify-content: center;
  position: absolute;
  width: 60px;
  z-index: 1000
}

#select-tooltip,
#sfModal,
.modal-backdrop,
div[id^=reader-helper] {
  display: none !important
}

.modal-open {
  overflow: auto !important
}

._sf_adjust_body {
  padding-right: 0 !important
}

.super_copy_btns_div {
  position: fixed;
  width: 154px;
  left: 10px;
  top: 45%;
  background: #e7f1ff;
  border: 2px solid #4595d5;
  font-weight: 600;
  border-radius: 2px;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
  z-index: 5000
}

.super_copy_btns_logo {
  width: 100%;
  background: #4595d5;
  text-align: center;
  font-size: 12px;
  color: #e7f1ff;
  line-height: 30px;
  height: 30px
}

.super_copy_btns_btn {
  display: block;
  width: 128px;
  height: 28px;
  background: #7f5711;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
  border: 0;
  outline: 0;
  margin: 8px auto;
  font-weight: 700;
  cursor: pointer;
  opacity: .9
}

.super_copy_btns_btn:hover {
  opacity: .8
}

.super_copy_btns_btn:active {
  opacity: 1
}
</style>
