<template>
  <a-drawer
    :visible="visible"
    :width="drawerWidth"
    placement="right"
    :closable="false"
    :keyboard="false"
    @close="close"
    class="inspection-detail-drawer"
  >
    <div class="custom-header">
      <div class="header-left">
        <a-icon type="file-search" style="color: #1890ff; margin-right: 8px;" />
        <span class="header-title">安检结果详情</span>
        <a-tag
          v-if="inspectionData.basicInfo.auditStatus && isAudited && inspectionData.basicInfo.f_entry_status === '入户'"
          :color="inspectionData.basicInfo.auditStatus.class === 'approved' ? 'green' :
            inspectionData.basicInfo.auditStatus.class === 'rejected' ? 'red' : 'orange'"
          class="status-tag"
          style="margin-left: 12px;"
        >
          {{ inspectionData.basicInfo.auditStatus.text }}
        </a-tag>
      </div>

      <div class="header-right">
        <a-space :size="12">
          <a-space :size="8">
            <a-button type="default" size="default" @click="handlePrint" :loading="printLoading">
              <a-icon type="printer" />打印
            </a-button>
            <a-button type="default" size="default" @click="handleDownloadPDF" :loading="pdfLoading">
              <a-icon type="file-pdf" />下载PDF
            </a-button>
          </a-space>

          <a-space v-if="inspectionData.basicInfo.id && !isAuditedComputed && isAudited && inspectionData.basicInfo.f_entry_status === '入户'" :size="12">
            <a-button type="danger" size="default" danger @click="handleReject">
              <a-icon type="close" />审核不通过
            </a-button>
            <a-button type="primary" size="default" @click="handleApprove">
              <a-icon type="check" />审核通过
            </a-button>
          </a-space>
        </a-space>
      </div>
    </div>

    <div class="inspection-detail-container">
      <a-spin :spinning="loading" size="large">
        <div class="detail-content" id="inspection-detail-content">
          <div class="detail-grid" :class="{ 'no-history': !showHistoryPanel }">
            <div class="history-panel" v-if="showHistoryPanel">
              <history-list
                :history-list="inspectionData.historyList"
                :active-id="currentHistoryId"
                :is-audited="isAudited"
                @select="handleHistorySelect"
              />
            </div>

            <div class="content-panel">
              <div class="summary-section">
                <a-card class="section-card" :bordered="false">
                  <div class="section-grid">
                    <inspection-summary :basic-info="inspectionData.basicInfo" />
                    <signature-recording
                      :attachments="inspectionData.attachments"
                      @preview-signature="handlePreviewSignature"
                      @play-recording="handlePlayRecording"
                    />
                  </div>
                </a-card>
              </div>
              <div class="device-section" v-show="showAiDeviceTab">
                <ai-device-status
                  :device-list="aiDeviceItem"
                  :config="AICheckConfig?.XInspectionDetailDrawer?.AiDeviceStatus"
                  :check-total-count="checkTotalCount"
                  @preview-photos="(photos, idx) => handlePreviewPhotos(photos, idx)"
                  @process-item="handleProcessItem"
                />
              </div>
              <div class="device-section" v-show="inspectionData.deviceList.length > 0">
                <device-status
                  :device-list="inspectionData.deviceList"
                  @preview-photos="(photos, idx) => handlePreviewPhotos(photos, idx)"
                />
              </div>

              <div class="check-items-section" v-show="inspectionData.checkItems.length > 0">
                <check-items
                  :check-items="inspectionData.checkItems"
                />
              </div>

              <div class="hazard-gallery-section" v-show="inspectionData.basicInfo.f_entry_status === '入户'">
                <a-card class="section-card" :bordered="false">
                  <div class="section-grid">
                    <hazard-photos :hazard-list="inspectionData.hazardList" />
                    <div class="overall-photos">
                      <div class="photos-header">
                        <div class="photos-title">
                          <a-icon type="picture" style="color: #1890FF;" />
                          <span>安检照片</span>
                        </div>
                        <div class="photos-count" v-if="inspectionData.attachments.filePhotos && inspectionData.attachments.filePhotos.length > 0">
                          共 {{ totalPhotos }} 张
                        </div>
                      </div>
                      <div class="photos-content">
                        <div class="subsection-label"><a-icon type="home" />整体安检照片</div>
                        <file-image-group
                          :file-ids="inspectionData.attachments.filePhotos || []"
                          :service-name="effectiveServiceName"
                          :columns="5"
                          :image-size="60"
                          :gap="10"
                          alt-prefix="整体安检照片"
                          empty-text="暂无整体安检照片"
                        />
                      </div>
                      <div v-if="inspectionData?.attachments?.imagePhotos && inspectionData.attachments.imagePhotos.length > 0" class="photos-content">
                        <div class="subsection-label"><a-icon type="file-protect" />通知书照片</div>
                        <file-image-group
                          :file-ids="inspectionData.attachments.imagePhotos || []"
                          :service-name="effectiveServiceName"
                          :columns="5"
                          :image-size="60"
                          :gap="10"
                          alt-prefix="通知书照片"
                          empty-text="暂无通知书照片"
                        />
                      </div>
                      <div v-if="inspectionData?.attachments?.contractPhotos && inspectionData.attachments.contractPhotos.length > 0" class="photos-content">
                        <div class="subsection-label"><a-icon type="file" />合同照片</div>
                        <file-image-group
                          :file-ids="inspectionData.attachments.contractPhotos || []"
                          :service-name="effectiveServiceName"
                          :columns="5"
                          :image-size="60"
                          :gap="10"
                          alt-prefix="合同照片"
                          empty-text="暂无合同照片"
                        />
                      </div>
                    </div>
                  </div>
                </a-card>
              </div>
            </div>
          </div>
        </div>
      </a-spin>

      <!-- 统一图片预览（DeviceStatus 签名等场景使用） -->
      <image-preview-modal
        v-if="previewModal.visible"
        :visible="previewModal.visible"
        :image-url="previewModal.images && previewModal.images[previewModal.current]"
        :image-name="`预览图片${previewModal.current + 1}`"
        :append-to-body="true"
        @close="previewModal.visible = false"
      />

      <a-modal
        v-if="approveModal"
        v-model="approveModal.visible"
        :title="approveModal.type === 'reject' ? '不通过原因' : '审核确认'"
        :width="500"
        :z-index="2025"
        @ok="handleApproveConfirm"
        @cancel="handleApproveCancel"
        :confirmLoading="approveModal.loading"
      >
        <div v-if="approveModal.type === 'reject'">
          <a-form-model :model="approveModal.form" :rules="approveRules" ref="approveForm">
            <a-form-model-item label="不通过原因" prop="note">
              <a-textarea
                v-model="approveModal.form.note"
                :rows="4"
                placeholder="请输入不通过原因..."
              />
            </a-form-model-item>
          </a-form-model>
        </div>
        <div v-else>
          <p>确认审核通过该安检记录吗？</p>
        </div>
      </a-modal>
    </div>
  </a-drawer>
