<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="表名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入表名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="所属区域" prop="orgId">
        <el-select v-model="queryParams.orgId" filterable clearable placeholder="请选择所属区域" class="!w-240px">
          <el-option v-for="opt in orgOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker v-model="queryParams.timeRange" type="datetimerange" value-format="YYYY-MM-DD HH"
          format="YYYY-MM-DD HH" start-placeholder="请选择开始时间" end-placeholder="请选择结束时间"
          :default-time="[new Date('2000-01-01 00:00:00'), new Date('2000-01-01 23:00:00')]"
          :disabled-time="getDisabledTime" class="!w-360px " popper-class="energydevicecheckPicker"
          :teleported="false" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table ref="tableRef" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" row-key="id"
      :expand-row-keys="expandRowKeys" :row-class-name="getRowClassName" style="margin-top: 20px; min-height: 50vh"
      @row-click="handleRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="expand" width="52">
        <template #default="scope">
          <el-table v-if="getPointDetailsRows(scope.row).length" :data="getPointDetailsRows(scope.row)"
            :show-overflow-tooltip="true" size="small" border>
            <el-table-column label="参数名称" prop="pointName" min-width="140" />
            <el-table-column label="最早采集值" prop="earliestValue" min-width="120" />
            <el-table-column label="最早采集时间" prop="earliestTime" min-width="170" />
            <el-table-column label="最新值" prop="latestValue" min-width="120" />
            <el-table-column label="最新采集时间" prop="latestTime" min-width="170" />
            <el-table-column label="能耗用量" prop="difference" min-width="120" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" width="70">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="表名称" align="center" prop="name" min-width="120" />
      <el-table-column label="能源类型" align="center" prop="deviceTypeName" min-width="100" />
      <el-table-column label="所属区域" align="center" prop="orgName" min-width="100" />
      <el-table-column label="能源用量" align="center" prop="energyConsumption" min-width="120" />
      <el-table-column label="班次" align="center" min-width="90">
        <template #default>
          <el-tag type="success">早班</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" min-width="170">
        <template #default="scope">
          {{ scope.row.startTime ?? scope.row.earliestDataTime ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" min-width="170">
        <template #default="scope">
          {{ scope.row.endTime ?? scope.row.latestDataTime ?? '-' }}
        </template>
      </el-table-column>
    </el-table>

    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { EnergyDeviceApi, EnergyDeviceDataRecordVO } from '@/api/mes/energydevice'
import { OrganizationApi, OrganizationVO } from '@/api/mes/organization'

defineOptions({ name: 'EnergyDeviceCheckRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EnergyDeviceDataRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tableRef = ref()
const expandRowKeys = ref<Array<string | number>>([])
const selectedIds = ref<Array<number | string>>([])

const orgOptions = ref<{ label: string; value: string | number; raw?: OrganizationVO }[]>([])

const getDisabledTime = () => {
  const all = Array.from({ length: 60 }, (_, i) => i)
  return {
    disabledMinutes: () => all,
    disabledSeconds: () => all
  }
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined as string | undefined,
  orgId: undefined as string | number | undefined,
  timeRange: [] as string[],
  startTime: undefined as string | undefined,
  endTime: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const getPointDetailsRows = (row: EnergyDeviceDataRecordVO) => {
  const list = (row as any)?.pointDetails
  if (!Array.isArray(list)) return []
  return list
}

const getRowClassName = ({ row }: { row: EnergyDeviceDataRecordVO }) => {
  return getPointDetailsRows(row).length ? '' : 'row-no-expand'
}

const handleRowClick = (row: EnergyDeviceDataRecordVO) => {
  const rows = getPointDetailsRows(row)
  if (!rows.length) return
  const key = row.id
  const idx = expandRowKeys.value.findIndex((k) => k === key)
  if (idx >= 0) {
    expandRowKeys.value.splice(idx, 1)
  } else {
    expandRowKeys.value.push(key)
  }
}

const handleSelectionChange = (rows: EnergyDeviceDataRecordVO[]) => {
  selectedIds.value = rows
    .map((item) => item.id)
    .filter((id): id is number | string => id !== undefined && id !== null)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.startTime = queryParams.timeRange?.[0]
    queryParams.endTime = queryParams.timeRange?.[1]
    const params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      name: queryParams.name,
      orgId: queryParams.orgId,
      startTime: queryParams.startTime,
      endTime: queryParams.endTime
    }
    const res: any = await EnergyDeviceApi.queryDataRecords(params)
    const rows = (Array.isArray(res)
      ? res
      : Array.isArray(res?.list)
        ? res.list
        : Array.isArray(res?.data)
          ? res.data
          : []) as EnergyDeviceDataRecordVO[]
    list.value = rows
    total.value = Number(res?.total ?? rows.length)
    expandRowKeys.value = []
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.timeRange = []
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    queryParams.startTime = queryParams.timeRange?.[0]
    queryParams.endTime = queryParams.timeRange?.[1]
    const params: any = {
      name: queryParams.name,
      orgId: queryParams.orgId,
      startTime: queryParams.startTime,
      endTime: queryParams.endTime
    }
    if (selectedIds.value.length) {
      params.ids = selectedIds.value.join(',')
    }
    const data = await EnergyDeviceApi.exportQueryDataRecords(params)
    download.excel(data, '能源报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const loadOrgOptions = async () => {
  if (orgOptions.value.length) return
  const data: any = await OrganizationApi.getOrganizationList({})
  const rows = (Array.isArray(data) ? data : data?.list ?? data?.data ?? []) as OrganizationVO[]
  orgOptions.value = rows
    .filter((r) => r?.id !== undefined && r?.name)
    .map((r) => ({ label: r.name, value: r.id, raw: r }))
}

/** 初始化 **/
onMounted(async () => {
  await loadOrgOptions()
  await getList()
})
</script>

<style scoped lang="scss">
:deep(.el-time-spinner__wrapper:nth-child(1)) {
  width: 100%;
}

:deep(.el-time-spinner__wrapper:nth-child(2)) {
  display: none;
}
</style>
