<script setup lang="ts">
import {
  IotRhDailyReportApi,
  type IotRhDailyReportTotalWorkloadVO
} from '@/api/pms/iotrhdailyreport'
import { useUserStore } from '@/store/modules/user'
import download from '@/utils/download'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import UnfilledReportDialog from './UnfilledReportDialog.vue'
import CountTo from '@/components/count-to1.vue'
import dayjs from 'dayjs'
import RhTable from './rh-table.vue'

defineOptions({ name: 'IotRhDailyReport' })

const route = useRoute()

const message = useMessage()

const id = useUserStore().getUser.deptId

const deptId = id

interface Query {
  deptId?: number
  contractName?: string
  taskName?: string
  createTime?: string[]
  pageNo: number
  pageSize: number
  nonProductFlag?: string
}

const initQuery: Query = {
  pageNo: 1,
  pageSize: 10,
  deptId: route.query.deptId ? Number(route.query.deptId) : id,
  createTime: route.query.createTime
    ? (route.query.createTime as string[])
    : [...rangeShortcuts[1].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))],
  nonProductFlag: route.query.nonProductFlag ? (route.query.nonProductFlag as string) : undefined
}

const query = ref<Query>({ ...initQuery })

const getRouteCreateTime = () => {
  const createTime = route.query.createTime

  if (Array.isArray(createTime)) {
    return createTime.filter((item): item is string => typeof item === 'string')
  }

  return typeof createTime === 'string'
    ? [createTime]
    : [...rangeShortcuts[1].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))]
}

const syncQueryFromRoute = () => {
  query.value.deptId = route.query.deptId ? Number(route.query.deptId) : id
  query.value.createTime = getRouteCreateTime()
}

const totalWorkKeys: [string, string, string, string, number][] = [
  ['totalCount', '个', '总数', 'i-tabler:report-analytics text-sky', 0],
  [
    'alreadyReported',
    '个',
    '已填报',
    'i-material-symbols:check-circle-outline-rounded text-emerald',
    0
  ],
  ['notReported', '个', '未填报', 'i-material-symbols:cancel-outline-rounded text-rose', 0],
  ['totalGasInjection', '万方', '累计注气量', 'i-material-symbols:cloud-outline text-sky', 2],
  [
    'totalWaterInjection',
    '万方',
    '累计注水量',
    'i-material-symbols:water-drop-outline-rounded text-sky',
    2
  ]
  // [
  //   'utilizationRate',
  //   '%',
  //   '设备利用率',
  //   'i-material-symbols:check-circle-outline-rounded text-emerald',
  //   0
  // ],
  // [
  //   'totalPowerConsumption',
  //   'MWh',
  //   '累计用电量',
  //   'i-material-symbols:electric-bolt-outline-rounded text-sky',
  //   2
  // ],
  // [
  //   'totalFuelConsumption',
  //   '升',
  //   '累计油耗',
  //   'i-material-symbols:directions-car-outline-rounded text-sky',
  //   2
  // ],
]

const totalWork = ref({
  totalCount: 0,
  alreadyReported: 0,
  notReported: 0,
  totalFuelConsumption: 0,
  totalPowerConsumption: 0,
  totalWaterInjection: 0,
  totalGasInjection: 0,
  utilizationRate: 0
})

const totalLoading = ref(false)

const totalWorkloadDetail = ref({
  totalN2GasInjection: 0,
  totalNaturalGasInjection: 0
})

const formatGasInjectionTooltipValue = (value?: number | null) => ((value || 0) / 10000).toFixed(4)

const getTotal = useDebounceFn(async function () {
  totalLoading.value = true

  const { pageNo, pageSize, ...other } = query.value

  try {
    let res1: any[]
    if (query.value.createTime && query.value.createTime.length === 2) {
      res1 = await IotRhDailyReportApi.rhDailyReportStatistics({
        createTime: query.value.createTime,
        deptId: query.value.deptId
      })

      totalWork.value.totalCount = res1[0].count
      totalWork.value.alreadyReported = res1[1].count
      totalWork.value.notReported = res1[2].count
    }

    const res2: IotRhDailyReportTotalWorkloadVO = await IotRhDailyReportApi.totalWorkload(other)

    totalWorkloadDetail.value = {
      totalN2GasInjection: res2.totalN2GasInjection || 0,
      totalNaturalGasInjection: res2.totalNaturalGasInjection || 0
    }

    totalWork.value = {
      ...totalWork.value,
      ...res2,
      totalPowerConsumption: (res2.totalPowerConsumption || 0) / 1000,
      totalWaterInjection: (res2.totalWaterInjection || 0) / 10000,
      totalGasInjection: (res2.totalGasInjection || 0) / 10000,
      totalFuelConsumption: res2.totalFuelConsumption || 0,
      utilizationRate: Number(((res2.utilizationRate || 0) * 100).toFixed(2))
    }
  } finally {
    totalLoading.value = false
  }
}, 500)

const list = ref<any[]>([])
const total = ref(0)

const loading = ref(false)

