<template>
  <div class="app-container">
    <div class="venue-header  dataScreening-header">
      <h4><i class="iconfont icon-shuju" />区域总览</h4>
      <div class="bookshelf-area">
        <!--  <span class="bookshelf-area">{{ floorName }} </span> -->
        <router-link :to="{ path: '/check/check/dataScreening', query: {floorTabIndex: floorTabIndex }}">
          {{ floorName }}
        </router-link>
        <div class="double-click-btn"><span>点击左侧位置返回</span></div>
      </div>
      <p><i class="iconfont icon-gongsi" />{{ user.fonds.fondsName }}</p>
    </div>
    <div class="venue-content dataScreening-content">
      <crudOperation :permission="permission">
        <template v-slot:middle>
          <el-button v-permission="permission.add" class="check-btn" size="mini" @click="toAdd(2)">
            <i class="iconfont icon-shengchengpandiandan" />
            区域盘点
          </el-button>
        </template>
        <template v-slot:right>
          <el-button :loading="crud.downloadLoading" size="mini" @click="doExport(2)">
            <i class="iconfont icon-daochu" />
            导出
          </el-button>
        </template>
      </crudOperation>
      <div class="venue-left">
        <div class="container-right tab-content">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <ul class="tab-nav">
            <li v-for="(item,index) in regionOptions" :key="index" :class="{ 'active-tab-nav': tabIndex == index }" @click="changeActiveTab(index)">{{ item.regionName }}<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <CanvasPreview ref="previewRefs" v-loading="prewLoading" page-preview="region" :current-mark-data="currentMarkData" :image-url="imageUrl" />
        </div>
      </div>
      <div class="venue-right">
        <div class="lib-right-item lib-info">
          <h4>本区概况</h4>
          <ul class="data-right-list">
            <li><p>书架</p><span><i>{{ baseData.shelfCount }}</i>个</span></li>
            <li><p>摄像头</p><span><i>{{ baseData.deviceCount }}</i>个</span></li>
          </ul>
        </div>
        <div class="lib-right-item">
          <h4>本区盘点概况</h4>
          <!-- <div class="refresh-date">2024-11-28 09:46</div> -->
          <ul class="data-right-list">
            <li><p>在架</p><span><i>{{ baseStockData.onShelfNum }}</i>册</span></li>
            <li><p>错架</p><span><i>{{ baseStockData.errorShelfNum }}</i>册</span> <span class="percentage">（{{ baseStockData.errorShelfProbo }}）</span></li>
            <li><p>错序</p><span><i>{{ baseStockData.errorOrderNum }}</i>册</span><span class="percentage">（{{ baseStockData.errorOrderProbo }}）</span></li>
          </ul>
        </div>
        <div class="lib-right-item">
          <h4>本区流通统计</h4>
          <div class="refresh-date">2024-11-28 09:46</div>
          <bookSwiper ref="bookSwiperRefs" />
        </div>
      </div>
    </div>
    <eForm ref="eform" />
    <exportForm ref="exportform" export-type="regions" />
  </div>
</template>

