<script lang="ts" setup>
import { IotStatApi } from '@/api/pms/stat'
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 TEAM_TABLE_HEIGHT = 500
const DEFAULT_TIME_RANGE = [
  dayjs().subtract(7, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  dayjs().subtract(1, 'day').endOf('day').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)
const tableHeight = '100%'

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.getRyTeamRate({
      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.getRyRate({ 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-full flex flex-col">
    <div class="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="ry-device-list-panel__picker">
        <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"
          class="ry-device-list-panel__picker-input"
          @change="handleDateChange" />
      </div>
    </div>
    <!-- v-loading="loading" -->
    <div class="device-list-panel__body flex flex-col flex-1 min-h-0">
      <el-table
        :data="tableData"
        :height="tableHeight"
        class="device-list-table"
        @row-click="handleRowClick">
        <el-table-column prop="projectDeptName" label="项目部" align="center" />
        <el-table-column prop="teamCount" label="队伍数量" width="72" align="center" />
        <el-table-column prop="cumulativeDays" label="累计天数" width="72" align="center" />
        <el-table-column prop="constructionDays" label="施工天数" width="72" 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="设备利用率" 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');

.ry-device-list-panel__picker {
  display: flex;
  width: calc(260px * var(--kb-scale, 1));
  align-items: center;
}

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

  :deep(.el-input__wrapper) {
    min-height: calc(28px * var(--kb-scale, 1));
    padding: 0 calc(10px * var(--kb-scale, 1));
  }

  :deep(.el-range-input),
  :deep(.el-range-separator) {
    font-size: calc(12px * var(--kb-scale, 1));
  }

  :deep(.el-range__icon),
  :deep(.el-range__close-icon) {
    font-size: calc(14px * var(--kb-scale, 1));
  }
}

.device-list-table {
  :deep(.el-table__header-wrapper th.el-table__cell) {
    font-size: calc(17px * var(--kb-scale, 1));
    line-height: 1.25;
  }

  :deep(.el-table__body td.el-table__cell) {
    font-size: calc(15px * var(--kb-scale, 1));
  }
}
</style>

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