const loadList = useDebounceFn(async function () {
  loading.value = true
  try {
    const data = await IotRhDailyReportApi.getIotRhDailyReportPage(query.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
})

function handleSizeChange(val: number) {
  query.value.pageSize = val
  handleQuery()
}

function handleCurrentChange(val: number) {
  query.value.pageNo = val
  loadList()
  getTotal()
}

function handleQuery(setPage = true) {
  if (setPage) {
    query.value.pageNo = 1
  }
  loadList()
  getTotal()
}

function resetQuery() {
  query.value = { ...initQuery }

  handleQuery()
}

watch(
  [
    () => query.value.deptId,
    () => query.value.contractName,
    () => query.value.taskName,
    () => query.value.createTime,
    () => query.value.nonProductFlag
  ],
  () => {
    handleQuery()
  },
  { immediate: true }
)

watch(
  () => [route.query.deptId, route.query.createTime],
  () => {
    syncQueryFromRoute()
  }
)

// const selectedRowData = ref<any>(null)

// const formRef = ref()

// const openForm = (type: string, id?: number, row?: any) => {
//   if (row) {
//     selectedRowData.value = {
//       deptName: row.deptName,
//       contractName: row.contractName,
//       taskName: row.taskName,
//       relocationDays: row.relocationDays
//     }
//   } else {
//     selectedRowData.value = null
//   }

//   formRef.value.open(type, id)
// }

const exportLoading = ref(false)

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

    exportLoading.value = true
    const res = await IotRhDailyReportApi.exportIotRhDailyReport(query.value)

    download.excel(res, '瑞恒日报.xls')
  } finally {
    exportLoading.value = false
  }
}

const unfilledDialogRef = ref()

const alarmCollapse = ref<string[]>([])

const openUnfilledDialog = () => {
  if (!query.value.createTime || query.value.createTime.length === 0) {
    message.warning('请先选择创建时间范围')
    return
  }

  // 打开弹窗
  unfilledDialogRef.value.open()
}
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[48px_auto_1fr_auto] gap-x-4 gap-y-3 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-4">
      <DeptTreeSelect :top-id="157" :deptId="deptId" v-model="query.deptId" :show-title="false" />
    </div> -->
    <DeptTreeSelect
      :top-id="157"
      :deptId="deptId"
      v-model="query.deptId"
      :show-title="false"
      class="row-span-4" />
    <el-form
      size="default"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-6 gap-8 flex items-center justify-between">
      <div class="flex items-center gap-8">
        <el-form-item label="项目">
          <el-input
            v-model="query.contractName"
            placeholder="请输入项目"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-180px" />
        </el-form-item>
        <el-form-item label="任务">
          <el-input
            v-model="query.taskName"
            placeholder="请输入任务"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-180px" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="query.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')]"
            class="!w-220px"
            :shortcuts="rangeShortcuts" />
        </el-form-item>
        <el-form-item label="非生产时效" prop="nonProductFlag">
          <el-switch v-model="query.nonProductFlag" active-value="Y" inactive-value="N" />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @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="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['pms:iot-rh-daily-report:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['pms:iot-rh-daily-report:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
    <div class="grid grid-cols-5 gap-3">
      <template v-for="info in totalWorkKeys" :key="info[0]">
        <el-tooltip :disabled="info[0] !== 'totalGasInjection'" placement="top">
          <template #content>
            <div>
              累计氮气注气量：{{
                formatGasInjectionTooltipValue(totalWorkloadDetail.totalN2GasInjection)
              }}
              万方
            </div>
            <div>
              累计天然气注气量：{{
                formatGasInjectionTooltipValue(totalWorkloadDetail.totalNaturalGasInjection)
              }}
              万方
            </div>
          </template>
          <div
            class="group relative bg-white dark:bg-[#1d1e1f] rounded-lg shadow-sm hover:shadow-md border border-gray-100 dark:border-gray-700 p-2.5 overflow-hidden transition-all duration-300"
            :class="{
              'cursor-pointer hover:border-blue-200 dark:hover:border-blue-800':
                info[2] === '未填报',
              'cursor-help': info[0] === 'totalGasInjection'
            }"
            @click="info[2] === '未填报' ? openUnfilledDialog() : ''">
            <div class="relative z-10 flex flex-col h-full justify-center">
              <span
                class="text-[11px] text-gray-400 dark:text-gray-500 font-medium tracking-wide mb-0.5">
                {{ info[2] }}
              </span>
              <div class="flex items-baseline gap-1">
                <count-to
                  class="text-lg font-bold text-gray-800 dark:text-gray-100 leading-none tracking-tight font-sans"
                  :start-val="0"
                  :end-val="totalWork[info[0]]"
                  :decimals="info[4]" />
                <span class="text-[10px] text-gray-400 font-normal">{{ info[1] }}</span>
              </div>
            </div>

            <div
              class="absolute -right-2 -bottom-3 opacity-40 dark:opacity-60 transform rotate-[-10deg] transition-transform duration-500 group-hover:scale-110 group-hover:rotate-0">
              <div :class="info[3]" class="text-5xl"></div>
            </div>
          </div>
        </el-tooltip>
      </template>
    </div>

    <rh-table
      :list="list"
      :total="total"
      :loading="loading"
      :page-no="query.pageNo"
      :page-size="query.pageSize"
      :show-action="false"
      is-index
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange" />
    <div class="p-1 bg-white dark:bg-[#1d1e1f] rounded-lg shadow">
      <el-collapse v-model="alarmCollapse" class="alarm-collapse">
        <el-collapse-item title="告警提示" name="alarm">
          <div class="flex flex-col gap-2">
            <el-alert
              class="h-8!"
              title="运行时效超过100%红色预警"
              type="error"
              show-icon
              :closable="false" />
            <el-alert
              class="h-8!"
              title="气电比计算结果大于15橙色预警"
              type="warning"
              show-icon
              :closable="false" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>

  <UnfilledReportDialog ref="unfilledDialogRef" :query-params="query" />
</template>

<style scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.zm-table) {
  .el-table__cell {
    height: 42px;
  }
}

:deep(.alarm-collapse) {
  border-top: 0;
  border-bottom: 0;

  .el-collapse-item__header {
    height: 32px;
    padding-left: 12px;
    font-size: 15px;
    font-weight: 700;
    line-height: 32px;
    border-bottom: 0;
  }

  .el-collapse-item__wrap {
    border-bottom: 0;
  }

  .el-collapse-item__content {
    padding-bottom: 4px;
  }
}
</style>
