<template>
  <ContentWrap>
    <el-form class="-mb-15px energy-device-check-filter-form" :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto">
      <el-form-item :label="t('EnergyManagement.EnergyDeviceCheck.searchNameLabel')" prop="name">
        <el-input
          v-model="queryParams.name" :placeholder="t('EnergyManagement.EnergyDeviceCheck.searchNamePlaceholder')" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item :label="t('EnergyManagement.EnergyDeviceCheck.searchOrgLabel')" prop="orgId">
        <el-select v-model="queryParams.orgId" filterable clearable :placeholder="t('EnergyManagement.EnergyDeviceCheck.searchOrgPlaceholder')" 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="t('EnergyManagement.EnergyDeviceCheck.searchTimeRangeLabel')" prop="timeRange">
        <el-date-picker
v-model="queryParams.timeRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH"
          :start-placeholder="t('EnergyManagement.EnergyDeviceCheck.searchTimeRangeStartPlaceholder')"
          :end-placeholder="t('EnergyManagement.EnergyDeviceCheck.searchTimeRangeEndPlaceholder')"
          :default-time="[new Date('2000-01-01 00:00:00'), new Date('2000-01-01 23:00:00')]"
          :shortcuts="timeRangeShortcuts"
          :disabled-time="getDisabledTime" class="!w-360px " popper-class="energydevicecheckPicker" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('EnergyManagement.EnergyDeviceCheck.searchButtonText') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('EnergyManagement.EnergyDeviceCheck.resetButtonText') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> {{ t('EnergyManagement.EnergyDeviceCheck.exportButtonText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <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=" min-height: 50vh;margin-top: 20px"
      @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 :header-cell-style="{ background: '#f5f7fa', color: '#909399' }">
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandPointNameColumn')" prop="pointName" min-width="140" />
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandEarliestValueColumn')" prop="earliestValue" min-width="120" />
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandEarliestTimeColumn')" prop="earliestTime" min-width="170" />
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandLatestValueColumn')" prop="latestValue" min-width="120" />
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandLatestTimeColumn')" prop="latestTime" min-width="170" />
            <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableExpandDifferenceColumn')" 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="t('EnergyManagement.EnergyDeviceCheck.tableNameColumn')" align="center" prop="name" min-width="120" />
      <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableEnergyTypeColumn')" align="center" prop="deviceTypeName" min-width="100" />
      <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableOrgColumn')" align="center" prop="orgName" min-width="100" />
      <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableEnergyConsumptionColumn')" 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="t('EnergyManagement.EnergyDeviceCheck.tableStartTimeColumn')" align="center" min-width="170">
        <template #default="scope">
          {{ scope.row.startTime ?? scope.row.earliestDataTime ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('EnergyManagement.EnergyDeviceCheck.tableEndTimeColumn')" 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 buildDefaultTimeRange = () => {
  const pad = (n: number) => (n < 10 ? `0${n}` : String(n))
  const end = new Date()
  end.setMilliseconds(0)
  const start = new Date(end.getTime() - 24 * 60 * 60 * 1000)
  const format = (d: Date) => {
    const y = d.getFullYear()
    const m = pad(d.getMonth() + 1)
    const day = pad(d.getDate())
    const h = pad(d.getHours())
    const min = pad(d.getMinutes())
    const s = pad(d.getSeconds())
    return `${y}-${m}-${day} ${h}:${min}:${s}`
  }
  return [format(start), format(end)] as string[]
}

const timeRangeShortcuts = [
   {
    text: '今天',
    value: () => {
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  {
    text: '昨天',
    value: () => {
      const start = new Date()
      start.setDate(start.getDate() - 1)
      start.setHours(0, 0, 0, 0)
      const end = new Date(start)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  {
    text: '7天',
    value: () => {
      const end = new Date()
      end.setMilliseconds(0)
      const start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000)
      return [start, end]
    }
  }
]

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined as string | undefined,
  orgId: undefined as string | number | undefined,
  timeRange: buildDefaultTimeRange(),
  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 = buildDefaultTimeRange()
  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, t('EnergyManagement.EnergyDeviceCheck.exportFileName'))
  } 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>