</template>

<script>
import { mapState } from 'vuex'
import inspectionService from './services/inspectionService'
import HistoryList from './components/HistoryList.vue'
import InspectionSummary from './components/InspectionSummary.vue'
import SignatureRecording from './components/SignatureRecording.vue'
import DeviceStatus from './components/DeviceStatus.vue'
import AiDeviceStatus from './components/AiDeviceStatus.vue'
import CheckItems from './components/CheckItems.vue'
import HazardPhotos from './components/HazardPhotos.vue'
import { FileImageGroup } from '@vue2-client/base-client/components/common/FileImage'
import ImagePreviewModal from '@vue2-client/base-client/components/common/ImagePreviewModal/ImagePreviewModal.vue'
import { printWithHtmlToImage, exportToPDFWithJpeg } from '@vue2-client/utils/htmlToImage'
import { runLogic } from '@vue2-client/services/api/common'

export default {
  name: 'XInspectionDetailDrawer',
  components: {
    HistoryList,
    InspectionSummary,
    SignatureRecording,
    DeviceStatus,
    AiDeviceStatus,
    CheckItems,
    HazardPhotos,
    FileImageGroup,
    ImagePreviewModal
  },
  props: {
    /**
     * 服务名，如 'af-safecheck'，用于通过 fileId 加载图片
     * 与 fileImageService 二选一，serviceName 优先
     */
    serviceName: { type: String, default: 'af-safecheck' },
    /** @deprecated 请改用 serviceName。保留此 prop 以向后兼容 */
    fileImageService: { type: Object, default: null },
    /** 是否启用审核功能 */
    isAudited: { type: Boolean, default: false }
  },
  provide () {
    // 将 serviceName 注入子组件（CheckItems 通过 inject 使用）
    return {
      serviceName: this.serviceName
    }
  },
  data () {
    return {
      loading: false,
      visible: false,
      currentId: null,
      currentHistoryId: null,
      showHistoryPanel: true,
      printLoading: false,
      pdfLoading: false,
      needRefresh: false,
      f_userinfo_id: null,
      windowWidth: typeof window !== 'undefined' ? window.innerWidth : 1200,
      inspectionData: {
        basicInfo: {},
        historyList: [],
        deviceList: [],
        checkItems: [],
        hazardList: [],
        attachments: {
          signature: null,
          recordings: [],
          filePhotos: [],
          imagePhotos: [],
          contractPhotos: []
        }
      },
      previewModal: { visible: false, images: [], current: 0 },
      approveModal: { visible: false, type: 'approve', form: { note: '' }, loading: false },
      approveRules: {
        note: [
          { required: true, message: '请输入不通过原因', trigger: 'blur' },
          { min: 5, message: '不通过原因至少5个字符', trigger: 'blur' }
        ]
      },
      // AI辅助相关配置
      AICheckConfig: {},
      pcAiInspectionAssistResult: {
        success: true,
        result: []
      },
    }
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
    totalPhotos () {
      const fileLen = this.inspectionData.attachments?.filePhotos?.length || 0
      const imageLen = this.inspectionData.attachments?.imagePhotos?.length || 0
      const contractLen = this.inspectionData.attachments?.contractPhotos?.length || 0
      return fileLen + imageLen + contractLen
    },
    /** 有效服务名：优先使用 serviceName prop */
    effectiveServiceName () {
      return this.serviceName || ''
    },
    isAuditedComputed () {
      return this.inspectionData.basicInfo.auditStatus &&
        (this.inspectionData.basicInfo.auditStatus.class === 'approved' ||
          this.inspectionData.basicInfo.auditStatus.class === 'rejected')
    },
    drawerWidth () {
      const windowWidth = this.windowWidth
      const width = windowWidth >= 1600 ? 90 : windowWidth >= 1200 ? 92 : windowWidth >= 1000 ? 94 : windowWidth >= 768 ? 95 : 98
      const historyPanelWidth = 340
      if (!this.showHistoryPanel) {
        const widthPx = windowWidth * (width / 100)
        return `${Math.max(0, widthPx - historyPanelWidth)}px`
      }
      return `${width}vw`
    },
    showAiDeviceTab () {
      return this.pcAiInspectionAssistResult.success && this.AICheckConfig?.enable
    },
    aiDeviceItem () {
      return this.pcAiInspectionAssistResult.result || []
    },
    checkTotalCount() {
      const data = this.inspectionData || {}

      // checkItems 的 items 总数
      const checkItemsCount = (data.checkItems || []).reduce(
        (total, item) => total + ((item.items || []).length),
        0
      )

      // deviceList 的 safetyChecks 总数
      const safetyChecksCount = (data.deviceList || []).reduce(
        (total, item) => total + ((item.safetyChecks || []).length),
        0
      )

      // 总检查项数量
      return checkItemsCount + safetyChecksCount
    }
  },
  mounted () {
    this._onResize = () => { this.windowWidth = window.innerWidth }
    window.addEventListener('resize', this._onResize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this._onResize)
  },
  methods: {
    async init (params) {
      this.AICheckConfig = await inspectionService.getAICheckConfig()
      try {
        this.loading = true
        this.visible = true
        this.currentId = params.id
        this.currentHistoryId = params.id
        this.f_userinfo_id = params.f_userinfo_id || null

        this.inspectionData = {
          basicInfo: {},
          historyList: [],
          deviceList: [],
          checkItems: [],
          hazardList: [],
          attachments: { signature: null, recordings: [], filePhotos: [], imagePhotos: [] }
        }

        this.showHistoryPanel = !params?.id && !!params?.f_userinfo_id

        if (params.f_userinfo_id) {
          const historyList = await inspectionService.getHistoryList(params.f_userinfo_id)
          if (historyList && historyList.length > 0) {
            this.inspectionData.historyList = historyList
            if (!params.id) {
              this.currentId = historyList[0].id
              this.currentHistoryId = historyList[0].id
            }
          } else {
            this.$message.error('未查询到当前用户的历史记录！')
            return
          }
        }

        await this.loadInspectionData(this.currentId, params.f_userinfo_id)
      } catch (error) {
        console.error('初始化详情页失败:', error)
        this.$message.error(error.message || '加载详情数据失败')
      } finally {
        this.loading = false
      }
    },

    async loadInspectionData (id, userInfoId = null) {
      const data = await inspectionService.getFullDetail(id, userInfoId)
      try {
        if (this.showAiDeviceTab) {
           const res = await runLogic('getPcAiInspectionAssistResultLogic', {
            paperId: this.currentId
          }, 'af-safecheck')
          console.warn('getPcAiInspectionAssistResultLogic', res)
          this.pcAiInspectionAssistResult = res
        }
      } catch (e) {
        console.error('getPcAiInspectionAssistResultLogic', e)
      }
      console.warn('datra', data)
      this.inspectionData = {
        ...data,
        historyList: this.inspectionData.historyList || data.historyList || []
      }
      if (this.inspectionData.historyList && this.inspectionData.historyList.length > 0) {
        const activeItem = this.inspectionData.historyList.find(item => item.isActive)
        if (activeItem) this.currentHistoryId = activeItem.id
      }
    },

    async handleHistorySelect (historyId) {
      if (historyId === this.currentHistoryId) return
      try {
        this.loading = true
        this.currentHistoryId = historyId
        const data = await inspectionService.switchToHistoryDetail(historyId, this.currentId, this.f_userinfo_id)
        this.inspectionData = { ...data, historyList: this.inspectionData.historyList || data.historyList || [] }
      } catch (error) {
        this.$message.error('切换历史记录失败')
      } finally {
        this.loading = false
      }
    },

    handleApprove () {
      this.approveModal = { visible: true, type: 'approve', form: { note: '' }, loading: false }
    },

    handleReject () {
      this.approveModal = { visible: true, type: 'reject', form: { note: '' }, loading: false }
    },

    async handleApproveConfirm () {
      if (this.approveModal.type === 'reject') {
        try {
          await this.$refs.approveForm.validate()
        } catch (error) {
          return
        }
      }
      try {
        this.approveModal.loading = true
        await inspectionService.approve({
          id: this.currentId,
          state: this.approveModal.type === 'approve' ? '通过' : '不通过',
          note: this.approveModal.form.note,
          user: this.currUser
        })
        this.$message.success(`审核${this.approveModal.type === 'approve' ? '通过' : '不通过'}操作成功`)
        await this.loadInspectionData(this.currentId)
        this.needRefresh = true
        this.handleApproveCancel()
      } catch (error) {
        this.$message.error(error.message || '审核操作失败')
      } finally {
        this.approveModal.loading = false
      }
    },

    handleApproveCancel () {
      this.approveModal = { visible: false, type: 'approve', form: { note: '' }, loading: false }
    },

    handlePreviewSignature (signature) {
      if (!signature) return
      const url = typeof signature === 'string' ? signature : (signature?.url || signature?.imageUrl)
      if (url) this.handlePreviewPhotos([url], 0)
    },

    handlePlayRecording () {
      this.$message.info('录音播放功能待实现')
    },

    handlePreviewPhotos (photos, current = 0) {
      this.previewModal = {
        visible: true,
        images: Array.isArray(photos) ? (typeof photos[0] === 'string' ? photos : photos.map(p => p?.url || p?.imageUrl).filter(Boolean)) : [photos],
        current
      }
    },

    /**
     * 处理AI检测项（检测结果不一致/新增隐患）
     */
    async handleProcessItem (item) {
      console.warn('handleProcessItem', item)
      this.$confirm({
        title: `${item.name || ''}`,
        content: '确认是否将 AI 检测结果修正为与人工判定结果保持一致',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        async onOk () {
          console.log('OK')
          try {
            this.loading = true
            const params = {
              ...item
            }

            delete params.options
            await runLogic('updatePcAiInspectionAssistResultLogic', params, 'af-hone')
            this.$message.success('处理成功')
            await this.loadInspectionData(this.currentId)
          } catch (error) {
            console.error('处理AI检测项失败:', error)
            this.$message.error(error.message || '处理失败')
          } finally {
            this.loading = false
          }
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },

    /**
     * 打印/导出前的布局调整（隐藏历史面板，展开单列布局）
     * 返回还原函数，调用后恢复原始布局
     */
    _getPrintSetup () {
      return async (element) => {
        const historyPanel = element.querySelector('.history-panel')
        const detailGrid = element.querySelector('.detail-grid')
        const contentPanel = element.querySelector('.content-panel')
        const origHistory = historyPanel ? historyPanel.style.display : ''
        const origGrid = detailGrid ? detailGrid.style.cssText : ''
        const origContent = contentPanel ? contentPanel.style.padding : ''
        const origElPadding = element.style.padding
        const origElBg = element.style.background
        if (historyPanel) historyPanel.style.display = 'none'
        if (detailGrid) {
          detailGrid.style.display = 'block'
          detailGrid.style.gridTemplateColumns = '1fr'
        }
        element.style.padding = '0'
        element.style.background = '#ffffff'
        if (contentPanel) contentPanel.style.padding = '8px'
        return () => {
          if (historyPanel) historyPanel.style.display = origHistory
          if (detailGrid) detailGrid.style.cssText = origGrid
          if (contentPanel) contentPanel.style.padding = origContent
          element.style.padding = origElPadding
          element.style.background = origElBg
        }
      }
    },

    async handlePrint () {
      try {
        this.printLoading = true
        this.$message.loading('正在准备打印数据，请稍候...', 0)
        await printWithHtmlToImage('inspection-detail-content', '安检结果详情', {
          beforePrint: this._getPrintSetup(),
          pixelRatio: 1.5
        })
        this.$message.destroy()
        this.$message.success('打印预览已生成')
      } catch (error) {
        console.error('打印失败:', error)
        this.$message.destroy()
        this.$message.error('打印失败')
      } finally {
        setTimeout(() => { this.printLoading = false }, 1000)
      }
    },

    async handleDownloadPDF () {
      try {
        this.pdfLoading = true
        this.$message.loading('正在准备PDF数据，请稍候...', 0)
        const contentElement = document.getElementById('inspection-detail-content')
        if (!contentElement) {
          this.$message.destroy()
          this.$message.error('未找到可导出内容')
          return
        }
        const timestamp = new Date().toISOString().slice(0, 19).replace(/[-:T]/g, '')
        await exportToPDFWithJpeg(`安检结果详情_${timestamp}`, 'inspection-detail-content', {
          beforeExport: this._getPrintSetup(),
          pixelRatio: 1.5,
          quality: 0.85
        })
        this.$message.destroy()
        this.$message.success('PDF导出成功')
      } catch (error) {
        console.error('PDF导出失败:', error)
        this.$message.destroy()
        this.$message.error('PDF导出失败')
      } finally {
        setTimeout(() => { this.pdfLoading = false }, 500)
      }
    },

    close () {
      if (this.needRefresh) {
        this.$emit('refresh')
        this.needRefresh = false
      }
      this.visible = false
      this.currentId = null
      this.currentHistoryId = null
      this.showHistoryPanel = true
      this.inspectionData = {
        basicInfo: {},
        historyList: [],
        deviceList: [],
        checkItems: [],
        hazardList: [],
        attachments: { signature: null, recordings: [], filePhotos: [], imagePhotos:  [] }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.custom-header {
  position: sticky;
  top: 0;
  z-index: 1000;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  background: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);

  .header-left { display: flex; align-items: center; flex: 1; }
  .header-title { font-size: 16px; font-weight: 600; color: #1f2937; }
  .header-right { display: flex; align-items: center; flex-shrink: 0; }
}

.inspection-detail-drawer {
  :deep(.ant-drawer-body) { padding: 0 !important; height: 100% !important; overflow: hidden !important; display: flex; flex-direction: column; }
  :deep(.ant-drawer-content-wrapper) { height: 100vh !important; }
  :deep(.ant-drawer-content) { height: 100vh !important; display: flex; flex-direction: column; }
}

.inspection-detail-container {
  flex: 1;
  background: #f0f2f5;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.detail-content {
  flex: 1;
  padding: 16px;
  height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

.detail-grid {
  display: grid;
  grid-template-columns: var(--history-panel-width, 340px) 1fr;
  gap: 16px;
  flex: 1;
  min-height: 0;
  height: calc(100vh - 60px - 32px);

  &.no-history { grid-template-columns: 1fr; }
}

.history-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.content-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto !important;
  overflow-x: hidden;
  padding-right: 8px;
  min-height: 0;
  flex: 1;
}

.section-card { box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; }

.section-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  min-height: auto;
  align-items: stretch;
}

.overall-photos {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: white;
  display: flex;
  flex-direction: column;
}

.photos-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.photos-title { display: flex; align-items: center; gap: 8px; font-size: 16px; font-weight: 600; color: #1f2937; }
.photos-count { font-size: 14px; color: #6b7280; font-weight: 400; }
.photos-content { padding: 16px; }

@media (max-width: 1024px) {
  .detail-grid { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
  .history-panel { max-height: 200px; }
  .section-grid { grid-template-columns: 1fr; }
}
.subsection-label { display: flex; align-items: center; gap: 6px; font-size: 12px; color: #6b7280; font-weight: 500; margin-bottom: 12px; }
</style>
