<script setup>
import dayjs from 'dayjs'
import CountTo from '@/components/count-to1.vue'
import { FiveIotProjectDailyReportApi } from '@/api/pms/fiveconstructiondailyreport'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'

defineOptions({ name: 'FiveDailyReportSummary' })

const route = useRoute()
const router = useRouter()
const defaultDeptId = 388
const { ZmTable, ZmTableColumn } = useTableComponents()

const summaryCards = [
  {
    key: 'cumulativeWorkingLayers',
    label: '压裂',
    unit: '层',
    icon: 'i-material-symbols-layers-outline-rounded',
    decimals: 0
  },
  {
    key: 'totalDailyFuel',
    label: '油耗',
    unit: 'L',
    icon: 'i-material-symbols-local-gas-station-outline-rounded',
    decimals: 0
  },
  {
    key: 'cumulativeMixSand',
    label: '加砂',
    unit: '方',
    icon: 'i-material-symbols-auto-mode-rounded',
    decimals: 0
  },
  {
    key: 'cumulativeLiquidVolume',
    label: '注液',
    unit: '方',
    icon: 'i-material-symbols-water-drop-outline-rounded',
    decimals: 0
  },
  {
    key: 'utilizationRate',
    label: '设备利用率',
    unit: '%',
    icon: 'i-material-symbols-build-outline-rounded',
    decimals: 2
  }
]

const tableColumns = [
  { prop: 'projectDeptName', label: '部门', minWidth: 180 },
  { prop: 'cumulativeLiquidVolume', label: '注液量(方)', minWidth: 140 },
  { prop: 'cumulativeMixSand', label: '加砂(方)', minWidth: 140 },
  { prop: 'cumulativeWorkingLayers', label: '压裂(层)', minWidth: 140 },
  { prop: 'totalDailyFuel', label: '油耗(L)', minWidth: 140 },
  { prop: 'utilizationRate', label: '设备利用率(%)', minWidth: 150 }
]

const createDefaultQuery = () => ({
  pageNo: 1,
  pageSize: 10,
  deptId: defaultDeptId,
  createTime: [
    ...rangeShortcuts[1].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))
  ]
})

const query = ref(createDefaultQuery())
const list = ref([])
const total = ref(0)
const loading = ref(false)
const summaryLoading = ref(false)
const currentDeptName = ref('5号国')
const selectedDeptType = ref('1')
const cardStatistics = ref({
  cumulativeWorkingLayers: 0,
  totalDailyFuel: 0,
  cumulativeMixSand: 0,
  cumulativeLiquidVolume: 0,
  utilizationRate: 0
})

const deptColumnLabel = computed(() => (selectedDeptType.value === '1' ? '项目部' : '队伍'))

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

  if (Array.isArray(createTime)) {
    const values = createTime.filter((item) => typeof item === 'string')
    if (values.length === 2) {
      query.value.createTime = values
    }
  } else if (typeof createTime === 'string') {
    const values = createTime.split(',').filter(Boolean)
    if (values.length === 2) {
      query.value.createTime = values
    }
  }
}

const loadList = useDebounceFn(async () => {
  loading.value = true
  try {
    const data = await FiveIotProjectDailyReportApi.getProjectDailyReportSummaryPage({
      pageNo: query.value.pageNo,
      pageSize: query.value.pageSize,
      deptId: query.value.deptId,
      createTime: query.value.createTime
    })
    list.value = (data?.list ?? []).map((item) => ({
      ...item,
      deptDisplayName:
        String(item.type || selectedDeptType.value || '1') === '2'
          ? item.projectDeptName || '-'
          : item.teamName || item.projectDeptName || '-'
    }))
    total.value = data?.total ?? 0
  } finally {
    loading.value = false
  }
}, 200)

const loadSummary = useDebounceFn(async () => {
  summaryLoading.value = true
  try {
    const data = await FiveIotProjectDailyReportApi.getIotProjectDailyReportSummary({
      deptId: query.value.deptId,
      createTime: query.value.createTime
    })

    cardStatistics.value = {
      cumulativeWorkingLayers: data?.cumulativeWorkingLayers || 0,
      totalDailyFuel: data?.totalDailyFuel || 0,
      cumulativeMixSand: data?.cumulativeMixSand || 0,
      cumulativeLiquidVolume: data?.cumulativeLiquidVolume || 0,
      utilizationRate: Number(data?.utilizationRate || 0)
    }
  } finally {
    summaryLoading.value = false
  }
}, 200)

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

function resetQuery() {
  query.value = createDefaultQuery()
  currentDeptName.value = '5号国'
  loadSummary()
  handleQuery()
}

function handleDeptNodeClick(node) {
  currentDeptName.value = node?.name || '5号国'
  selectedDeptType.value = String(node?.type || '1')
  loadSummary()
  handleQuery()
}

function handleSizeChange(value) {
  query.value.pageSize = value
  handleQuery(false)
}

function handleCurrentChange(value) {
  query.value.pageNo = value
  loadList()
}

function formatCellValue(row, prop) {
  if (prop === 'utilizationRate') {
    return row[prop] === null || row[prop] === undefined ? '-' : `${Number(row[prop]).toFixed(2)}%`
  }

  const value = row[prop]
  return value === null || value === undefined || value === '' ? '-' : value
}

