<template>
  <div class="map-wrapper">
    <div class="map-content">
      <!-- 左边图书馆基本信息 -->
      <div class="lib-info">
        <div class="database-title">{{ libCurrent && libCurrent.name }}</div>
        <div class="lib-content">
          <div style="width: 5.175rem; height: 3rem; overflow: hidden;">
            <swiper v-if="swiperOption" :key="swiperKey" ref="mySwiper" class="swiperLib" :options="swiperOption">
              <swiper-slide v-for="(item,index) in displayedImages" :key="index">
                <div class="book-img" style="width: 100%; height: 3rem;">
                  <img :src="item.cover" :onerror="defaultImg" style="width: 100%;">
                </div>
              </swiper-slide>
              <!-- 标页码 -->
              <div slot="pagination" class="swiper-pagination" />
            </swiper>
          </div>
          <ul class="lib-cont-item lib-cont01">
            <li>
              <img src="@/assets/images/map_18.png" alt="">
              <p>
                <span>藏书量</span>
                <span>{{ libCurrent && libCurrent.GCL }}<i>本</i></span>
              </p>
            </li>
            <li>
              <img src="@/assets/images/map_20.png" alt="">
              <p>
                <span>办证量</span>
                <span>{{ libCurrent && (libCurrent.countCard !== undefined ? libCurrent.countCard : libCurrent.readerIdNum) }}<i>人</i></span>
              </p>
            </li>
          </ul>
          <ul class="lib-cont-item lib-cont02">
            <li>
              <img src="@/assets/images/map_28.png" alt="">
              <p>
                <span>占地面积</span>
                <span>{{ libCurrent && libCurrent.occupationArea }}<i>平方米</i></span>
              </p>
            </li>
          </ul>
          <div ref="scrollInfo" class="scroll-container">
            <div ref="marquee" class="lib-text" v-html="libCurrent && libCurrent.explains" />
          </div>
        </div>
      </div>
      <!-- map -->
      <div ref="chart" style="width: 920px; height: 924px;  z-index: 999; border:1px solid rgba(0, 0, 0, 0);" />
      <div class="map-hx-bg">
        <div class="map-hx-small" />
        <div class="map-hx-big" />
      </div>
      <!-- 右边排行榜 -->
      <div class="read-num">
        <div class="database-title">读者统计</div>
        <div class="online">
          <p>本年累计办证人数</p>
          <p class="num"><span>{{ cardTotal }}</span><i>人</i></p>
        </div>
        <div class="lending-ranking">
          <h5>借阅Top10</h5>
          <div class="ranking-cont">
            <ul class="ranking-title">
              <li style="width: 0.8rem;">排名</li>
              <li style="width: 1.25rem; text-align: left; ">姓名</li>
              <li style="flex:1;" />
              <li style="width: 1.75rem; text-align: right; padding-right: .25rem;">借阅次数</li>
            </ul>
            <ul class="ranking-list">
              <li v-for="(item,index) in rankingWithPercentage" :key="index" :class="{ 'hovered': index === currentHover }">
                <div style="width: 1rem; color: #79B8FF;" :class="[{'ranking-num1':index===0},{'ranking-num2':index===1},{'ranking-num3':index===2}]">{{ index>=3 ? index+1 : null }}</div>
                <div style="width: 1.25rem; text-align: left; ">{{ item.RDNAME }}</div>
                <div class="ranking-progress" style="flex:1; align-self: center;">
                  <el-progress :percentage="item.percentage" :stroke-width="8" :show-text="false" color="#009afb" />
                </div>
                <div style="width: 1.75rem; text-align: right; padding-right: .25rem;">{{ item.TOTALNUM }}<i>次</i></div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { FetchLibBookTotal, FetchUsertotal, FetchLibcodeDetails, FetchReadRanking, FetchLendingTotal } from '@/api/library'
// import mapJson from '@/assets/json/dxh.json'
// import libJson from '@/assets/json/lib.json'
import { debounce } from 'lodash' // js工具类,按需加载
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import { pageCrud } from '../mixins/index.js'

