<template>
  <div class="content-main">
    <Search refs="searchRefs" search-type="noList" />
    <div class="box-style" style="margin: 30px 44px;">
      <div class="dataScreening-header">
        <h4 class="filter-header">架位总览</h4>
        <div class="bookshelf-area">
          <!--  <span class="bookshelf-area">{{ floorName }} - {{ regionName }} - {{ gridRow +'排' }}</span> -->
          <!-- <router-link :to="{ path: '/', query: {floorTabIndex: floorTabIndex }}">
            {{ floorName }}
          </router-link>
          <span>/</span>
          <router-link :to="{ path: '/regions', query: {regionTabIndex: regionTabIndex }}">
            {{ regionName }}
          </router-link>
          <span>/</span>
          <router-link :to="{ path: '/shelf', query: {tabIndex: tabIndex }}">
            {{ gridRow +'排' }}
          </router-link>
          <div class="double-click-btn"><span>点击左侧位置返回</span></div> -->
          <router-link :to="{ path: '/shelf', query: {tabIndex: tabIndex }}">
            <i class="iconfont icon-huifu" />返回
          </router-link>
        </div>
      </div>
      <div class="tab-content">
        <ul class="tab-nav">
          <li v-for="(item,index) in tabListData" :key="index" class="active-tab-nav">{{ item.name }}<i /></li>
        </ul>

        <div v-loading="shelfAllGridDataLoading" class="gird-data-book">
          <div v-for="(item,index) in shelfAllGridData" :key="index" class="gird-layer">
            <span class="gird-left-line" />
            <span class="gird-right-line" />
            <div class="layer-left">
              <div class="layer-left-book">
                <!-- <div
                v-for="(book,i) in item.books"
                :key="i"
                :class="['book-item', { 'red-active' : book.bookStatus === '错架'} ,{ 'blue-active' : book.bookStatus === '错序'}]"
                @touchstart="handleTouchStart(index, i, $event)"
                @touchmove="handleTouchMove(index, i, $event)"
                @touchend="handleTouchEnd(index, i, $event)"
              >
                <span class="book-name">{{ book.bookName }}</span>
              </div> -->
                <!-- @touchstart="handleTouchStart(index, i, book, $event)" -->
                <div :class="['swiper'+index,'rack-box-list']">
                  <div class="swiper-wrapper">
                    <div v-for="book in item.books" :key="book.id" :class="['list-item swiper-slide', { 'red-active' : book.bookStatus === '错架'} ,{ 'blue-active' : book.bookStatus === '错序'}]" @click="getBookDetaisByBookRecNo(book)">
                      <span class="book-name">{{ book.bookName }}</span>
                    </div>
                  </div>
                </div>
              </div>

            </div>
            <div class="layer-right-handle">
              <div class="layer-info-header">
                <h4>{{ item.gridName }}</h4>
              <!-- <span>2024-11-28 09:46</span> -->
              </div>
              <div class="layer-right-content">
                <div class="layer-tag-info">
                  <div class="tag-item tag-sort">错序：<i class="iconfont icon-zhuangtai2" /><p>{{ baseStockData.length !==0 && baseStockData[index].errorOrderNum }}</p><span>（{{ baseStockData.length !==0 && baseStockData[index].errorOrderProbo }}）</span></div>
                  <div class="tag-item tag-place">错架：<i class="iconfont icon-zhuangtai2" /><p>{{ baseStockData.length !==0 &&baseStockData[index].errorShelfNum }}</p><span>（{{ baseStockData.length !==0 && baseStockData[index].errorShelfProbo }}）</span></div>
                  <div class="tag-item tag-all">在架：<i class="iconfont icon-zhuangtai2" /><p>{{ baseStockData.length !==0 && baseStockData[index].onShelfNum }}</p></div>
                </div>
              </div>
            </div>
          </div>
          <!-- popover -->
          <div
            v-if="popoverIndex !== null"
            class="popover-external-set"
            :style="popoverStyle"
          >
            <div class="popover-content-set">
              <div class="tooltip-top">
                <h4>{{ shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].bookName }}</h4>
                <span v-if="shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].bookStatus === '错序'" class="tag-item tag-place">错序</span>
                <span v-if="shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].bookStatus === '错架'" class="tag-item tag-sort">错架</span>
              </div>
              <ul>
                <li><p>索书号</p><em>{{ shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].sortmark }}</em></li>
                <li><p>ISBN</p><em>{{ shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].isbn }}</em></li>
                <li><p>著者</p><em>{{ shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].bookAuthor }}</em></li>
                <li><p>出版社</p><em>{{ shelfAllGridData[popoverIndex.layer].books[popoverIndex.book].bookPublish }}</em></li>
              </ul>
            </div>
          </div>

        </div>
        <!-- <ul class="change-layer">
          <li v-for="(item,index) in rackOptions" :key="index" :class="{ 'active': layerVal === index+1 }" @click="changeShelfGetGrid(parseInt(item.name))">{{ item.name }}</li>
        </ul> -->
        <swiper
          ref="swiperTitleLayer"
          class="swiper-title layerShelf-swiper"
          :options="swiperOptionTitlelayer"
          :auto-update="true"
          :auto-destroy="true"
        >
          <swiper-slide
            v-for="(item,index) in rackOptions"
            :key="index"
            ref="swiperSlideItem"
            class="swiper-slide-title"
          >
            <div
              class="tab-name"
              :class="{ active: layerVal === index+1 }"
              @click="changeShelfGetGrid(parseInt(item.name))"
            >
              {{ item.name }}
            </div>
          </swiper-slide>
        </swiper>
      </div>
    </div>
    <BookDetails ref="bookDetailsRef" />
  </div>
