<template>
  <div class="edit-add-detail detail show-scrollbar">
    <el-dialog
      title="值班记录预览"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      custom-class="pdf-preview-dialog"
    >
      <vue-pdf-embed v-if="pdfBlob" :source="pdfBlob" class="pdf-embed" />
      <div v-else class="empty-pdf">正在加载PDF...</div>
    </el-dialog>
    <div
      v-loading="formLoading"
      class="form-content"
      element-loading-background="rgba(10 ,38 ,61, 0.9)"
      element-loading-text="详情加载中..."
    >
      <el-form
        ref="formInfo"
        :model="detailForm"
        label-position="left"
        label-suffix="："
        label-width="120px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">
              值班日志
            </div>
          </div>
        </div>
        <div class="form-wrapper" ref="contentToExport">
          <div class="download-btn-container">
            <el-tooltip content="预览值班日志" placement="left">
              <i class="el-icon-view action-icon" @click="handlePreview"></i>
            </el-tooltip>
            <el-tooltip content="下载值班日志" placement="left">
              <i
                class="el-icon-download download-icon"
                @click="handleDownload"
              ></i>
            </el-tooltip>
          </div>
          <div class="title">
            <div>运行监测调度中心</div>
            <div>值 班 记 录</div>
          </div>
          <el-descriptions :column="3" border :labelStyle="{width: '140px'}">
            <el-descriptions-item label="所属路段" :span="3">
              {{ detailForm.roadInfosName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="班次">
              {{ detailForm.shiftName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="工作时间" :span="2">
              {{ detailForm.dateRange || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="值班人员" :span="3">
              <span class="textarea-content">{{
                detailForm.dutyPersonnel || '-'
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="值班记录" :span="3">
              <template slot="label">
                <span class="text-row">值班记录</span>
              </template>
              <span class="textarea-content">{{
                detailForm.dutySituation || '-'
              }}</span>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions
            :column="6"
            border
            class="el-descriptions-table"
            direction="vertical"
          >
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              交通事故
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.trafficAccidentCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.trafficAccidentDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              人员伤亡
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.casualtyCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.casualtyDetail || '-' }}
            </el-descriptions-item>

            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              管制情况
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.controlSituationCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.controlSituationDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              重大事件记录
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.majorEventCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.majorEventDetail || '-' }}
            </el-descriptions-item>

            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              拥堵情况
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.congestionCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.congestionDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              设备报修
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.equipmentRepairCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.equipmentRepairDetail || '-' }}
            </el-descriptions-item>

            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              投诉记录
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.complaintCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.complaintDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              清障救援
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.rescueCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.rescueDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              外单位来访
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.visitCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.visitDetail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="事项"
              :labelStyle="{width: '140px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              来电询问
            </el-descriptions-item>
            <el-descriptions-item
              label="数量"
              :labelStyle="{width: '120px'}"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.inquiryCount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item
              label="详情"
              :contentStyle="{'text-align': 'center'}"
            >
              {{ detailForm.inquiryDetail || '-' }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions border :labelStyle="{width: '140px'}">
            <el-descriptions-item label="交接情况" :span="3">
              <template slot="label">
                <span class="text-row">交接情况</span>
              </template>
              <span class="textarea-content">{{
                detailForm.handoverSituation || '-'
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="设施设备" :span="3">
              <template slot="label">
                <span class="text-row">设施设备</span>
              </template>
              <span class="textarea-content">{{
                detailForm.facilityStatus || '-'
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="接班人员" :span="3">
              <span class="textarea-content">{{
                detailForm.nextShiftPersonnel || '-'
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="管理员意见" :span="2">
              <span class="textarea-content">{{
                detailForm.adminComment || '-'
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item
              label="管理员签字"
              :span="1"
              :contentStyle="{width: '200px'}"
            >
              {{ detailForm.adminName || '-' }}<br />
              {{ detailForm.adminAuditTime || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-form>
    </div>
    <el-backtop :visibility-height="20" target=".el-form">
      <div class="top-box">UP</div>
    </el-backtop>
  </div>
</template>

<script>
import {
  tableDetail,
  exportDataBatch
} from '@/api/patrolAndRescue/commandDispatch/reportManagement/dutyRecords.js'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'

export default {
  name: 'DetailPage',
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  components: {},
  data() {
    return {
      detailForm: {},
      formLoading: false,
      pubSub: null,
      previewVisible: false,
      pdfBlob: null,
      id: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  mounted() {
    this.pubSub = PubSub.subscribe('DetailPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    dictionaryEscape,
    async handleDownload() {
      this.downloadLoading = true
      try {
        const params = `ids=${this.id}`
        await exportDataBatch(params)
      } catch (e) {
        this.$message.error(`数据导出失败`)
      } finally {
        this.downloadLoading = false
      }
      // try {
      //   const printContent = this.generatePrintContent(false)
      //   const tempDiv = document.createElement('div')
      //   tempDiv.innerHTML = printContent
      //   document.body.appendChild(tempDiv)

      //   await pdfUtils.generateFromElement(
      //     tempDiv,
      //     '值班记录.pdf',
      //     {
      //       orientation: 'portrait',
      //       unit: 'mm',
      //       format: 'a4',
      //       scale: 2
      //     }
      //   )

      //   document.body.removeChild(tempDiv)
      //   this.$message.success('PDF生成并下载成功')
      // } catch (error) {
      //   console.error('PDF生成失败:', error)
      //   this.$message.error(error.message || 'PDF生成失败')
      // }
    },
    async handlePreview() {
      // 生成打印内容并预览
      const printContent = this.generatePrintContent()
      const printWindow = window.open('', '_blank')
      if (printWindow) {
        printWindow.document.write(printContent)
        printWindow.document.close()
        printWindow.focus()
        printWindow.print()
        printWindow.close()
      }
    },

    generatePrintContent(show = true) {
      return `
      <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    padding: 0;
                    margin: 0;
                }
                .print-header { 
                    text-align: center; 
                    margin-bottom: 20px; 
                }
                .print-header h1 { 
                    font-size: 24px; 
                    margin: 0; 
                    font-weight: bold; 
                }
                .print-table { 
                    width: 100%; 
                    border-collapse: collapse;
                    margin-bottom: 20px;
                }
                .print-table th, .print-table td { 
                    border: 1px solid #000; 
                    padding: 8px; 
                    text-align: left; 
                }
                .print-table th { 
                    width: 140px; 
                    text-align: center;
                }
                .print-table .wide-cell {
                    width: 200px;
                }
                .print-footer { 
                    margin-top: 30px; 
                    text-align: right; 
                    font-size: 12px; 
                }
                .text-content {
                    white-space: pre-line;
                    padding: 8px;
                }
                .text-row{
                    writing-mode: vertical-rl;
                    letter-spacing: 12px;
                }
                @page { 
                    size: A4; 
                    margin: 10mm; 
                }
                @media print {
                    * {
                        -webkit-print-color-adjust: exact !important;
                        color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }
                    body {
                        margin: 0 30px;
                        padding: 20px 0;
                    }
                    .print-table th {
                        text-align: center;
                    }
                }
            </style>
        </head>
        <body>
          <div class="print-header">
            <h1>运行监测调度中心</h1>
            <h1>值 班 记 录</h1>
          </div>

          <table class="print-table">
            <tr>
              <th>所属路段</th>
              <td colspan="5">${this.detailForm.roadInfosName || '-'}</td>
            </tr>
            <tr>
              <th>班次</th>
              <td>${this.detailForm.shiftName || '-'}</td>
              <th>工作时间</th>
              <td colspan="3">${this.detailForm.dateRange || '-'}</td>
            </tr>
            <tr>
              <th>值班人员</th>
              <td colspan="5" class="text-content">${this.detailForm
                .dutyPersonnel || '-'}</td>
            </tr>
            <tr style='height: 300px;'>
              <th class='text-row'>值班记录</th>
              <td colspan="5" class="text-content">${this.detailForm
                .dutySituation || '-'}</td>
            </tr>
            <tr>
              <th>事项</th>
              <th>数量</th>
              <th>详情</th>
              <th>事项</th>
              <th>数量</th>
              <th>详情</th>
            </tr>
            <tr>
              <th>交通事故</td>
              <td>${this.detailForm.trafficAccidentCount || '-'}</td>
              <td class="text-content">${this.detailForm
                .trafficAccidentDetail || '-'}</td>
              <th>人员伤亡</td>
              <td>${this.detailForm.casualtyCount || '-'}</td>
              <td class="text-content">${this.detailForm.casualtyDetail ||
                '-'}</td>
            </tr>
            <tr>
              <th>管制情况</td>
              <td>${this.detailForm.controlSituationCount || '-'}</td>
              <td class="text-content">${this.detailForm
                .controlSituationDetail || '-'}</td>
              <th>重大事件记录</td>
              <td>${this.detailForm.majorEventCount || '-'}</td>
              <td class="text-content">${this.detailForm.majorEventDetail ||
                '-'}</td>
            </tr>
            <tr>
              <th>拥堵情况</td>
              <td>${this.detailForm.congestionCount || '-'}</td>
              <td class="text-content">${this.detailForm.congestionDetail ||
                '-'}</td>
              <th>设备报修</td>
              <td>${this.detailForm.equipmentRepairCount || '-'}</td>
              <td class="text-content">${this.detailForm
                .equipmentRepairDetail || '-'}</td>
            </tr>
            <tr>
              <th>投诉记录</td>
              <td>${this.detailForm.complaintCount || '-'}</td>
              <td class="text-content">${this.detailForm.complaintDetail ||
                '-'}</td>
              <th>清障救援</td>
              <td>${this.detailForm.rescueCount || '-'}</td>
              <td class="text-content">${this.detailForm.rescueDetail ||
                '-'}</td>
            </tr>
            <tr>
              <th>外单位来访</td>
              <td>${this.detailForm.visitCount || '-'}</td>
              <td class="text-content">${this.detailForm.visitDetail ||
                '-'}</td>
              <th>来电询问</td>
              <td>${this.detailForm.inquiryCount || '-'}</td>
              <td class="text-content">${this.detailForm.inquiryDetail ||
                '-'}</td>
            </tr>
            <tr style='height: 300px; min-height: 300px;'>
              <th class='text-row'>交接情况</th>
              <td colspan="5" class="text-content">${this.detailForm
                .handoverSituation || '-'}</td>
            </tr>
            <tr style='height: 300px;'>
              <th class='text-row'>设施设备</th>
              <td colspan="5" class="text-content">${this.detailForm
                .facilityStatus || '-'}</td>
            </tr>
            <tr>
              <th>接班人员</th>
              <td colspan="5" class="text-content">${this.detailForm
                .nextShiftPersonnel || '-'}</td>
            </tr>
            <tr>
              <th>管理员意见</th>
              <td colspan="3" class="text-content">${this.detailForm
                .adminComment || '-'}</td>
              <th>管理员签字</th>
              <td>
                <div>${this.detailForm.adminName || '-'}</div>
                <div>${this.detailForm.adminAuditTime || '-'}</div>
              </td>
            </tr>
          </table>

          ${
            show
              ? `<div class="print-footer">
                打印时间: ${new Date().toLocaleString()}
            </div>`
              : ``
          }
            <script>
                setTimeout(function() {
                window.print();
                window.close();
                }, 200);
            <\/script>
        </body>
        </html>
      `
    },

    // 打开页面执行
    openPage() {},

    // 关闭页面执行
    closePage() {
      const {pubSub} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub
      })
      this.$nextTick(_ => {
        this.$refs.formInfo.$el.scrollTop = 0
      })
    },

    // 获取详情
    async getDetail(id) {
      this.formLoading = true
      try {
        let {
          startTime = '',
          endTime = '',
          roadInfos = [],
          ...detailForm
        } = await tableDetail(id)
        const roadInfosName = roadInfos.map(i => i.name).join('、')

        this.detailForm = {
          ...detailForm,
          dateRange: `${startTime.slice(0, 16)} 至 ${endTime.slice(0, 16)}`,
          roadInfosName
        }
      } finally {
        this.formLoading = false
      }
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';

::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep
  .el-descriptions
  .el-descriptions__body
  .el-descriptions-row
  .el-descriptions-item__cell.el-descriptions-item__label {
  width: auto;
  text-align: center;
}
.edit-add-detail {
  .form-content .el-form {
    display: flex;
    flex-direction: column;
    overflow-y: hidden !important;
  }

  .form-wrapper {
    flex: 1;
    overflow-y: auto;
    width: 1200px;
    margin: 0 auto;
    padding: 0 100px;
    position: relative;
    .title {
      margin: 10px 0;
      > div {
        font-size: 24px;
        text-align: center;
      }
    }
    .download-btn-container {
      position: absolute;
      top: 0;
      right: 10px;
      z-index: 1;
      margin-top: 10px;
    }
    .download-icon {
      font-size: 18px;
      margin-left: 10px;
      margin-right: 10px;
      color: #cceeff;
      cursor: pointer;
    }
    .action-icon {
      font-size: 18px;
      color: #cceeff;
      cursor: pointer;
    }
  }
}
.textarea-content {
  white-space: pre-line;
}
.text-row {
  font-size: 15px;
  writing-mode: vertical-rl;
  font-family: PingFang SC-Medium, PingFang SC, serif;
  color: #f0f0f0;
  letter-spacing: 12px;
}

.pdf-preview-dialog {
  .el-dialog__body {
    padding: 0;
    height: 80vh;
    display: flex;
    flex-direction: column;
  }
  .pdf-embed {
    flex: 1;
    min-height: 0;
  }
  .empty-pdf {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #999;
  }
}
</style>
