<template>
  <div>
    <vue-office-excel ref="a" v-if="+type === 0" v-bind="$attrs" :src="src" @error="$emit('error', $event)" @rendered="handleRendered"/>
  </div>
</template>

<script>
import * as Excel from 'exceljs/dist/exceljs'
// 引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
// 引入相关样式
import '@vue-office/excel/lib/index.css'

const workbook = new Excel.Workbook()

export default {
  name: 'file-review',
  components: {
    VueOfficeExcel
  },
  props: {
    // 预览类型 0: Excel
    type: {
      type: [Number, String],
      default: 0
    },
    src: {
      type: [String, File, ArrayBuffer],
      default: ''
    }
  },
  data () {
    return {
      worksheet: null,
      rendered: 0
    }
  },
  watch: {
    src: {
      async handler (val) {
        await workbook.xlsx.load(val)
        this.worksheet = workbook.worksheets[0]
        this.handleRendered()
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.setupSheetClickHandler()
    })
  },
  methods: {
    setupSheetClickHandler () {
      // 等待组件渲染完成
      setTimeout(() => {
        if (!this.$refs.a || !this.$refs.a.rootRef) {
          return
        }
        try {
          const _bottom = this.$refs.a.rootRef.childNodes[0]?.childNodes[3]
          if (!_bottom) {
            return
          }
          const _ul = _bottom.childNodes[1]
          if (!_ul) {
            return
          }
          _ul.addEventListener('click', (evt) => {
            if (evt.target.localName === 'ul') {
              return
            }
            this.worksheet = workbook.getWorksheet(evt.target.innerText)
            this.$emit('click:bottom-bar', evt.target.innerText)
          })
        } catch (error) {
          console.error('设置工作表点击事件失败:', error)
        }
      }, 500)
    },
    switchToFirstSheet () {
      // 切换到第一个工作表
      this.$nextTick(() => {
        // 多次尝试，确保组件完全渲染
        let attempts = 0
        const maxAttempts = 10
        const trySwitch = () => {
          attempts++
          if (!this.$refs.a || !this.$refs.a.rootRef) {
            if (attempts < maxAttempts) {
              setTimeout(trySwitch, 200)
            }
            return
          }
          try {
            const rootNode = this.$refs.a.rootRef.childNodes[0]
            if (!rootNode) {
              if (attempts < maxAttempts) {
                setTimeout(trySwitch, 200)
              }
              return
            }
            const _bottom = rootNode.childNodes[3]
            if (!_bottom) {
              if (attempts < maxAttempts) {
                setTimeout(trySwitch, 200)
              }
              return
            }
            const _ul = _bottom.childNodes[1]
            if (!_ul || !_ul.children || _ul.children.length === 0) {
              if (attempts < maxAttempts) {
                setTimeout(trySwitch, 200)
              }
              return
            }
            // 找到第一个可见的工作表标签
            const sheetItems = Array.from(_ul.children).filter(li => {
              return li.style.display !== 'none' && li.textContent && li.textContent.trim()
            })
            if (sheetItems.length > 0) {
              const firstSheetLi = sheetItems[0]
              // 检查是否已经是激活状态
              if (!firstSheetLi.classList.contains('active')) {
                firstSheetLi.click()
                const sheetName = firstSheetLi.textContent.trim()
                // 更新 worksheet 引用
                try {
                  this.worksheet = workbook.getWorksheet(sheetName)
                } catch (e) {
                  console.warn('无法获取工作表:', sheetName)
                }
              }
            }
          } catch (error) {
            console.error('切换到第一个工作表失败:', error)
          }
        }
        setTimeout(trySwitch, 500)
      })
    },
    handleRendered () {
      this.rendered++
      if (this.rendered >= 2) {
        // 渲染完成后，切换到第一个工作表
        this.switchToFirstSheet()
        this.$emit('rendered')
        this.rendered = 0
      }
    },
    getRow (index) {
      const row = this.worksheet.getRow(index + 1)
      let _merges = 0
      const text = []
      row.eachCell((cell, colNumber) => {
        if (cell._mergeCount) {
          _merges = cell._mergeCount + colNumber
        }
        if (_merges > colNumber) {
          return
        }
        _merges = 0
        if (typeof cell.value === 'object' && cell.value !== null) {
          text.push(cell.value.text || cell.value.result || '格式异常')
          return
        }
        text.push(cell.value)
      })
      return text
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
