<script lang="ts" setup>
import { QhseMonthReportSummaryApi } from '@/api/pms/qhse'
import type { QhseMonthReportItem, ReportCompanyColumn, ReportMetricRow } from './types'
import dayjs from 'dayjs'
import { computed, ref, watch } from 'vue'

interface Props {
  visible: boolean
  yearMonths: string | undefined
}

interface TableRow {
  category: string
  label: string
  field: keyof QhseMonthReportItem
  summary: string
  [key: string]: string | keyof QhseMonthReportItem
}

const props = defineProps<Props>()
const emits = defineEmits(['update:visible'])

const loading = ref(false)
const reportList = ref<QhseMonthReportItem[]>([])

const metricRows: ReportMetricRow[] = [
  { category: '人工时和安全行驶公里数', label: '员工人数', field: 'employee', unit: '人' },
  { category: '人工时和安全行驶公里数', label: '分包商人数', field: 'subcontractors', unit: '人' },
  {
    category: '人工时和安全行驶公里数',
    label: '安全行驶里程数（公里）',
    field: 'drivingMileage',
    unit: '公里'
  },
  {
    category: '人工时和安全行驶公里数',
    label: '总人工时数（小时）',
    field: 'totalManHours',
    unit: '小时'
  },
  { category: 'QHSE被动性指标统计', label: '无事故累计天数', field: 'withoutAccident', unit: '天' },
  { category: 'QHSE被动性指标统计', label: '死亡事故（起）', field: 'fatality', unit: '起' },
  { category: 'QHSE被动性指标统计', label: '损失工时事故（起）', field: 'injury', unit: '起' },
  {
    category: 'QHSE被动性指标统计',
    label: '工作受限事件（起）',
    field: 'restrictedCase',
    unit: '起'
  },
  { category: 'QHSE被动性指标统计', label: '医疗处理事件（起）', field: 'medicalCase', unit: '起' },
  { category: 'QHSE被动性指标统计', label: '急救箱事件（起）', field: 'firstAidCase', unit: '起' },
  { category: 'QHSE被动性指标统计', label: '交通事故（起）', field: 'vehicleAccident', unit: '起' },
  { category: 'QHSE被动性指标统计', label: '未遂事件（起）', field: 'nearMiss', unit: '起' },
  { category: 'QHSE被动性指标统计', label: '泄漏事件（起）', field: 'spill', unit: '起' },
  {
    category: 'QHSE被动性指标统计',
    label: '违反保命规则的次数（次）',
    field: 'lifeSavingRules',
    unit: '次'
  },
  { category: 'QHSE主动性指标统计', label: '班前会（次）', field: 'toolboxTalk', unit: '次' },
  {
    category: 'QHSE主动性指标统计',
    label: 'QHSE管理委员会会议（次）',
    field: 'committeeMeeting',
    unit: '次'
  },
  {
    category: 'QHSE主动性指标统计',
    label: 'QHSE月度例会（次）',
    field: 'monthlyMeeting',
    unit: '次'
  },
  {
    category: 'QHSE主动性指标统计',
    label: '公司级隐患排查（次）',
    field: 'companyHazard',
    unit: '次'
  },
  { category: 'QHSE主动性指标统计', label: 'QHSE检查（次）', field: 'qhseInspection', unit: '次' },
  { category: 'QHSE主动性指标统计', label: '安全观察卡（张）', field: 'socCards', unit: '张' },
  { category: 'QHSE主动性指标统计', label: '工作许可审核（份）', field: 'ptwAudit', unit: '份' },
  { category: 'QHSE主动性指标统计', label: '工作安全分析（次）', field: 'jsa', unit: '次' },
  { category: 'QHSE主动性指标统计', label: '演练次数', field: 'drills', unit: '次' },
  { category: 'QHSE主动性指标统计', label: 'QHSE培训次数', field: 'training', unit: '次' },
  {
    category: 'QHSE主动性指标统计',
    label: 'QHSE培训人次',
    field: 'participantsTraining',
    unit: '人次'
  },
  {
    category: 'QHSE主动性指标统计',
    label: 'QHSE培训学时数（小时）',
    field: 'trainingsHours',
    unit: '小时'
  },
  { category: '环境数据', label: '水消耗（吨）', field: 'waterConsumption', unit: '吨' },
  { category: '环境数据', label: '柴油消耗（升）', field: 'dieselConsumption', unit: '升' },
  {
    category: '环境数据',
    label: '用电量（千瓦时）',
    field: 'electricityConsumption',
    unit: '千瓦时'
  },
  {
    category: '环境数据',
    label: '天然气消耗量（立方米）',
    field: 'naturalGasConsumption',
    unit: '立方米'
  }
  // { category: '其他信息', label: '备注', field: 'remark', unit: '/' }
]