export default {
  name: 'Map',
  components: {
    swiper, swiperSlide
  },
  mixins: [pageCrud],
  data() {
    return {
      currentHover: -1,
      timeTicket: null,
      defaultImg: 'this.src="' + require('@/assets/images/default-img.png') + '"',
      count: 0,
      len: 1, // 轮播数组的长度， 通过 count % len 可以得到[0, len-1] 数组下标
      libALLNum: [],
      libInfoData: [],
      libIndex: 0,
      libCurrent: null,
      swiperKey: 1,
      currentMapIndex: 0,
      displayedImages: [],
      libImg: [],
      swiperOption: null,
      seriesData: [],
      mapImg: require('../../assets/images/map-bg2.png'),
      cardTotal: 0,
      rankingData: [],
      rankingWithPercentage: [],
      rankInterval: null,
      timer: null,
      position: 0,
      speed: 2,
      activatedBaseSetting: {}
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.swiper
    }
  },
  watch: {
    baseSetting: {
      handler(result) {
        if (!result) return

        this.activatedBaseSetting = result
        if (result.open_lib_appId && result.open_lib_secret && result.open_lib_http) {
          this.getLibBookTotal(this.activatedBaseSetting)
          this.getReadRanking(this.activatedBaseSetting)
          this.getLendingTotal(this.activatedBaseSetting)
        }
      },
      immediate: true
    }
  },
  beforeDestroy() {
    this.destroy()
  },
  created() {
  },
  activated() {
    // this.getLibBookTotal(this.activatedBaseSetting)
    if (this.rankingData.length !== 0) {
      this.currentHover = -1
      this.rankInterval = setInterval(() => {
        this.currentHover = (this.currentHover + 1) % this.rankingData.length
      }, 1000)
    }
    this.$nextTick(() => {
      window.addEventListener('resize', debounce(this.resize, 2000))
    })
  },
  deactivated() {
    this.destroy()
  },
  mounted() {
  },
  methods: {
    destroy() {
      window.removeEventListener('resize', this.resize)
      clearTimeout(this.timeTicket)
      clearInterval(this.rankInterval)
      clearInterval(this.timer)
      // localStorage.setItem('libIndexItem', this.libIndex)
      // localStorage.setItem('libCurrentItem', this.libCurrent)
      localStorage.setItem('countItem', this.count)

      this.rankInterval = null
      this.timer = null
      this.timeTicket = null
    },
    startScrolling() {
      this.$nextTick(() => {
        const containerHeight = this.$refs.scrollInfo.offsetHeight
        const contentHeight = this.$refs.marquee.offsetHeight
        // 设置 CSS 变量 --container-height，以便在 CSS 中使用
        this.$refs.marquee.parentElement.style.setProperty('--container-height', `${contentHeight + 30}px`)
        if (contentHeight > containerHeight) {
          this.$refs.marquee.classList.add('lib-animation')
        } else {
          this.$refs.marquee.classList.remove('lib-animation')
        }
      })
    },
    getReadRanking(result) {
      const currentDate = new Date() // 获取当前日期
      currentDate.setDate(currentDate.getDate() - 30) // 将当前日期减去30天
      const year = currentDate.getFullYear() // 获取年份
      const month = currentDate.getMonth() + 1 // 获取月份（注意月份从0开始，需要加1）
      const day = currentDate.getDate() // 获取日期
      const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`

      const params = {
        'libcode': this.libcode,
        'starttime': formattedDate,
        'endtime': this.getFormattedDate(new Date()),
        'rownum': 10,
        'nordtype': 'JXTSG_E',
        'thirdAppid': result.open_lib_appId.context,
        'thirdSecret': result.open_lib_secret.context,
        'thirdUrl': result.open_lib_http.context
      }

      FetchReadRanking(params).then(res => {
        const result = JSON.parse(res.data)

        if (result.success && result.resultlist.length > 0) {
          this.rankingData = result.resultlist.sort((a, b) => b.TOTALNUM - a.TOTALNUM).slice(0, 10)
          this.rankingDataComputed()

          this.rankInterval = setInterval(() => {
            this.currentHover = (this.currentHover + 1) % this.rankingData.length
          }, 1000)
        } else {
          this.rankingData = []
          if (this.rankInterval) {
            clearInterval(this.rankInterval)
            this.rankInterval = null
          }
        }
      }).catch(error => {
        console.error('Error', error)
        return null
      })
    },
    rankingDataComputed() {
      const firstPlaceNum = this.rankingData[0].TOTALNUM
      this.rankingWithPercentage = this.rankingData.map(item => {
        if (item.RDNAME.length === 2) {
          // 截取name 字符串截取第一个字符，
          item.RDNAME = item.RDNAME.substring(0, 1) + ' * '
        } else if (item.RDNAME.length === 3) {
          // 截取第一个和第三个字符
          item.RDNAME = item.RDNAME.substring(0, 1) + ' * ' + item.RDNAME.substring(2, 3)
        } else if (item.RDNAME.length > 3) {
          // 截取第一个和大于第4个字符
          item.RDNAME = item.RDNAME.substring(0, 1) + ' * ' + ' * ' + item.RDNAME.substring(3, item.RDNAME.length)
        }
        const percentage = (item.TOTALNUM / firstPlaceNum) * 100
        return { ...item, percentage }
      })
    },
    getLendingTotal(result) {
      const params = {
        'thirdAppid': result.open_lib_appId.context,
        'thirdSecret': result.open_lib_secret.context,
        'thirdUrl': result.open_lib_http.context
      }
      FetchLendingTotal(params).then(res => {
        const result = JSON.parse(res.data)
        if (result.success & result.resultlist.length !== 0) {
          // BZL_YEAR  本年办证人数
          this.cardTotal = result.resultlist.filter(item => item.LIBCODE !== '999').reduce((acc, obj) => acc + obj.BZL_YEAR, 0)
        } else {
          this.cardTotal = 0
        }
      }).catch(error => {
        console.error('Error', error)
      })
    },
    // 馆藏量
    getLibBookTotal(result) {
      const params = {
        'libcode': this.libcode,
        'starttime': '2000-01-01',
        'endtime': '2034-01-01',
        'thirdAppid': result.open_lib_appId.context,
        'thirdSecret': result.open_lib_secret.context,
        'thirdUrl': result.open_lib_http.context
      }
      FetchLibBookTotal(params).then(res => {
        const resultData = JSON.parse(res.data)
        console.log('馆藏量', resultData)
        if (resultData.success & resultData.resultlist.length !== 0) {
          // 目的拿到馆藏量
          this.libALLNum = resultData.resultlist
        } else {
          this.libALLNum = []
        }

        this.getUserTotal(result)
          .then(userTotals => {
            userTotals.forEach(userTotal => {
              console.log('userTotal', userTotal)
              const libCode = Object.keys(userTotal)[0]
              const count = userTotal[libCode]
              const foundItem = this.libALLNum.find(item => item.LIBCODE === libCode)
              if (foundItem) {
                foundItem.countCard = count
              }
            })
            this.getLibcodeDetails()
          })
          .catch(error => {
            console.error('Error', error)
            this.getLibcodeDetails()
          })
      }).catch(error => {
        console.error('Error', error)
        this.libALLNum = []
        this.getLibcodeDetails()
      })
    },
    // 左边办证量
    getTotalForLibcode(libcode, result) {
      const params = {
        'libcode': libcode,
        'startdate': '2000-01-01',
        'enddate': '2034-01-01',
        'isrdtype': 0,
        'thirdAppid': result.open_lib_appId.context,
        'thirdSecret': result.open_lib_secret.context,
        'thirdUrl': result.open_lib_http.context
      }
      return FetchUsertotal(params).then(res => {
        const result = JSON.parse(res.data)
        if (result.success && result.pagedata.length > 0) {
          return { [libcode]: result.pagedata[0].count }
        } else {
          throw new Error('Failed' + libcode)
        }
      }).catch(error => {
        console.error('Error' + libcode, error)
        return { [libcode]: 0 }
      })
    },
    getUserTotal(result) {
      const libraries = [this.libcode]
      const getTotalPromises = libraries.map(libcode => this.getTotalForLibcode(libcode, result))
      return Promise.all(getTotalPromises)
        .then(results => {
          return results
        })
        .catch(error => {
          console.error('Error', error)
          return 0
        })
    },
    // 分馆显示内容
    getLibcodeDetails() {
      const params = {
        'libcode': this.libcode
      }
      FetchLibcodeDetails(params).then(res => {
        // const result = JSON.parse(res.data)
        const result = res.data
        console.log('result', result)
        if (result.length !== 0) {
          // const libCode = {
          //   [this.libcode]: [114.133561, 30.641408]
          // }
          const libCode = {}
          result.forEach(library => {
            let key
            // 根据branchType确定键名：总馆用libcode，分馆用tcId
            if (library.branchType === 1) {
              key = library.libcode // 总馆
            } else if (library.branchType === 2) {
              key = library.tcId // 分馆
            }

            // 处理坐标，转换为数字类型（空值时默认为0）
            const x = library.mapX ? Number(library.mapX) : 0
            const y = library.mapY ? Number(library.mapY) : 0

            if (key) {
              libCode[key] = [x, y]
            }
          })
          console.log('分馆', libCode)

          const updatedLibraries = result.map(library => {
            const matchingData = this.libALLNum.find(item => item.LIBCODE === library.tcId)
            if (matchingData) {
              return {
                ...library,
                GCL: matchingData.GCL,
                sort: Object.keys(libCode).indexOf(library.tcId) + 1,
                coordinate: libCode[library.tcId],
                countCard: matchingData.countCard ? matchingData.countCard : 0
              }
            } else {
              return {
                ...library,
                GCL: 0,
                sort: Object.keys(libCode).indexOf(library.tcId) + 1,
                coordinate: libCode[library.tcId],
                countCard: 0
              }
            }
          }).sort((a, b) => a.sort - b.sort)

          this.libInfoData = updatedLibraries
          console.log('this.libInfoData', this.libInfoData)
          if (localStorage.getItem('countItem')) {
            this.count = parseInt(localStorage.getItem('countItem'))
          } else {
            this.count = 0
          }
          if (this.libInfoData.length !== 0) {
            this.initChart() // 初始化
            setTimeout(() => {
              this.updateChart() // 更新数据，散点轮播显示
              this.startScrolling()
              window.addEventListener('resize', debounce(this.resize, 2000)) // 使用事件捕获，由外层向内
            }, 300)
          }
        } else {
          this.libInfoData = []
        }
      }).catch(error => {
        console.error('Error', error)
      })
    },
    initChart() {
      this.$echarts.registerMap('map', this.baseSetting.map_data.context) // 注册map
      this.myChart = this.$echarts.init(this.$refs.chart) // echarts容器实例化

      var mapImg = document.createElement('img')
      mapImg.style.height = mapImg.height = mapImg.width = mapImg.style.width = '1px'
      mapImg.src = require('../../assets/images/map-bg2.png')

      const libJson = {}
      this.libInfoData.forEach(library => {
        const x = library.mapX ? Number(library.mapX) : (library.coordinate?.[0] || 0)
        const y = library.mapY ? Number(library.mapY) : (library.coordinate?.[1] || 0)
        libJson[library.name] = [x, y]
      })

      const mainLib = this.libInfoData.find(lib => lib.branchType === 1) || {}
      const mainLibName = mainLib.name || '总馆'

      const mainLibCoord = mainLib.mapX && mainLib.mapY
        ? [Number(mainLib.mapX), Number(mainLib.mapY)] : [0, 0]

      var XAData = this.libInfoData.map(item => {
        return [
          { name: mainLibName },
          { name: item.name, value: item.address }
        ]
      })

      var convertData = function(data) {
        var res = []
        for (var i = 0; i < data.length; i++) {
          var dataItem = data[i]
          var fromCoord = libJson[dataItem[0].name]
          var toCoord = libJson[dataItem[1].name]
          if (fromCoord && toCoord) {
            res.push({
              fromName: dataItem[0].name,
              toName: dataItem[1].name,
              coords: [fromCoord, toCoord],
              value: dataItem[1].value
            })
          }
        }
        return res
      }
      var series = [];
      [
        [mainLibName, XAData]
      ].forEach(function(item, i) {
        series.push(
          {
            name: item[0],
            type: 'effectScatter',
            symbol: 'image://' + require('@/assets/images/map_10.png'),
            symbolSize: [26, 20],
            coordinateSystem: 'geo',
            zlevel: 3,
            selectedMode: false,
            rippleEffect: {
              // brushType: 'stroke',
              color: 'transparent'
              // scale: 1.5
            },
            label: {
              normal: {
                show: true,
                position: 'right',
                formatter: ''
              }
            },
            itemStyle: {
              normal: {
                color: 'transparent',
                areaColor: 'transparent'
              },
              emphasis: {
                areaColor: '#2B91B7'
              }
            },
            tooltip: {
              show: true
            },
            data: item[1].map(function(dataItem) {
              return {
                name: dataItem[1].name,
                value: dataItem[1].name ? libJson[dataItem[1].name].concat([dataItem[1].value]) : '',
                place: dataItem[1].value
              }
            })
          },
          {
            name: item[0],
            type: 'lines',
            zlevel: 1,
            effect: {
              show: true,
              period: 6,
              trailLength: 0.7,
              color: 'red', // arrow箭头的颜色
              symbolSize: 3
            },
            lineStyle: {
              normal: {
                color: '#fff',
                width: 0,
                curveness: 0.2
              }
            },
            tooltip: {
              show: false
            },
            data: convertData(item[1])
          },
          {
            name: item[0],
            type: 'lines',
            zlevel: 2,
            symbol: ['none', 'arrow'],
            symbolSize: 10, // 固定箭头大小
            effect: {
              show: true,
              period: 6,
              trailLength: 0,
              symbol: 'arrow',
              symbolSize: 10 // 动态箭头大小
            },
            lineStyle: {
              normal: {
                color: '#fff',
                width: 1,
                opacity: 0.6,
                curveness: 0.2
              }
            },
            tooltip: {
              show: false
            },
            data: convertData(item[1])
          }
        )
      })

      this.seriesData = series
      const initOption = {
        baseOption: {
          // 提示框
          tooltip: {
            trigger: 'item',
            triggerOn: 'click',
            showContent: true, // 是否显示提示框浮层
            alwaysShowContent: true, // 是否一直显示提示框内容
            // hideDelay: 100, // 浮层隐藏的延迟
            enterable: 'mousemove|click',
            padding: [0, 0, 0, 0],
            backgroundColor: null,
            position: function(point, params, dom, rect, size) {
              const x = point[0] + 14
              const y = Math.max(point[1] - 164, 20)
              return [x, y]
            },
            formatter: (params, ticket, callback) => {
              if (params.seriesType === 'effectScatter') {
                const addressLine = params.data.place ? `<div class='place'>地址：${params.data.place}</div>` : ''
                return `<div class='tooltip-main' >
                        <div class='tooltip-line'></div>
                        <div class='tooltip-content'>
                          <div class='title'>${params.data.name}</div>
                         ${addressLine}
                        </div>
                      </div>`
              } else if (params.seriesType === 'lines') {
                return (
                  params.data.fromName +
                '>' +
                params.data.toName +
                '<br />' +
                params.data.value
                )
              } else {
                return params.name
              }
            }
          },
          // 设置geo坐标系
          geo: [
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '6%', // 距离顶部的位置，每层向下一个百分比
              left: '11%',
              roam: false, // 是否开启平游或缩放
              center: mainLibCoord,
              z: 6, // 可以看成是css的z-index，数字越大图层越高，我这里设置了5个，然后页面有点卡，根据实际需要来添加，3个其实就能看出效果了
              itemStyle: {
                areaColor: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: 'rgba(0,0,0,.1)'
                  }, {
                    offset: 0.8, color: 'rgba(59,143,248,.6)'
                  }],
                  global: false
                },
                borderColor: '#9ffcff',
                borderWidth: 1
              },
              emphasis: {
                itemStyle: {
                  areaColor: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(0,0,0,.1)'
                    }, {
                      offset: 0.8, color: 'rgba(59,143,248,.6)'
                    }],
                    global: false
                  } // 鼠标移上去时区域的颜色
                }
              },
              label: {
                emphasis: {
                  show: false,
                  color: '#fff'
                }
              },
              tooltip: {
                show: true
              }
            },
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '6%', // 距离顶部的位置，每层向下一个百分比
              left: '11%',
              roam: false, // 是否开启平游或缩放
              z: 5, // 可以看成是css的z-index，数字越大图层越高，我这里设置了5个，然后页面有点卡，根据实际需要来添加，3个其实就能看出效果了
              itemStyle: {
                areaColor: {
                  type: 'pattern',
                  image: mapImg,
                  repeat: 'repeat'
                }, // 每个图层的背景色，根据需要来调，由亮变暗，下面的几个颜色也一样
                borderColor: '#9ffcff',
                borderWidth: 3,
                shadowColor: '#4cd4eb',
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 0,
                emphasis: { // 地图悬停高亮样式
                  areaColor: {
                    type: 'pattern',
                    image: mapImg,
                    repeat: 'repeat'
                  }
                }
              },
              emphasis: {
                disabled: true,
                areaColor: '#01215c'
              },
              label: {
                emphasis: {
                  show: false,
                  color: '#fff'
                }
              },
              tooltip: {
                show: false
              }
            },
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '7%', // 根据自己需要来设置
              left: '10%',
              roam: false, // 是否开启平游或缩放
              z: 4, // 变小，也就是被压在下面
              itemStyle: {
                areaColor: '#05498f', // 记得改颜色
                borderColor: '#0296cf',
                borderWidth: 2,
                shadowColor: '#0296cf',
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 0,
                emphasis: { // 地图悬停高亮样式
                  disabled: true,
                  areaColor: '#05498f'
                }
              },
              tooltip: {
                show: false
              }
            },
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '9%', // 根据自己需要来设置
              left: '9%',
              roam: false,
              z: 3, // 变小，也就是被压在下面
              itemStyle: {
                areaColor: 'rgba(3,106,183,.5)', // 记得改颜色
                borderColor: '#025792',
                borderWidth: 2,
                shadowColor: '#025792',
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 0,
                emphasis: { // 地图悬停高亮样式
                  areaColor: 'rgba(3,106,183,.5)'
                }
              },
              tooltip: {
                show: false
              }
            },
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '11%', // 根据自己需要来设置
              left: '8%',
              roam: false,
              z: 2, // 变小，也就是被压在下面
              itemStyle: {
                areaColor: 'rgba(3,106,183,.2)', // 记得改颜色
                borderColor: '#195175',
                borderWidth: 1,
                shadowColor: '#0f4c74',
                shadowOffsetX: 0,
                shadowOffsetY: 4,
                shadowBlur: 10,
                emphasis: { // 地图悬停高亮样式
                  areaColor: 'rgba(3,106,183,.2)'
                }
              },
              tooltip: {
                show: false
              }
            },
            {
              map: 'map',
              aspectScale: 1,
              zoom: 1.1,
              top: '12%', // 根据自己需要来设置
              left: '10%',
              roam: false,
              z: 1, // 变小，也就是被压在下面
              itemStyle: {
                areaColor: 'rgba(0,0,0,.6)', // 记得改颜色
                borderColor: 'rgba(0,0,0,.6)',
                borderWidth: 2,
                shadowColor: 'rgba(0,0,0,.6)',
                shadowOffsetX: 0,
                shadowOffsetY: 4,
                shadowBlur: 10,
                emphasis: { // 地图悬停高亮样式
                  areaColor: 'rgba(0,0,0,.6)'
                }
              },
              tooltip: {
                show: false
              }
            }
          ],
          series: series
        },
        media: [
          {
            query: {
              maxWidth: 666
            },
            option: {
              tooltip: {
                position: function(point, params, dom, rect, size) {
                  return [point[0] + 10, point[1] - 122]
                }
              }
            }
          }
        ]
      }
      this.myChart.setOption(initOption)
      // setTimeout(() => {
      //   this.myChart.setOption(initOption)
      // }, 200)
    },
    updateChart() {
      this.len = this.seriesData[0].data.length // 此处设置的是需要轮播的次数
      // this.myChart.setOption(updateOption)
      this.libIndex = this.count % this.len
      this.libCurrent = this.libInfoData[this.libIndex]
      console.log('this.libIndex', this.libIndex)
      console.log('this.libCurrent22', this.libCurrent)
      this.initSwiper()
      this.updatePageWithData()
      this.autohover()
    },
    mouseMove() {
      // 当鼠标移入，终止轮播，高亮显示当前区域
      this.myChart.on('mouseover', (params) => {
        clearInterval(this.timeTicket)
        this.myChart.dispatchAction({
          type: 'downplay'
          // seriesIndex: 0
        })
        this.myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: params.dataIndex
        })
        this.myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: params.dataIndex
        })
      })
      // 当鼠标移出，轮播继续开始
      this.myChart.on('mouseout', this.autohover)
    },
    autohover() {
      // clearInterval(this.timeTicket)
      // this.timeTicket = setInterval(() => {
      // 1. 取消上次的高亮
      this.myChart.dispatchAction({
        type: 'downplay',
        seriesIndex: 0
      })
      // 2. 显示当前高亮
      this.myChart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: this.count % this.len
      })
      // 3. 显示提示框中的信息
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: this.count % this.len
      })
      // }, 2000)
    },
    resize() {
      this.myChart.resize()
    },
    // updatePageWithData() {
    //   this.displayedImages = []
    //   const linkSrc = process.env.NODE_ENV === 'production' ? window.g.ApiUrl : process.env.VUE_APP_BASE_API
    //   const params = {
    //     'branchId': this.libCurrent.id
    //   }
    //   FetchLibcodeResouceDetails(params).then(res => {
    //     const result = JSON.parse(res.data)
    //     this.displayedImages = result.map((item, index) => {
    //       if (item.filePath) {
    //         item.cover = linkSrc + '/downloadFile' + item.filePath
    //       } else {
    //         item.cover = ''
    //       }
    //       return item
    //     })
    //     this.currentMapIndex = 0
    //   }).catch(error => {
    //     console.error('Error', error)
    //   })
    // },
    updatePageWithData() {
      this.displayedImages = []
      if (this.libCurrent && this.libCurrent.promotions && this.libCurrent.promotions.length) {
        this.displayedImages = this.libCurrent.promotions.map((item, index) => ({
          id: item.id,
          cover: item.imgPath,
          sort: index + 1
        }))
      } else {
        this.displayedImages = []
      }
      // 重置当前图片索引
      this.currentMapIndex = 0
    },

    initSwiper() {
      // const _self = this
      this.swiperOption = {
        // loop: true,
        // initialSlide: 0,
        notNextTick: false, // notNextTick是一个组件自有属性，如果notNextTick设置为true，组件则不会通过NextTick来实例化swiper，也就意味着你可以在第一时间获取到swiper对象，假如你需要刚加载遍使用获取swiper对象来做什么事，那么这个属性一定要是true
        // slidesPerView: 3, // 数量
        // spaceBetween: 30, // 间距
        // slidesPerGroup: 1, // 分几组
        // 禁止滑动
        noSwiping: true,
        observer: true, // 开启动态检查器
        direction: 'horizontal', // 设置水平还是垂直vertical
        // grabCursor: true, //光标样式
        // setWrapperSize: true,
        // autoHeight: true,
        // centeredSlides: true,
        // paginationClickable: true,
        // keyboard: true, //键盘控制
        // mousewheelControl: true, //鼠标轮控制
        autoplay: {
          delay: 3000, // 自动切换的时间间隔，单位ms
          stopOnLastSlide: false, // 当切换到最后一个slide时停止自动切换
          disableOnInteraction: false // 用户操作swiper之后，是否禁止autoplay
          // reverseDirection: false, //开启反向自动轮播
          // waitForTransition: true, //等待过渡完毕。自动切换会在slide过渡完毕后才开始计时
        },
        // 显示分页
        pagination: {
          el: '.swiper-pagination',
          type: 'progressbar'
          // progressbarOpposite: true,
          // clickable: true // 允许分页点击跳转
        },
        on: {
          slideChangeTransitionEnd() {
            // _self.currentMapIndex = this.activeIndex
            // if (_self.currentMapIndex === _self.displayedImages.length - 1) {
            //   setTimeout(() => {
            //     if (_self.count === _self.libInfoData.length - 1) {
            //       _self.count = 0
            //       // _self.$parent.autoPagination(3)
            //     } else {
            //       _self.count++
            //     }
            //     _self.libIndex = _self.count % _self.len
            //     _self.libCurrent = _self.libInfoData[_self.libIndex]
            //     console.log('_self.count', _self.count)
            //     console.log('_self.libIndex', _self.libIndex)
            //     console.log('_self.libCurrent', _self.libCurrent)
            //     _self.updatePageWithData()
            //     _self.autohover()
            //     _self.startScrolling()
            //     _self.currentMapIndex = 0
            //   }, 3000)
            // }
          }
        }
      }
    }
  }
}

</script>

<style lang="scss" scoped>
@import "~@/assets/styles/index.scss";
</style>