function handleDeptCellClick(row) {
  const rowType = String(row?.type || selectedDeptType.value || '1')
  const targetQuery = {
    deptId: String(query.value.deptId || defaultDeptId),
    createTime: Array.isArray(query.value.createTime) ? query.value.createTime : undefined,
    projectDeptId: undefined,
    teamId: undefined
  }

  if (rowType === '2' && row?.projectDeptId) {
    targetQuery.projectDeptId = String(row.projectDeptId)
  } else if (row?.teamId) {
    targetQuery.teamId = String(row.teamId)
  } else if (row?.projectDeptId) {
    targetQuery.projectDeptId = String(row.projectDeptId)
  } else {
    return
  }

  router.push({
    name: 'ConstructionDailyReport',
    query: targetQuery
  })
}

syncQueryFromRoute()

watch(
  () => [query.value.createTime?.[0], query.value.createTime?.[1]],
  () => {
    loadSummary()
    handleQuery()
  },
  { immediate: true }
)

watch(
  () => query.value.deptId,
  () => {
    loadSummary()
    handleQuery()
  },
  { immediate: true }
)

watch(
  () => route.query.createTime,
  () => {
    syncQueryFromRoute()
  }
)
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[48px_44px_1fr] gap-3 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <DeptTreeSelect
      v-model="query.deptId"
      :top-id="388"
      :deptId="defaultDeptId"
      :show-title="false"
      class="row-span-3"
      @node-click="handleDeptNodeClick" />

    <el-form
      size="small"
      label-width="auto"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 pt-3 pb-4 flex items-center flex-wrap min-w-0">
      <div class="flex items-center gap-2 flex-wrap">
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="query.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="rangeShortcuts"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-260px" />
        </el-form-item>

        <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-form-item>
      </div>
    </el-form>

    <div class="summary-cards min-w-0" v-loading="summaryLoading">
      <article
        v-for="card in summaryCards"
        :key="card.key"
        class="summary-card bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-5 py-8 min-w-0">
        <div class="summary-card__icon" :class="card.icon"></div>
        <div class="min-w-0">
          <div class="summary-card__label">{{ card.label }}({{ card.unit }})</div>
          <count-to
            class="summary-card__value"
            :start-val="0"
            :end-val="cardStatistics[card.key]"
            :decimals="card.decimals || 0">
            <span class="summary-card__placeholder">--</span>
          </count-to>
        </div>
      </article>
    </div>

    <div class="summary-content min-h-0 min-w-0 overflow-hidden">
      <div class="summary-content__header">
        <h3 class="summary-content__title">{{ currentDeptName }}日报汇总</h3>
      </div>

      <div class="summary-table-wrap">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              show-border>
              <ZmTableColumn type="index" label="序号" :width="70" fixed="left" />
              <ZmTableColumn
                prop="deptDisplayName"
                :label="deptColumnLabel"
                :min-width="180"
                show-overflow-tooltip
                cover-formatter
                :real-value="(row) => formatCellValue(row, 'deptDisplayName')">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    class="summary-table-link"
                    @click.stop="handleDeptCellClick(row)">
                    {{ formatCellValue(row, 'deptDisplayName') }}
                  </el-button>
                </template>
              </ZmTableColumn>
              <ZmTableColumn
                v-for="column in tableColumns.slice(1)"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :min-width="column.minWidth"
                show-overflow-tooltip
                cover-formatter
                :real-value="(row) => formatCellValue(row, column.prop)" />
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>

      <div class="h-8 mt-2 flex items-center justify-end">
        <el-pagination
          v-show="total > 0"
          :current-page="query.pageNo"
          :page-size="query.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

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

.summary-cards {
  min-width: 0;
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 16px;
}

.summary-card {
  position: relative;
  display: flex;
  align-items: center;
  gap: 14px;
  overflow: hidden;
}

/* .summary-card::after {
  content: '';
  position: absolute;
  inset: auto -32px -32px auto;
  width: 66px;
  height: 66px;
  border-radius: 999px;
  background: linear-gradient(135deg, rgb(59 130 246 / 0.14), rgb(16 185 129 / 0.08));
} */

.summary-card__icon {
  position: relative;
  z-index: 1;
  flex: none;
  width: 44px;
  height: 44px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #2563eb;
  background: linear-gradient(135deg, rgb(37 99 235 / 0.14), rgb(14 165 233 / 0.08));
}

.summary-card__label {
  position: relative;
  z-index: 1;
  color: var(--el-text-color-regular);
  font-size: 13px;
  line-height: 20px;
  margin-bottom: 4px;
}

.summary-card__value {
  position: relative;
  z-index: 1;
  font-size: 28px;
  font-weight: 600;
  line-height: 1;
  color: var(--el-text-color-primary);
}

.summary-card__placeholder {
  font-size: 16px;
  color: var(--el-text-color-placeholder);
}

.summary-content {
  background: #fff;
  border-radius: 12px;
  box-shadow: var(--el-box-shadow-light);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 20px;
}

.summary-content__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.summary-content__title {
  font-size: 18px;
  line-height: 28px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.summary-table-wrap {
  position: relative;
  flex: 1;
  min-height: 0;
}

.summary-table-link {
  padding: 0;
  font-weight: 500;
}

@media (max-width: 1600px) {
  .summary-card__value {
    font-size: 24px;
  }
}

@media (max-width: 1280px) {
  .summary-card {
    gap: 10px;
    padding: 12px 14px;
  }

  .summary-card__icon {
    width: 38px;
    height: 38px;
    border-radius: 12px;
    font-size: 20px;
  }

  .summary-card__label {
    font-size: 12px;
    line-height: 18px;
  }

  .summary-card__value {
    font-size: 20px;
  }
}
</style>