</template>

<script>
import { FetchShelfGridByShelfIdAndGridShelf, FetchBillByShelfIdAndGridShelf, FetchBookShelfDetails, FetchInitStockInfo, FetchInitBookDetailsByGrids, FetchBookDetaisByBookRecNo } from '@/api/inquiryMachine'
import { positionCrud } from './mixins/index.js'
import Search from './module/search'
import BookDetails from './module/bookDetails'
import { Swiper, swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/swiper-bundle.css'

export default {
  name: 'Index',
  components: {
    Search,
    BookDetails,
    swiper,
    swiperSlide
  },
  mixins: [positionCrud],
  data() {
    return {
      activeIndex: 0,
      detailVisible: false,
      detailTable: [],
      detailCurrent: {},
      tabdialogIndex: 0,
      listLoading: false,
      tabIndex: 0,
      floorTabIndex: 0,
      regionTabIndex: 0,
      floorName: null,
      floorId: null,
      regionName: null,
      regionId: null,
      gridRow: null,
      gridShelf: null,
      bookShelfDetails: null,
      booShelfGrid: null,
      shelfAllGridData: [],
      layerNum: 0,
      rackNum: 0,
      bookNum: 46,
      layerVal: null,
      rackOptions: [],
      tabListData: [],
      popoverIndex: null,
      popoverVisible: [],
      popoverStyles: [],
      popoverPosition: { x: 0, y: 0 }, // Popover的位置
      baseStockData: [],
      shelfAllGridDataLoading: false,
      billNoImg: null,
      bigImg: '',
      gridName: '',
      getGridToward: 1,
      swiperOptionTitlelayer: {
        slidesPerView: 'auto',
        freeMode: true
      }
    }
  },
  computed: {
    swiperTitleLayer() {
      return this.$refs.swiperTitleLayer.$el.swiper
    },
    cellStyle: function() {
      const h = '76px'
      const w = '100%/' + this.rackNum
      return { width: `calc(${w} )`, height: `calc(${h})` }
    },
    popoverStyle() {
      return {
        top: `${this.popoverPosition.y - 300}px`, // 鼠标的Y坐标偏移10px
        left: `${this.popoverPosition.x - 240}px`, // 鼠标的X坐标偏移10px
        position: 'absolute'
      }
    }
  },
  created() {
    if (localStorage.getItem('dataScreenFloorTableIndex')) {
      this.floorTabIndex = localStorage.getItem('dataScreenFloorTableIndex')
    }
    if (localStorage.getItem('dataScreenRegionTableIndex')) {
      this.regionTabIndex = localStorage.getItem('dataScreenRegionTableIndex')
    }
    if (localStorage.getItem('dataScreenShelf')) {
      const dataScreenShelf = JSON.parse(localStorage.getItem('dataScreenShelf'))
      this.floorName = dataScreenShelf.floorName
      this.regionName = dataScreenShelf.regionName
      this.gridName = dataScreenShelf.gridName
      this.gridRow = dataScreenShelf.gridRow
      this.gridShelf = dataScreenShelf.gridShelf

      if (localStorage.getItem('dataScreenShelfAllGrid')) {
        this.shelfAllGridData = JSON.parse(localStorage.getItem('dataScreenShelfAllGrid'))
      }

      // 单面/双面
      this.tabListData = [{ name: dataScreenShelf.regionName + ' - ' + this.removeAreaPrefix(dataScreenShelf.gridName) }]

      this.tabIndex = dataScreenShelf.toward - 1
      FetchBookShelfDetails({ 'shelfId': dataScreenShelf.shelfId }).then(res => {
        this.layerNum = res.shelfFloor
        this.rackNum = res.shelfShelf
        this.floorId = res.floorId
        this.regionId = res.regionId
        this.bookShelfDetails = res

        this.rackOptions = []
        for (let i = 1; i <= this.rackNum; i++) {
          this.rackOptions.push({ id: i, name: `0${i}架` })
        }
        this.layerVal = parseInt(this.gridShelf) || ''

        this.getInitStockInfo(this.shelfAllGridData)

        this.getInitBookDetailsByGrids(this.shelfAllGridData)

        this.initSwiper()
      }).catch(() => {
      })
    }
  },
  mounted() {

  },
  methods: {
    initSwiper() {
      this.$nextTick(() => {
        this.shelfAllGridData.forEach((el, index) => {
          new Swiper('.swiper' + index, {
            slidesPerView: 'auto',
            slidesPerGroup: 15,
            observer: true
          })
        })
      })
    },
    removeAreaPrefix(gridNames) {
      const index = gridNames.indexOf('面')
      if (index !== -1) {
        return gridNames.substring(0, index + 1)
      }
      return gridNames
    },

    getBillByShelfIdAndGridShelf(data) {
      const params = {
        'gridShelf': data[0].gridShelf,
        'ShelfId': data[0].shelfId,
        'size': 5
      }
      FetchBillByShelfIdAndGridShelf(params).then(res => {
        if (res !== null) {
          this.checkDateLine = res.sort((a, b) => {
            return new Date(b.endTime) - new Date(a.endTime)
          })
          this.billNoImg = this.checkDateLine[0].stockBill
          this.checkDateLine[0].icon = 'el-icon-more'
          this.checkDateLine[0].color = '#0bbd87'
        } else {
          this.checkDateLine = []
        }
      }).catch(() => {
      })
    },
    async getInitStockInfo(data) {
      const promises = data.map(item => {
        const params = {
          'fondsCode': this.libcode,
          'floorId': this.floorId,
          'regionId': this.regionId,
          'shelfId': item.shelfId,
          'gridId': item.id
        }
        return FetchInitStockInfo(params)
      })
      const results = await Promise.all(promises)
      if (!Array.isArray(this.baseStockData)) {
        this.baseStockData = []
      }
      this.baseStockData = this.baseStockData.concat(results)
    },
    getInitBookDetailsByGrids(data) {
      const ids = data.map(item => item.id)
      const params = {
        'grids': ids.join(',')
      }
      FetchInitBookDetailsByGrids(params).then(res => {
        this.shelfAllGridData.forEach((item) => {
          const gridId = item.id
          if (Object.prototype.hasOwnProperty.call(res, gridId)) {
            // item.books = res[gridId]
            this.$set(item, 'books', res[gridId])
          }
        })
      }).catch(() => {
      })
    },
    handleDetail(item) {
      console.log('item', item)
      this.detailVisible = true
      this.detailTable = item.books
      this.detailCurrent = item
      if (this.detailCurrent.onShelfNum) {
        this.bigImg = `${this.baseApi}/api/fileRelevant/getImg?imgType=1&imgId=/${this.libcode}/${this.billNoImg}/${this.detailCurrent.gridCode}/img_result/result_LSD_compressed.jpg`
      } else {
        this.bigImg = ''
      }
    },
    // handleTouchStart(item) {
    //   // this.isTouching = true
    //   // this.showPopover(layerIndex, bookIndex, event)

    //   // this.$refs.bookDetailsRef.detailShow = true
    // },
    getBookDetaisByBookRecNo(item) {
      FetchBookDetaisByBookRecNo({
        'bookRecNo': item.bookRecNo
      }).then(res => {
        this.$refs.bookDetailsRef.getBookRankingDetail(res)
      }).catch(() => {
        this.$message.error('接口错误')
      })
    },
    handleTouchMove(layerIndex, bookIndex, event) {
      if (this.isTouching) {
        this.showPopover(layerIndex, bookIndex, event)
      }
    },
    handleTouchEnd(layerIndex, bookIndex, event) {
      this.isTouching = false
      this.hidePopover()
    },
    showPopover(layerIndex, bookIndex, event) {
      this.popoverIndex = { layer: layerIndex, book: bookIndex }
      const bookElement = event.target // 获取书籍项元素
      const rect = bookElement.getBoundingClientRect() // 获取边界
      if (layerIndex === 0) {
        this.popoverPosition = {
          x: window.scrollX + rect.left + rect.width / 2 - 40,
          y: window.scrollY + rect.top + rect.height
        }
      } else {
        this.popoverPosition = {
          x: window.scrollX + rect.left + rect.width / 2 - 40,
          y: window.scrollY + rect.top + rect.height - 170
        }
      }
    },
    hidePopover() {
      this.popoverIndex = null
    },
    updateParts(gridName) {
      const parts = gridName.match(/(\d+)区(\d+)排([A-Za-z])面(\d+)架(\d+)层/)
      if (parts) {
        this.getGridShelf = parts[4]
        this.getGridFloor = parts[5]
        const toward = parts[3]
        if (toward === 'A') {
          this.getGridToward = 1
        } else if (toward === 'B') {
          this.getGridToward = 2
        }
      }
    },
    changeShelfGetGrid(val) {
      this.updateParts(this.gridName)
      this.shelfAllGridDataLoading = true
      this.layerVal = val
      const params = {
        'gridShelf': '0' + val,
        'shelfId': this.bookShelfDetails.id,
        'toward': this.getGridToward,
        'floorType': this.bookShelfDetails.floorType
      }
      FetchShelfGridByShelfIdAndGridShelf(params).then(res => {
        this.shelfAllGridData = []
        this.shelfAllGridData = res
        this.getInitStockInfo(this.shelfAllGridData)

        this.getInitBookDetailsByGrids(this.shelfAllGridData)

        this.shelfAllGridDataLoading = false
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/index.scss";
.gird-data-book{
  position: relative;
  // padding:  0 10px;
  // height: 650px;
  // margin-top: 4px;
  // overflow: hidden;
  // overflow-y: scroll;
}

.gird-layer{
  position: relative;
  display: flex;
  justify-content: space-between;
  .gird-left-line{
    position: absolute;
    left: 0;
    top: 0;
    display: block;
    width: 6px;
    height: 130px;
    background: url('~@/assets/images/shelf01.png') no-repeat left top;
    background-size: 100% 100%;
    z-index: 999;
  }
  .gird-right-line{
    position: absolute;
    right: calc(310px);
    top: 0;
    display: block;
    width: 6px;
    height: 130px;
    background: url('~@/assets/images/shelf01.png') no-repeat left top;
    background-size: 100% 100%;
    z-index: 999;
  }
  .layer-left{
    width: calc(100% - 300px);
    height: 130px;
    margin-right: 5px;
    padding: 0 0 0 12px;
    background: url('~@/assets/images/shelf02.png') repeat left top;
    background-size: 10% 100%;
    overflow: hidden;
    overflow-x: scroll;
  }
  .layer-left-book{
    // width: calc(100vw - 655px);
    height: 130px;
    white-space: nowrap;
    .rack-box-list{
      height: 200px;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
    }
    .list-item{
      display: inline-block;
      border: none;
      width: 42px;
      height: 120px;
      background: url('~@/assets/images/shelf03.png') no-repeat left top;
      background-size: 100% 100%;
      position: relative;
      margin-left: -14px;
      margin-top: 10px;
      .book-name{
        position: absolute;
        left: 12px;
        top: 16px;
        display: block;
        height: 90px;
        font-size: 16px;
        writing-mode:vertical-rl;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      &.red-active{
        background: url('~@/assets/images/shelf05.png') no-repeat left top;
        background-size: 100% 100%;
      }
      &.blue-active{
        background: url('~@/assets/images/shelf06.png') no-repeat left top;
        background-size: 100% 100%;
      }
    }
  }

}

.layer-right-handle{
  width: 300px;
  padding: 0 10px;
  background-color: #E8F2FF;
  margin: 3px 5px;
  border-radius: 6px;
}
.layer-info-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 36px;
  h4{
    font-size: 20px;
    color: #0c0e1e;
  }
  span{
    font-size: 12px;
  }
}
.layer-right-content{
  display: flex;
  justify-content: space-between;
}
.layer-tag-info{
  div.tag-item {
    display: flex;
    justify-content: flex-start;
    line-height: 26px;
    font-size: 18px;
  }
}
.layer-handle{
  display: flex;
  flex-direction: column;
  .el-button,
  .el-button--info.is-plain {
    margin-left: 0 !important;
    margin-bottom: 10px;
    padding: 7px 10px !important;
    font-weight: bold !important;
    border-color: #0348f3 !important;
    color: #0348f3 !important;
  }
  .check-btn{
    color: #fff !important;
    background-color: #0348f3 !important;
  }
}

.layerShelf-swiper{
  margin-top: 20px;
  ::v-deep .swiper-wrapper{
    font-size: 20px;
    border-bottom: none !important;
    .swiper-slide-title {
      width: auto !important;
      margin-right: 20px;
      cursor: pointer;
      .tab-name {
        padding: 5px 10px;
        &.active {
          background-color: #0348F3;
          color: #fff;
          border-radius: 6px;
          border: 2px solid #0348F3;
        }
      }
    }
  }
}
</style>
