<template>
  <div class="app-container">
    <div class="venue-header">
      <h4><i class="iconfont icon-shuju" />数据总览</h4>
      <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(1)">
            <i class="iconfont icon-shengchengpandiandan" />
            全量盘点
          </el-button>
        </template>
        <template v-slot:right>
          <el-button :loading="crud.downloadLoading" size="mini" @click="doExport(1)">
            <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 floorOptions" :key="index" :class="{ 'active-tab-nav': tabIndex == index }" @click="changeActiveTab(index)">{{ item.floorName }}<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <div class="total-data">
            <span>楼层概况</span>
            <p>区域：{{ baseData.regionCount }}</p>
            <p>书架：{{ baseData.shelfCount }}</p>
            <p>摄像头：{{ baseData.deviceCount }}</p>
          </div>
          <CanvasPreview ref="previewRefs" v-loading="prewLoading" page-preview="floor" :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.floorCount }}</i>层</span></li>
            <li><p>区域</p><span><i>{{ baseData.regionCount }}</i>个</span></li>
            <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" />
  </div>
</template>

<script>
import { FetchInitStockInfo } from '@/api/stockTask/index'
import { dataScreeningCrud } from '@/views/visualCheck/mixins/index'
import { FetchInitLibraryRegionList } from '@/api/area/index'
import crudStockTaskLog from '@/api/stockTaskLog/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/libraryFloor/initLibraryFloorList', crudMethod: { ...crudStockTaskLog }, 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,
      floorOptions: [],
      tabIndex: 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']
      },
      swiperParams: {},
      swiperShelfParams: {}
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'
    ]),
    swiperContent() {
      return this.$refs.swiperContent.$el.swiper
    }
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
    },
    [CRUD.HOOK.afterRefresh](crud) {
      this.floorOptions = crud.data

      if (this.$route.query.floorTabIndex) {
        this.tabIndex = this.$route.query.floorTabIndex
      } else {
        this.tabIndex = 0
      }

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

      this.$nextTick(() => {
        this.$refs.bookSwiperRefs.swiperParams = {
          'floorId': this.floorOptions[this.tabIndex].id
        }
        this.$refs.bookSwiperRefs.swiperShelfParams = {
          'floorId': this.floorOptions[this.tabIndex].id
        }
        if (this.$refs.bookSwiperRefs.swiperActiveIndex === 0) {
          this.$refs.bookSwiperRefs.getInitHotBookList()
        } else {
          this.$refs.bookSwiperRefs.getInitHotShelfList()
        }
      })
    },
    toAdd(type) {
      this.$refs.eform.formVisible = true
      this.$refs.eform.setData(type)
      this.$refs.eform.form.stockRegion = '全部区域'
    },
    doExport(type) {
      this.$refs.exportform.formExportVisible = true
      this.$refs.exportform.type = 1
    },
    async getInitStockInfo(data) {
      const promises = data.map(item => {
        const params = {
          'floorId': this.floorOptions[this.tabIndex].id,
          'regionId': item.id
        }
        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].id
      })
      this.baseStockDataAllShelf = this.baseStockDataAllShelf.concat(results)
      return this.baseStockDataAllShelf
    },

    async changeActiveTab(index) {
      this.prewLoading = true
      if (this.$refs.previewRefs.canvasPreview.lowerCanvasEl) {
        this.$refs.previewRefs.canvasPreview.clear()
        this.$refs.previewRefs.canvasPreview.dispose()
      }
      this.allCoverData = []
      this.tabIndex = index
      const params = {
        'floorId': this.floorOptions[index].id
      }
      try {
        const res = await FetchInitLibraryRegionList(params)
        console.log(res)
        this.allCoverData = res.content
        if (this.floorOptions[index].floorMap) {
          this.imageUrl = this.baseApi + '/api/fileRelevant/getImg?imgId=' + this.floorOptions[index].floorMap
        } else {
          this.imageUrl = this.defaultImg
        }

        if (this.allCoverData.length !== 0) {
          this.currentMarkData = this.allCoverData[0]

          // const signPoint = this.allCoverData.find(item => item.signPoint !== null)?.signPoint
          const imgInfo = JSON.parse(this.allCoverData[0].signPoint).imgInfo

          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.id,
              name: item.regionName,
              floorName: item.floorName,
              floorId: item.floorId,
              pointInfo: signPoint ? signPoint.pointInfo[0].pointInfo : null
            }
          })
          parsedSignPoints.forEach(parsedItem => {
            const baseStockItem = baseStockDataAllShelf.find(baseItem => baseItem.id === parsedItem.id)
            if (baseStockDataAllShelf) {
              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>
