<script lang="ts" setup>
import { IotRdDailyReportApi } from '@/api/pms/iotrddailyreport'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import dayjs from 'dayjs'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { useUserStore } from '@/store/modules/user'
import download from '@/utils/download'

defineOptions({ name: 'DailyReport' })

const tab = ref('井')
const tabOptions = ['井', '队伍']

interface List {
  createTime: number // 日期
  deptName: string // 施工队伍
  contractName: string // 项目
  taskName: string // 任务
  id: number
  deptId: number
  projectId: number
  taskId: number
  timeRange: any // 时间节点
  rdStatus: string // 施工状态
  cumulativeWorkingWell: number // 施工井
  cumulativeWorkingLayers: number // 施工层
  dailyPumpTrips: number // 泵车台次
  dailyToolsSand: number // 仪表/混砂
  runCount: number // 趟数
  bridgePlug: number // 桥塞
  waterVolume: number // 水方量
  hourCount: number // 时间H
  dailyFuel: number // 油耗(L)
  reportDetails: any // 当日生产动态
  nextPlan: string // 下步工作计划
  externalRental: string // 外租设备
  malfunction: string // 故障情况
  faultDowntime: number // 故障误工H
  lastGroupIdFlag: boolean
}

interface Column {
  prop?: keyof List
  label: string
  'min-width'?: string
  isTag?: boolean
  isDay?: boolean
  fixed?: 'left' | 'right'
  formatter?: (row: List) => any
  children?: Column[]
  dictType?: string
}

const columns = ref<Column[]>([
  {
    label: '日期',
    prop: 'createTime',
    'min-width': '120px',
    fixed: 'left',
    formatter: (row: List) => dayjs(row.createTime).format('YYYY-MM-DD')
  },
  {
    label: '施工队伍',
    prop: 'deptName',
    fixed: 'left',
    'min-width': '120px'
  },
  {
    label: '任务',
    prop: 'taskName',
    fixed: 'left',
    'min-width': '120px'
  },
  // {
  //   label: '时间节点',
  //   prop: 'timeRange',
  //   'min-width': '120px'
  // },
  {
    label: '施工状态',
    prop: 'rdStatus',
    'min-width': '120px',
    isTag: true,
    dictType: DICT_TYPE.PMS_PROJECT_RD_STATUS
  },
  {
    label: '当日',
    children: [
      {
        label: '施工井',
        prop: 'cumulativeWorkingWell',
        'min-width': '120px'
      },
      {
        label: '施工层',
        prop: 'cumulativeWorkingLayers',
        'min-width': '120px'
      },
      {
        label: '泵车台次',
        prop: 'dailyPumpTrips',
        'min-width': '120px'
      },
      {
        label: '仪表/混砂',
        prop: 'dailyToolsSand',
        'min-width': '120px'
      }
    ]
  },
  {
    label: '趟数',
    prop: 'runCount',
    'min-width': '120px'
  },
  {
    label: '桥塞',
    prop: 'bridgePlug',
    'min-width': '120px'
  },
  {
    label: '水方量',
    prop: 'waterVolume',
    'min-width': '120px'
  },
  {
    label: '时间H',
    prop: 'hourCount',
    'min-width': '120px'
  },
  {
    label: '油耗(L)',
    prop: 'dailyFuel',
    'min-width': '120px'
  },
  {
    label: '生产动态',
    prop: 'reportDetails',
    'min-width': '120px',
    isDay: true
  },
  {
    label: '下步工作计划',
    prop: 'nextPlan',
    'min-width': '120px'
  },
  {
    label: '外租设备',
    prop: 'externalRental',
    'min-width': '120px'
  },
  {
    label: '故障情况',
    prop: 'malfunction',
    'min-width': '120px'
  },
  {
    label: '故障误工H',
    prop: 'faultDowntime',
    'min-width': '120px'
  }
])

const getTextWidth = (text: string, fontSize = 12) => {
  const span = document.createElement('span')
  span.style.visibility = 'hidden'
  span.style.position = 'absolute'
  span.style.whiteSpace = 'nowrap'
  span.style.fontSize = `${fontSize}px`
  span.style.fontFamily = 'PingFang SC'
  span.innerText = text

  document.body.appendChild(span)
  const width = span.offsetWidth
  document.body.removeChild(span)

  return width
}

