<script lang="ts" setup>
import { IotStatApi } from '@/api/pms/stat'
import download from '@/utils/download'
import dayjs from 'dayjs'
import type { Ref } from 'vue'

interface RhDeviceListRow {
  projectDeptId: number
  projectDeptName: string
  teamCount: number
  sgTeamCount: number
  zbTeamCount: number
  dmTeamCount: number
  hourUtilizationRate: number
  yearHourUtilizationRate: number
  waterInjection: number
  yearWaterInjection: number
  gasInjection: number
  yearGasInjection: number
  sort?: number | null
  productionSummary: string
}

interface RhTeamRateRow {
  teamName: string
  cumulativeDays: number
  constructionDays: number
  utilizationRate: number
}

const TABLE_HEIGHT = 220
const TEAM_TABLE_HEIGHT = 500
const DEFAULT_DATE = dayjs().subtract(1, 'day').format('YYYY-MM-DD')

const props = withDefaults(
  defineProps<{
    pageMode?: 'compact' | 'full'
  }>(),
  {
    pageMode: 'compact'
  }
)

const createDate = ref(DEFAULT_DATE)
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<RhDeviceListRow[]>([])
const teamDialogVisible = ref(false)
const teamLoading = ref(false)
const currentProjectDeptName = ref('')
const teamList = ref<RhTeamRateRow[]>([])
const kbScale = inject<Ref<number>>('rhKbScale', ref(1))

const tableData = computed(() => list.value)
const createTime = computed(() => [
  dayjs(createDate.value).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  dayjs(createDate.value).endOf('day').format('YYYY-MM-DD HH:mm:ss')
])
const tableHeight = computed<number | string>(() =>
  props.pageMode === 'full' ? '100%' : Math.round(TABLE_HEIGHT * kbScale.value)
)

function formatRate(value?: number | null) {
  return value === null || value === undefined ? '--' : `${(Number(value) * 100).toFixed(2)}%`
}

function formatInjection(value?: number | null) {
  return value === null || value === undefined ? '--' : value
}

function handleDateChange() {
  getList()
}

const message = useMessage()

async function handleExport() {
  try {
    await message.exportConfirm()

    exportLoading.value = true
    const res = await IotStatApi.exportRhDashboard({ createTime: createTime.value })

    download.excel(res, `瑞恒看板-${createDate.value}.xlsx`)
  } finally {
    exportLoading.value = false
  }
}

async function handleRowClick(row: RhDeviceListRow) {
  currentProjectDeptName.value = row.projectDeptName || '项目部'
  teamDialogVisible.value = true
  teamLoading.value = true

  try {
    const res = await IotStatApi.getRhTeamRate({
      deptId: row.projectDeptId,
      createTime: createTime.value
    })
    teamList.value = Array.isArray(res) ? (res as RhTeamRateRow[]) : []
  } catch (error) {
    console.error('获取瑞恒队伍明细失败:', error)
    teamList.value = []
  } finally {
    teamLoading.value = false
  }
}

function handleDialogClosed() {
  teamList.value = []
  currentProjectDeptName.value = ''
  teamLoading.value = false
}

