<template>
  <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="baggageMessage">
    <div class="baggageMessage-content">
      <template v-if="messageList.length">
        <el-scrollbar style="height: 100%">
          <el-row style="margin:0" :gutter="15">
            <el-col v-for="(message, index) in messageList" :key="index" :span="6">
              <div class="card">
                <div class="message-date">{{ message.readTime }}</div>
                <div class="message-content">
                  <el-scrollbar style="height: 100%">
                    <div>{{ message.sourceData.replaceAll(/[\\r\\n]{2,}/g, '\n').replaceAll('\\', '') }}</div>
                  </el-scrollbar>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-scrollbar>
      </template>
      <template v-else>
        <el-empty :image-size="1" description="暂无数据" />
      </template>
    </div>
    <div class="btns">
      <img class="btn-square btn-shadow" src="@/assets/baggage/ic_export.png" title="导出" @click="exportMessageToExcel">
    </div>
  </div>
</template>

<script>
import pf from '@/layout/mixin/publicFunc'
import * as XLSX from 'xlsx'
import XLSX_STYLE from 'xlsx-style'
import FileSaver from 'file-saver'
export default {
  name: 'BaggageMessage',
  mixins: [pf],
  props: {
    query: {
      type: Object,
      default: () => { }
    },
    tagObj: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      messageList: [],
      loading: false,
      dataContent: []
    }
  },
  watch: {
    tagObj: {
      handler (obj) {
        this.dataContent = obj
        this.queryDetails()
      },
      deep: true
    }
  },
  created () {
    this.dataContent = this.tagObj
  },
  mounted () {
    this.queryDetails()
  },
  methods: {
    async queryDetails () {
      try {
        this.loading = true
        const { code, returnData } = await this.getQueryList(SERVICE_ID.bagDetailId, this.dataContent)
        if (code == 0 && returnData && returnData.length) {
          this.messageList = [...returnData]
          this.loading = false
        } else {
          this.loading = false
        }
      } catch (error) {
        this.loading = false
        console.log(error)
        this.$message.error('失败')
      }
    },
    exportMessageToExcel () {
      const xlsxDatas = [['Date & Time', 'Message']]
      xlsxDatas.push(
        ...this.messageList.map(message => [
          message.flightDate,
          message.sourceData.replaceAll(/[\\r\\n]{2,}/g, '\n').replaceAll('\\', '')
        ])
      )
      const columnWidths = []
      xlsxDatas.forEach(row => {
        // 计算每一列宽度，考虑换行
        row.forEach((cell, columnIndex) => {
          const cellWidth = Math.max(
            ...cell
              .toString()
              .split('\n')
              .map(cellRow =>
                cellRow.split('').reduce((pre, curr) => {
                  const letterSize = curr.charCodeAt(0) > 255 ? 2 : 1
                  return pre + letterSize
                }, 0)
              )
          )
          if ((!columnWidths[columnIndex] && cellWidth > 0) || cellWidth > columnWidths[columnIndex]) {
            columnWidths[columnIndex] = cellWidth
          }
        })
      })
      // 生成表格数据
      const sheet = XLSX.utils.aoa_to_sheet(xlsxDatas)
      // 添加列宽度
      sheet['!cols'] = columnWidths.map(width => ({
        wch: width + 2
      }))
      // 表格对齐、添加边框
      const borderStyle = {
        style: 'medium',
        color: {
          rgb: 'FFFFFF'
        }
      }
      const reg = /^[A-Z]+([\d]+$)/
      for (const key in sheet) {
        const match = reg.test(key)
        if (match) {
          const rowIndex = reg.exec(key)[1]
          let cellStyle = {
            alignment: {
              horizontal: 'center',
              vertical: 'center',
              wrapText: true
            }
          }
          if (Number(rowIndex) === 1) {
            cellStyle = {
              ...cellStyle,
              border: {
                top: borderStyle,
                right: borderStyle,
                bottom: borderStyle,
                left: borderStyle
              },
              font: {
                color: {
                  rgb: 'FFFFFF'
                }
              },
              fill: {
                fgColor: {
                  rgb: '3366FF'
                }
              }
            }
          } else {
            cellStyle.alignment.horizontal = 'left'
          }
          sheet[key].s = cellStyle
        }
      }
      // 表格数据转换
      const workBook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workBook, sheet, '行李原始报文')
      const tableWrite = XLSX_STYLE.write(workBook, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'buffer',
        cellStyles: true
      })
      // 下载表格
      const { luggageNum, flightNo, flightDate } = this.query
      const fileName = `行李原始报文-${luggageNum}-${flightNo}-${flightDate}.xlsx`
      FileSaver.saveAs(new Blob([tableWrite], { type: 'application/octet-stream' }), fileName)
    },
  }
}
</script>

<style lang="scss" scoped>
.baggageMessage {
  height: 100%;
  position: relative;
  &-content {
    padding: 24px;
    height: 100%;
  }
  .card {
    width: 100%;
    height: 440px;
    padding: 20px;
    background: #ffffff;
    border: 1px solid #dfe3ea;
    box-shadow: 0px 3px 2px 0px rgba(0, 0, 0, 0.29);
    margin-bottom: 12px;
    > .message-date {
      width: 180px;
      height: 26px;
      line-height: 14px;
      font-size: 14px;
      font-family: Helvetica;
      color: #afb4bf;
      border-bottom: 1px solid #afb4bf;
      margin-bottom: 18px;
    }
    > .message-content {
      white-space: pre-line;
      line-height: 24px;
      font-size: 14px;
      color: #303133;
      word-break: break-all;
      height: calc(100% - 44px);
    }
  }
  .btns {
    position: absolute;
    top: -50px;
    right: 24px;
    z-index: 10;
    .r16 {
      margin-right: 16px;
    }
  }
}
</style>