const calculateColumnWidths = (colums: Column[]) => {
  for (const col of colums) {
    let { formatter, prop, label, 'min-width': minWidth, isTag, children } = col

    if (children && children.length > 0) {
      calculateColumnWidths(children)
      continue
    }

    minWidth =
      Math.min(
        ...[
          Math.max(
            ...[
              getTextWidth(label),
              ...list.value.map((v) => {
                let tagLabel = ''
                if (col.dictType) {
                  const option = getDictOptions(col.dictType).find(
                    (item) => item.value === v[prop!]
                  )
                  if (option) tagLabel = option.label
                }
                return getTextWidth(
                  formatter ? formatter(v) : Boolean(tagLabel) ? tagLabel : v[prop!]
                )
              })
            ]
          ) + (isTag ? 40 : 20),
          ...(isTag ? [] : [200])
        ]
      ) + 'px'

    col['min-width'] = col.isDay ? '250px' : minWidth
  }
}

// function checkTimeSumEquals24(row: List) {
//   // 获取三个字段的值，转换为数字，如果为空则视为0
//   const gasTime = row.dailyInjectGasTime || 0
//   const waterTime = row.dailyInjectWaterTime || 0
//   const nonProdTime = row.nonProductionTime || 0

//   // 计算总和
//   const sum = gasTime + waterTime + nonProdTime

//   // 返回是否等于24（允许一定的浮点数误差）
//   return Math.abs(sum - 24) < 0.01 // 使用0.01作为误差范围
// }

// function cellStyle(data: {
//   row: List
//   column: TableColumnCtx<List>
//   rowIndex: number
//   columnIndex: number
// }) {
//   const { row, column } = data

//   if (column.property === 'transitTime') {
//     const originalValue = row.transitTime ?? 0

//     if (originalValue > 1.2)
//       return {
//         color: 'red',
//         fontWeight: 'bold'
//       }
//   }

//   const timeFields = ['dailyInjectGasTime', 'dailyInjectWaterTime', 'nonProductionTime']
//   if (timeFields.includes(column.property)) {
//     if (!checkTimeSumEquals24(row)) {
//       return {
//         color: 'orange',
//         fontWeight: 'bold'
//       }
//     }
//   }

//   // 默认返回空对象，不应用特殊样式
//   return {}
// }

function rowClassName(data: { row: List; rowIndex: number }) {
  const { row } = data
  if (!row.lastGroupIdFlag) {
    return 'hide-expand-icon'
  }
  return ''
}

const id = useUserStore().getUser.deptId ?? 157

const deptId = id

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

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

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

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

const loading = ref(false)

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

const loadList = useDebounceFn(async function () {
  loading.value = true
  try {
    if (tab.value === '井') {
      const { deptId, taskName, ...other } = query.value
      const data = await IotRdDailyReportApi.getIotRdDailyReportTeamPage({
        ...other,
        taskName: query.value.wellName
      })
      list.value = data.list
      total.value = data.total
    } else {
      const data = await IotRdDailyReportApi.getIotRdDailyReportWellPage(query.value)
      list.value = data.list
      total.value = data.total
    }

    nextTick(() => {
      calculateColumnWidths(columns.value)
    })
  } finally {
    loading.value = false
  }
}, 500)

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

function resetQuery() {
  query.value = {
    pageNo: 1,
    pageSize: 10,
    deptId: 157,
    contractName: '',
    taskName: '',
    createTime: [
      ...rangeShortcuts[2].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))
    ]
  }
  handleQuery()
}

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

const expandRowKeys = computed(() => {
  return list.value.filter((item) => item.lastGroupIdFlag).map((item) => item.id.toString())
})

const exportLoading = ref(false)

const handleExport = () => {
  exportLoading.value = true
  if (tab.value === '井') {
    IotRdDailyReportApi.exportIotRdDailyReportWell(query.value).then((data) => {
      download.excel(data, '瑞都井日报统计.xls')
      exportLoading.value = false
    })
  } else {
    IotRdDailyReportApi.exportIotRdDailyReportTeam(query.value).then((data) => {
      download.excel(data, '瑞都队伍日报统计.xls')
      exportLoading.value = false
    })
  }
}
</script>