const companyColumns = computed<ReportCompanyColumn[]>(() =>
  reportList.value.map((item, index) => ({
    key: getCompanyKey(index),
    label: item.deptName || `公司${index + 1}`
  }))
)

const companyRowMap = computed<Record<string, QhseMonthReportItem>>(() =>
  Object.fromEntries(reportList.value.map((item, index) => [getCompanyKey(index), item]))
)

const categoryRowSpanMap = computed(() =>
  metricRows.reduce<Record<string, number>>((acc, item) => {
    acc[item.category] = (acc[item.category] || 0) + 1
    return acc
  }, {})
)

const firstRowIndexByCategory = computed(() =>
  metricRows.reduce<Record<string, number>>((acc, item, index) => {
    if (acc[item.category] === undefined) acc[item.category] = index
    return acc
  }, {})
)

const tableRows = computed<TableRow[]>(() =>
  metricRows.map((row) => {
    const companyValues = Object.fromEntries(
      companyColumns.value.map((company) => [
        company.key,
        getMetricCompanyValue(row.field, company.key)
      ])
    )

    return {
      category: row.category,
      label: row.label,
      field: row.field,
      summary: getMetricSummaryValue(row.field),
      ...companyValues
    }
  })
)

async function loadDetail() {
  loading.value = true
  try {
    const res = await QhseMonthReportSummaryApi.getQhseMonthReportSummary({
      yearMonths: props.yearMonths
    })
    reportList.value = ((res as any)?.data?.list ??
      (res as any)?.list ??
      []) as QhseMonthReportItem[]
  } finally {
    loading.value = false
  }
}

function handleVisibleChange(visible: boolean) {
  emits('update:visible', visible)
  if (!visible) reportList.value = []
}

function getCompanyKey(index: number) {
  return `company_${index}`
}

function formatMetricValue(value: QhseMonthReportItem[keyof QhseMonthReportItem]) {
  if (value === undefined || value === null || value === '') return '-'
  const numericValue = Number(value)
  if (!Number.isNaN(numericValue) && String(value).trim() !== '') {
    return Number.isInteger(numericValue) ? String(numericValue) : numericValue.toFixed(2)
  }
  return String(value)
}

function getMetricCompanyValue(field: keyof QhseMonthReportItem, companyKey: string) {
  const rowData = companyRowMap.value[companyKey]
  return formatMetricValue(rowData?.[field])
}

function getMetricSummaryValue(field: keyof QhseMonthReportItem) {
  const values = reportList.value
    .map((item) => item[field])
    .filter((value) => value !== undefined && value !== null && value !== '')

  if (!values.length) return '-'

  if (field === 'remark') {
    return values.map((value) => String(value)).join('；')
  }

  const numericValues = values.map((value) => Number(value))
  if (numericValues.every((value) => !Number.isNaN(value))) {
    if (field === 'withoutAccident') {
      return String(Math.min(...numericValues))
    }

    const total = numericValues.reduce((sum, value) => sum + value, 0)
    return Number.isInteger(total) ? String(total) : total.toFixed(2)
  }

  return values.map((value) => String(value)).join('；')
}

function tableSpanMethod({
  row,
  column,
  rowIndex
}: {
  row: TableRow
  column: { property?: string }
  rowIndex: number
}) {
  if (column.property !== 'category') return { rowspan: 1, colspan: 1 }
  const firstIndex = firstRowIndexByCategory.value[row.category]
  if (firstIndex !== rowIndex) return { rowspan: 0, colspan: 0 }
  return { rowspan: categoryRowSpanMap.value[row.category], colspan: 1 }
}

const previewMeta = computed(() => {
  const firstItem = reportList.value[0]
  if (!firstItem) return { personName: '-', createTime: '-' }

  const date = dayjs(firstItem.createTime)
  return {
    personName: firstItem.personName || '-',
    createTime: date.isValid() ? date.format('YYYY-MM-DD') : '-'
  }
})

watch(
  () => [props.visible, props.yearMonths] as const,
  async ([visible, yearMonths], previous = [false, undefined] as const) => {
    const [previousVisible, previousYearMonths] = previous
    if (!visible || !yearMonths) return
    if (visible === previousVisible && yearMonths === previousYearMonths) return
    await loadDetail()
  },
  { immediate: true }
)
</script>