async function getList() {
  loading.value = true

  try {
    const res = await IotStatApi.getRhRate({ createTime: createTime.value })
    list.value = Array.isArray(res) ? (res as RhDeviceListRow[]) : []
  } catch (error) {
    console.error('获取瑞恒项目部汇总失败:', error)
    list.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div
    class="panel device-list-panel w-full min-h-0 flex flex-col"
    :class="{ 'device-list-panel--full': props.pageMode === 'full' }">
    <div class="panel-title device-list-panel__title flex items-center justify-between">
      <div class="kb-panel-title-text flex items-center">
        <div class="icon-decorator">
          <span></span>
          <span></span>
        </div>
        项目部统计
      </div>
      <div class="device-list-panel__tools">
        <el-date-picker
          v-model="createDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择日期"
          :clearable="false"
          class="device-list-panel__picker-input"
          @change="handleDateChange" />
        <el-button type="success" plain :loading="exportLoading" @click="handleExport">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </div>
    </div>
    <div class="device-list-panel__body flex flex-col flex-1 min-h-0">
      <el-table
        v-loading="loading"
        :data="tableData"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgb(222 236 252 / 72%)"
        border
        class="device-list-table"
        :class="{ 'device-list-table--full': props.pageMode === 'full' }"
        @row-click="handleRowClick">
        <el-table-column prop="projectDeptName" label="项目部" width="140" align="center" />
        <el-table-column prop="teamCount" label="队伍总数" width="124" align="center" />
        <el-table-column prop="dmTeamCount" label="待命" width="124" align="center" />
        <el-table-column prop="zbTeamCount" label="施工准备" width="124" align="center" />
        <el-table-column prop="sgTeamCount" label="施工队伍" width="124" align="center" />
        <el-table-column label="注入量(万方)" width="170" align="center">
          <template #default="{ row }">
            <div class="device-list-table__multi-value">
              <span>日注气：{{ formatInjection(row.gasInjection) }}</span>
              <span>累注气：{{ formatInjection(row.yearGasInjection) }}</span>
              <span>日注水：{{ formatInjection(row.waterInjection) }}</span>
              <span>累注水：{{ formatInjection(row.yearWaterInjection) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="运行时效" width="220" align="center">
          <template #default="{ row }">
            <div class="device-list-table__multi-value">
              <span>当日运行时效：{{ formatRate(row.hourUtilizationRate) }}</span>
              <span>平均运行时效：{{ formatRate(row.yearHourUtilizationRate) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productionSummary" label="生产动态概述" min-width="220" align="left">
          <template #default="{ row }">
            <div class="device-list-table__summary">{{ row.productionSummary || '--' }}</div>
          </template>
        </el-table-column>

        <template #empty>
          <div class="h-full min-h-[220px] flex items-center justify-center">
            <el-empty description="暂无数据" :image-size="72" />
          </div>
        </template>
      </el-table>
    </div>
    <el-dialog
      v-model="teamDialogVisible"
      :title="`${currentProjectDeptName || '项目部'}队伍明细`"
      width="1200px"
      destroy-on-close
      class="device-list-dialog"
      @closed="handleDialogClosed"
      append-to-body>
      <el-table
        v-loading="teamLoading"
        :data="teamList"
        :height="TEAM_TABLE_HEIGHT"
        class="team-list-table">
        <el-table-column prop="teamName" label="队伍名称" min-width="220" align="center" />
        <el-table-column prop="cumulativeDays" label="累计天数" min-width="140" align="center" />
        <el-table-column prop="constructionDays" label="施工天数" min-width="140" align="center" />
        <el-table-column label="设备利用率" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatRate(row.utilizationRate) }}
          </template>
        </el-table-column>

        <template #empty>
          <div class="h-full min-h-[220px] flex items-center justify-center">
            <el-empty description="暂无队伍明细" :image-size="72" />
          </div>
        </template>
      </el-table>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');

.device-list-panel.device-list-panel--full {
  height: 100%;
  min-height: 0;
  margin-top: 0;
}

.device-list-panel__tools {
  display: flex;
  align-items: center;
  gap: calc(8px * var(--kb-scale, 1));
}

.device-list-panel__picker-input {
  width: calc(160px * var(--kb-scale, 1)) !important;
}

.device-list-table--full {
  :deep(.el-scrollbar__view) {
    display: block;
    height: 100%;
  }

  :deep(.el-table__body) {
    height: 100%;
  }

  :deep(.el-table__body tbody) {
    height: 100%;
  }
}

.device-list-table {
  :deep(.el-table__header-wrapper th.el-table__cell) {
    color: #10233c;
    background: #b5cde7;
    border-color: #fff;
  }

  :deep(.el-table__body td.el-table__cell) {
    color: #07192c;
    background: #89b3de;
    border-color: #fff;
  }

  :deep(.el-table__body tr:nth-child(2n) td.el-table__cell) {
    background: #b8cee5;
  }

  :deep(.el-table__row:hover > td.el-table__cell) {
    background: #75a5d6 !important;
  }
}

.device-list-table__multi-value {
  display: flex;
  flex-direction: column;
  gap: calc(4px * var(--kb-scale, 1));
  line-height: 1.35;
}

.device-list-table__summary {
  line-height: 1.5;
  white-space: pre-wrap;
  overflow-wrap: anywhere;
}
</style>

<style>
@import url('@/styles/kb-dialog.scss');
</style>