<template>
  <div
    class="daily-report-page grid grid-cols-[auto_1fr] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]"
  >
    <el-form
      size="default"
      class="col-span-2 bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 gap-8 flex items-center"
    >
      <div class="flex items-center gap-8">
        <el-segmented class="h-12" v-model="tab" :options="tabOptions" @change="handleQuery()" />
      </div>
      <div class="flex items-center gap-8">
        <el-form-item label="项目">
          <el-input
            v-model="query.contractName"
            placeholder="请输入项目"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item v-show="tab !== '井'" label="任务">
          <el-input
            v-model="query.taskName"
            placeholder="请输入任务"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-240px"
          />
        </el-form-item>
        <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-220px"
          />
        </el-form-item>
      </div>
      <el-form-item class="ml-auto">
        <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 plain type="success" @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 第二行左侧：自动落入第 2 行第 1 列 -->
    <DeptTreeSelect
      v-show="tab === '队伍'"
      :top-id="163"
      :deptId="deptId"
      v-model="query.deptId"
      title="队伍"
      class="daily-report-side"
    />
    <WellSelect
      v-show="tab === '井'"
      :deptId="163"
      v-model="query.wellName"
      v-model:contract-name="query.contractName"
      class="daily-report-side"
    />
    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg h-full"> </div> -->

    <!-- 第二行右侧：自动落入第 2 行第 2 列 -->
    <div
      class="daily-report-table-card bg-white dark:bg-[#1d1e1f] shadow rounded-lg p-4 flex flex-col min-h-0"
    >
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <el-table
              :data="list"
              v-loading="loading"
              stripe
              class="absolute"
              :max-height="height"
              :height="height"
              show-overflow-tooltip
              :width="width"
              :row-class-name="rowClassName"
              :tree-props="{ hasChildren: 'lastGroupIdFlag' }"
              row-key="id"
              scrollbar-always-on
              :expand-row-keys="expandRowKeys"
              border
            >
              <el-table-column type="expand" fixed="left">
                <template #default="{ row }">
                  <div
                    class="flex items-center gap-8 h-10 px-14 sticky left-0 w-fit box-border bg-[var(--el-bg-color)]"
                  >
                    <el-tag>桥塞: {{ row.groupIdBridgePlug }} </el-tag>
                    <el-tag>趟数: {{ row.groupIdRunCount }} </el-tag>
                    <el-tag>井数: {{ row.groupIdCumulativeWorkingWell }} </el-tag>
                    <el-tag>小时H: {{ row.groupIdHourCount }} </el-tag>
                    <el-tag>油耗L: {{ row.groupIdFuel }} </el-tag>
                    <el-tag>水方量(方): {{ row.groupIdWaterVolume }} </el-tag>
                    <el-tag>台次（泵车）: {{ row.groupIdPumpTrips }} </el-tag>
                    <el-tag>段数: {{ row.groupIdCumulativeWorkingLayers }} </el-tag>
                    <el-tag>台次（仪表/混砂）: {{ row.groupIdMixSand }} </el-tag>
                  </div>
                </template>
              </el-table-column>
              <DailyTableColumn :columns="columns" company="rd" />
              <!-- <el-table-column label="操作" width="120px" align="center" fixed="right">
                <template #default="{ row }">
                  <el-button link type="success" v-hasPermi="['pms:iot-rh-daily-report:query']">
                    查看
                  </el-button>
                  <el-button
                    v-show="row.status === 0"
                    link
                    type="primary"
                    v-hasPermi="['pms:iot-rh-daily-report:create']"
                  >
                    编辑
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
      <div class="h-10 mt-4 flex items-center justify-end">
        <el-pagination
          size="default"
          v-show="total > 0"
          v-model:current-page="query.pageNo"
          v-model: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>
.daily-report-page {
  grid-template-rows: 62px minmax(0, 1fr);
}

.daily-report-side {
  height: 100% !important;
  min-height: 0 !important;
}

.daily-report-table-card {
  min-height: 0;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

.el-segmented {
  --el-border-radius-base: 8px;
  --el-segmented-padding: 8px;
}

:deep(.hide-expand-icon) {
  .el-table__expand-icon {
    display: none;
  }
}
</style>