<template>
  <el-drawer
    :model-value="visible"
    :size="'100%'"
    :with-header="false"
    destroy-on-close
    body-class="qhse-report-preview-drawer__body"
    @update:model-value="handleVisibleChange">
    <div class="qhse-report-preview" v-loading="loading">
      <div class="qhse-report-preview__sheet">
        <div class="qhse-report-preview__sheet-title">QHSE 月度报告</div>
        <div class="qhse-report-preview__meta">
          <span>年月：{{ props.yearMonths || '-' }}</span>
          <!-- <span>填报人：{{ previewMeta.personName }}</span>
          <span>创建日期：{{ previewMeta.createTime }}</span> -->
        </div>

        <div class="qhse-report-preview__table-wrap">
          <el-table
            :data="tableRows"
            :span-method="tableSpanMethod"
            border
            stripe
            height="60vh"
            class="qhse-report-preview__el-table">
            <el-table-column
              prop="category"
              label="基本信息"
              fixed="left"
              width="170"
              align="center" />
            <el-table-column prop="label" label="单位" fixed="left" width="240" align="center" />
            <el-table-column
              v-for="company in companyColumns"
              :key="company.key"
              :prop="company.key"
              :label="company.label"
              min-width="140"
              align="center" />
            <el-table-column
              prop="summary"
              label="汇总"
              min-width="180"
              align="center"
              fixed="right" />
          </el-table>
        </div>
      </div>

      <div class="qhse-report-preview__footer">
        <el-button size="large" type="primary" @click="handleVisibleChange(false)">关闭</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped lang="scss">
.qhse-report-preview {
  display: flex;
  min-height: 100%;
  flex-direction: column;
  gap: 20px;
  background: linear-gradient(180deg, #eef4ff 0%, #f7f9fc 220px, #eef2f7 100%);
  padding: 24px;
}

.qhse-report-preview__sheet {
  display: flex;
  min-height: 0;
  flex: 1;
  flex-direction: column;
  gap: 16px;
  background: #fff;
  border: 1px solid #d8e0ef;
  border-radius: 10px;
  box-shadow: 0 18px 50px rgb(35 51 84 / 10%);
  padding: 24px;
}

.qhse-report-preview__sheet-title {
  text-align: center;
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 2px;
  color: #203354;
}

.qhse-report-preview__meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 24px;
  color: #52627f;
  font-size: 14px;
}

.qhse-report-preview__table-wrap {
  min-height: 0;
  flex: 1;
}

.qhse-report-preview__footer {
  position: sticky;
  bottom: 0;
  z-index: 20;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: auto;
  padding: 12px;
  border-radius: 10px;
  background: rgb(255 255 255 / 90%);
  backdrop-filter: blur(8px);
}

@media (width < 768px) {
  .qhse-report-preview {
    padding: 12px;
    gap: 12px;
  }

  .qhse-report-preview__sheet {
    padding: 14px;
    border-radius: 14px;
  }

  .qhse-report-preview__sheet-title {
    font-size: 22px;
    letter-spacing: 1px;
  }
}

:deep(.qhse-report-preview-drawer__body) {
  height: 100%;
  overflow-y: auto;
  padding: 0;
}

:deep(.qhse-report-preview__el-table) {
  --el-table-header-bg-color: #dbe8ff;
  --el-table-header-text-color: #183153;
  --el-table-row-hover-bg-color: #f8fbff;
}

:deep(.qhse-report-preview__el-table .el-table__cell) {
  padding: 0;
}

:deep(.qhse-report-preview__el-table th.el-table__cell) {
  font-weight: 700;
}

:deep(.qhse-report-preview__el-table .cell) {
  padding: 12px 14px;
  line-height: 1.5;
  word-break: break-word;
}

:deep(.qhse-report-preview__el-table .el-table__body-wrapper td:last-child) {
  background: #eef4ff;
  color: #14346b;
  font-weight: 700;
}

:deep(.qhse-report-preview__el-table .el-table__body-wrapper td:nth-child(2)) {
  background: #f8fbff;
  font-weight: 600;
}

:deep(.qhse-report-preview__el-table .el-table__body-wrapper td:nth-child(n + 3):not(:last-child)) {
  color: #0f3f8f;
  font-weight: 600;
}
</style>