<script>
import { FetchInitStockInfo } from '@/api/stockTask/index'
import { dataScreeningCrud } from '@/views/visualCheck/mixins/index'
import crudRegion from '@/api/area/index'
import { FetchInitBookShelfList } from '@/api/shelf/index'
import CRUD, { presenter, header, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import { mapGetters } from 'vuex'
import defaultImg from '@/assets/images/system/default-img.jpg'
import bookSwiper from '@/views/components/bookSwiper.vue'
import CanvasPreview from '@/views/components/canvasPreview.vue'
import eForm from './module/form'
import exportForm from './module/export'

export default {
  name: 'DataScreening',
  components: { crudOperation, bookSwiper, CanvasPreview, eForm, exportForm },
  cruds() {
    return CRUD({ title: '区域总览', url: 'api/libraryRegion/initLibraryRegionList', crudMethod: { ...crudRegion }, sort: [], optShow: {
      add: false,
      edit: false,
      del: false,
      download: false,
      group: false,
      reset: false
    }
    })
  },
  mixins: [presenter(), header(), crud(), dataScreeningCrud],
  data() {
    const _this = this
    return {
      prewLoading: false,
      regionOptions: [],
      floorName: null,
      currentRegionId: null,
      tabIndex: 0,
      floorTabIndex: 0,
      defaultImg: defaultImg,
      imageUrl: defaultImg,
      imageRegionUrl: defaultImg,
      currentMarkData: null,
      allCoverData: [],
      swiperActiveIndex: 0,
      rightDataIndex: null,
      swiperOptionContent: {
        slidesPerView: 'auto',
        on: {
          slideChangeTransitionStart: function() {
            _this.rightDataIndex = null
            _this.swiperActiveIndex = this.activeIndex
            _this.swiperTitle.slideTo(this.activeIndex, 500, false)
          }
        }
      },
      swiperOptionTitle: {
        slidesPerView: 'auto',
        freeMode: true
      },
      tabListData: [{ name: '热门图书' }, { name: '热门架位' }, { name: '冷面图书' }],
      permission: {
        add: ['admin', 'floor:add'],
        edit: ['admin', 'floor:edit'],
        del: ['admin', 'floor:del']
      },
      baseStockDataAllShelf: [],
      swiperParams: {},
      swiperShelfParams: {}
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ]),
    swiperContent() {
      return this.$refs.swiperContent.$el.swiper
    }
  },
  methods: {
    handleToShelfs() {
      this.$router.push({ path: '/dataScreening/shelf', query: { }})
    },
    [CRUD.HOOK.beforeRefresh]() {
      const data = JSON.parse(localStorage.getItem('dataScreenFloor'))
      this.crud.query.floorId = data.floorId
      this.currentRegionId = data.id
    },
    [CRUD.HOOK.afterRefresh](crud) {
      if (localStorage.getItem('dataScreenFloorTableIndex')) {
        this.floorTabIndex = localStorage.getItem('dataScreenFloorTableIndex')
      }

      this.regionOptions = crud.data
      const item = this.regionOptions.find(element => element.id === this.currentRegionId)
      let index
      if (this.$route.query.regionTabIndex) {
        index = this.$route.query.regionTabIndex
      } else {
        index = item ? this.regionOptions.indexOf(item) : -1
      }
      this.floorName = this.regionOptions[index].floorName
      this.tabIndex = index
      this.changeActiveTab(index)

      // 盘点概况
      const params = {
        'floorId': this.regionOptions[this.tabIndex].floorId,
        'regionId': this.regionOptions[this.tabIndex].id
      }
      this.handleInitStockInfo(params)

      this.$nextTick(() => {
        this.$refs.bookSwiperRefs.swiperParams = params
        this.$refs.bookSwiperRefs.swiperShelfParams = params
        if (this.$refs.bookSwiperRefs.swiperActiveIndex === 0) {
          this.$refs.bookSwiperRefs.getInitHotBookList()
        } else {
          this.$refs.bookSwiperRefs.getInitHotShelfList()
        }
      })
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU](crud) {
      return true
    },
    toAdd(type) {
      this.$refs.eform.formVisible = true
      this.$refs.eform.form.regionId = this.regionOptions[this.tabIndex].id
      this.$refs.eform.form.stockRegion = this.regionOptions[this.tabIndex].floorName + this.regionOptions[this.tabIndex].regionName
      this.$refs.eform.setData(type)
    },
    doExport(type) {
      this.$refs.exportform.formExportVisible = true
      this.$refs.exportform.type = 2
      this.$refs.exportform.params = {
        'regionId': this.regionOptions[this.tabIndex].id
      }
    },
    async getInitStockInfo(data) {
      const promises = data.map(item => {
        const params = {
          'floorId': this.floorId,
          'regionId': this.regionId,
          'shelfId': item.shelfId
        }
        return FetchInitStockInfo(params)
      })
      const results = await Promise.all(promises)
      if (!Array.isArray(this.baseStockDataAllShelf)) {
        this.baseStockDataAllShelf = []
      }
      // 为每个结果对象添加id字段
      results.forEach((result, index) => {
        result.id = data[index].shelfId
      })
      this.baseStockDataAllShelf = this.baseStockDataAllShelf.concat(results)
      return this.baseStockDataAllShelf
    },

    async changeActiveTab(index) {
      this.prewLoading = true
      this.tabIndex = index
      const params = {
        'floorId': this.regionOptions[index].floorId,
        'regionId': this.regionOptions[index].id
      }
      try {
        const res = await FetchInitBookShelfList(params)
        console.log(res)
        this.allCoverData = res.content
        if (this.regionOptions[index].regionMap) {
          this.imageUrl = this.baseApi + '/api/fileRelevant/getImg?imgId=' + this.regionOptions[index].regionMap
        } else {
          this.imageUrl = this.defaultImg
        }

        if (this.allCoverData.length !== 0) {
          this.currentMarkData = this.regionOptions[index]
          const signPoint = this.allCoverData.find(item => item.signPoint !== null)?.signPoint
          const imgInfo = signPoint ? JSON.parse(signPoint).imgInfo : null
          const baseStockDataAllShelf = await this.getInitStockInfo(this.allCoverData)
          const parsedSignPoints = this.allCoverData.map(item => {
            const signPoint = item.signPoint ? JSON.parse(item.signPoint) : null
            return {
              id: item.shelfId,
              name: item.shelfName,
              rowType: item.rowType,
              toward: item.toward,
              floorName: item.floorName,
              regionName: item.regionName,
              shelfFloor: item.shelfFloor,
              shelfShelf: item.shelfShelf,
              floorId: this.regionOptions[index].floorId,
              regionId: this.regionOptions[index].id,
              pointInfo: signPoint ? signPoint.pointInfo[0].pointInfo : null
            }
          })
          parsedSignPoints.forEach(parsedItem => {
            const baseStockItem = baseStockDataAllShelf.find(baseItem => baseItem.id === parsedItem.id)
            if (baseStockItem) {
              Object.assign(parsedItem, baseStockItem)
            }
          })

          const result = {
            pointInfo: parsedSignPoints,
            imgInfo: imgInfo
          }
          console.log('result', result)
          this.$nextTick(() => {
            this.$refs.previewRefs.initCanvasPreview(result, this.tabIndex)
          })
        } else {
          this.currentMarkData = {}
          setTimeout(() => {
            this.prewLoading = false
          }, 500)
        }
      } catch (error) {
        console.error(error)
      }
    },
    handleSlidClickFun(index) {
      this.rightDataIndex = null
      this.handleSlideToFun(index)
    },
    handleSlideToFun(index) {
      this.swiperActiveIndex = index
      this.swiperContent.slideTo(index, 500, false)
      this.swiperTitle.slideTo(index, 500, false)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
