<script lang="ts" setup>
import { IotStatApi } from '@/api/pms/stat'
import { rangeShortcuts } from '@/utils/formatTime'
import dayjs from 'dayjs'

interface RhDeviceListRow {
  projectDeptId: number
  projectDeptName: string
  teamCount: number
  cumulativeDays: number
  constructionDays: number
  utilizationRate: number
  gasInjection: number
  sort?: number | null
}

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

const TABLE_HEIGHT = 220
const TEAM_TABLE_HEIGHT = 500
const DEFAULT_TIME_RANGE = rangeShortcuts[2]
  .value()
  .map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))

const createTime = ref<string[]>(DEFAULT_TIME_RANGE)
const loading = ref(false)
const list = ref<RhDeviceListRow[]>([])
const teamDialogVisible = ref(false)
const teamLoading = ref(false)
const currentProjectDeptName = ref('')
const teamList = ref<RhTeamRateRow[]>([])

const tableData = computed(() => list.value)

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

function formatGasInjection(value?: number | null) {
  return (Number(value ?? 0) / 10000).toFixed(2)
}

function handleDateChange() {
  getList()
}

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 w-full h-[280px] flex flex-col mt-3">
    <div class="panel-title h-9 flex items-center justify-between">
      <div class="flex items-center">
        <div class="icon-decorator">
          <span></span>
          <span></span>
        </div>
        项目部统计
      </div>
      <div class="w-260px! -translate-y-[4px]">
        <el-date-picker
          v-model="createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          :clearable="false"
          :shortcuts="rangeShortcuts"
          class="w-260px!"
          @change="handleDateChange"
        />
      </div>
    </div>
    <!-- v-loading="loading" -->
    <div class="flex-1 min-h-0 px-4 py-2">
      <el-table
        :data="tableData"
        :height="TABLE_HEIGHT"
        class="device-list-table"
        @row-click="handleRowClick"
      >
        <el-table-column prop="projectDeptName" label="项目部" min-width="220" align="center" />
        <el-table-column prop="teamCount" label="队伍数量" min-width="120" align="center" />
        <el-table-column prop="cumulativeDays" label="累计天数" min-width="120" align="center" />
        <el-table-column prop="constructionDays" label="施工天数" min-width="120" align="center" />
        <el-table-column label="注气量(万方)" min-width="150" align="center">
          <template #default="{ row }">
            {{ formatGasInjection(row.gasInjection) }}
          </template>
        </el-table-column>
        <el-table-column label="设备利用率" min-width="140" 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>
    </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');
</style>

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