<script setup lang="ts">
import DeptTree2 from '@/views/pms/iotrhdailyreport/DeptTree2.vue'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
import dayjs from 'dayjs'
import { IotRhDailyReportApi } from '@/api/pms/iotrhdailyreport'
import { useDebounceFn } from '@vueuse/core'
import CountTo from '@/components/count-to1.vue'

dayjs.extend(quarterOfYear)

const rangeShortcuts = [
  {
    text: '今天',
    value: () => {
      const today = dayjs()
      return [today.startOf('day').toDate(), today.endOf('day').toDate()]
    }
  },
  {
    text: '昨天',
    value: () => {
      const yesterday = dayjs().subtract(1, 'day')
      return [yesterday.startOf('day').toDate(), yesterday.endOf('day').toDate()]
    }
  },
  {
    text: '本周',
    value: () => {
      return [dayjs().startOf('week').toDate(), dayjs().endOf('week').toDate()]
    }
  },
  {
    text: '上周',
    value: () => {
      const lastWeek = dayjs().subtract(1, 'week')
      return [lastWeek.startOf('week').toDate(), lastWeek.endOf('week').toDate()]
    }
  },
  {
    text: '本月',
    value: () => {
      return [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()]
    }
  },
  {
    text: '上月',
    value: () => {
      const lastMonth = dayjs().subtract(1, 'month')
      return [lastMonth.startOf('month').toDate(), lastMonth.endOf('month').toDate()]
    }
  },
  {
    text: '本季度',
    value: () => {
      return [dayjs().startOf('quarter').toDate(), dayjs().endOf('quarter').toDate()]
    }
  },
  {
    text: '上季度',
    value: () => {
      const lastQuarter = dayjs().subtract(1, 'quarter')
      return [lastQuarter.startOf('quarter').toDate(), lastQuarter.endOf('quarter').toDate()]
    }
  },
  {
    text: '今年',
    value: () => {
      return [dayjs().startOf('year').toDate(), dayjs().endOf('year').toDate()]
    }
  },
  {
    text: '去年',
    value: () => {
      const lastYear = dayjs().subtract(1, 'year')
      return [lastYear.startOf('year').toDate(), lastYear.endOf('year').toDate()]
    }
  },
  {
    text: '最近7天',
    value: () => {
      return [dayjs().subtract(6, 'day').toDate(), dayjs().toDate()]
    }
  },
  {
    text: '最近30天',
    value: () => {
      return [dayjs().subtract(29, 'day').toDate(), dayjs().toDate()]
    }
  },
  {
    text: '最近90天',
    value: () => {
      return [dayjs().subtract(89, 'day').toDate(), dayjs().toDate()]
    }
  },
  {
    text: '最近一年',
    value: () => {
      return [dayjs().subtract(1, 'year').toDate(), dayjs().toDate()]
    }
  }
]

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

const id = 157

const query = ref<Query>({
  pageNo: 1,
  pageSize: 10,
  deptId: 157,
  createTime: []
})

const totalWorkKeys = [
  ['totalCount', '个', '总数', 'i-tabler:report-analytics text-sky'],
  [
    'alreadyReported',
    '个',
    '已填报',
    'i-material-symbols:check-circle-outline-rounded text-emerald'
  ],
  ['notReported', '个', '未填报', 'i-material-symbols:cancel-outline-rounded text-rose'],
  [
    'totalFuelConsumption',
    'L',
    '累计油耗',
    'i-material-symbols:directions-car-outline-rounded text-sky'
  ],
  [
    'totalPowerConsumption',
    'KWH',
    '累计用电量',
    'i-material-symbols:electric-bolt-outline-rounded text-sky'
  ],
  [
    'totalWaterInjection',
    '方',
    '累计注水量',
    'i-material-symbols:water-drop-outline-rounded text-sky'
  ],
  ['totalGasInjection', '万方', '累计注气量', 'i-material-symbols:cloud-outline text-sky']
]

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

const totalLoading = ref(false)

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

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

  try {
    let res1: any[]
    if (query.value.createTime.length !== 0) {
      res1 = await IotRhDailyReportApi.rhDailyReportStatistics({
        createTime: query.value.createTime
      })

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

    const res2 = await IotRhDailyReportApi.totalWorkload(other)

    totalWork.value = {
      ...totalWork.value,
      ...res2,
      totalGasInjection: (res2.totalGasInjection || 0) / 10000
    }
  } finally {
    totalLoading.value = false
  }
}, 1000)

interface List {
  id: number | null
  name: string | null
  type: '1' | '2' | '3'
  cumulativeGasInjection: number | null
  cumulativeWaterInjection: number | null
  cumulativePowerConsumption: number | null
  cumulativeFuelConsumption: number | null
  transitTime: number | null
}

const total = ref<number>(1000)

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

const type = ref('2')

const columns = (type: string) => {
  return [
    {
      label: type === '2' ? '项目部' : '队伍',
      prop: 'name'
    },
    {
      label: '累计注气量(万方)',
      prop: 'cumulativeGasInjection'
    },
    {
      label: '累计注水量(方)',
      prop: 'cumulativeWaterInjection'
    },
    {
      label: '累计用电量(KWH)',
      prop: 'cumulativePowerConsumption'
    },
    {
      label: '累计油耗(L)',
      prop: 'cumulativeFuelConsumption'
    }
  ]
}

const listLoading = ref(false)

const formatter = (row: List, column: any) => {
  return row[column.property] ?? 0
}

const getList = useDebounceFn(async () => {
  listLoading.value = true
  try {
    const res = (await IotRhDailyReportApi.getIotRhDailyReportSummary(query.value)) as {
      total: number
      list: any[]
    }

    const { total: resTotal, list: resList } = res

    total.value = resTotal

    type.value = resList[0]?.type || '2'

    list.value = resList.map(
      ({ id, projectDeptIa, projectDeptName, teamId, teamName, sort, taskId, type, ...other }) => ({
        id: type === '2' ? projectDeptIa : teamId,
        name: type === '2' ? projectDeptName : teamName,
        ...other,
        cumulativeGasInjection: (other.cumulativeGasInjection || 0) / 10000
      })
    )
  } finally {
    listLoading.value = false
  }
}, 1000)

const handleDeptNodeClick = (node: any) => {
  query.value.deptId = node.id
  handleQuery()
}

const handleQuery = (setPage = true) => {
  if (setPage) {
    query.value.pageNo = 1
  }
  getTotal()
  getList()
}

const resetQuery = () => {
  query.value = {
    pageNo: 1,
    pageSize: 10,
    deptId: 157,
    contractName: '',
    taskName: '',
    createTime: []
  }
  handleQuery()
}

watch(
  () => query.value.createTime,
  () => handleQuery(false)
)

onMounted(() => {
  handleQuery()
})
</script>

<template>
  <div class="grid grid-cols-[16%_1fr] gap-5">
    <div class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow p-4">
      <DeptTree2 :deptId="id" @node-click="handleDeptNodeClick" />
    </div>
    <div class="grid grid-rows-[62px_164px_1fr] h-full gap-5">
      <el-form
        size="default"
        class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 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-240px"
            />
          </el-form-item>
          <el-form-item 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"
              class="!w-220px"
            />
          </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-form-item>
      </el-form>
      <div class="grid grid-cols-7 gap-8">
        <div
          v-for="info in totalWorkKeys"
          :key="info[0]"
          class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow p-4 flex flex-col items-center justify-center gap-2"
        >
          <div class="size-7.5" :class="info[3]"></div>
          <count-to class="text-2xl font-medium" :start-val="0" :end-val="totalWork[info[0]]">
            <span class="text-xs leading-8 text-[var(--el-text-color-regular)]">暂无数据</span>
          </count-to>
          <div class="text-xs font-medium text-[var(--el-text-color-regular)]">{{ info[1] }}</div>
          <div class="text-sm font-medium text-[var(--el-text-color-regular)]">{{ info[2] }}</div>
        </div>
      </div>
      <div class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow pt-4 px-8">
        <el-table
          v-loading="listLoading"
          :data="list"
          :stripe="true"
          :style="{ width: '100%' }"
          max-height="600"
          class="min-h-143"
          show-overflow-tooltip
        >
          <el-table-column
            v-for="item in columns(type)"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            align="center"
            :formatter="formatter"
          />
        </el-table>

        <Pagination
          class="mt-8"
          :total="total"
          v-model:page="query.pageNo"
          v-model:limit="query.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>

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

:deep(.el-table) {
  border-top-right-radius: 8px;
  border-top-left-radius: 8px;

  .el-table__cell {
    height: 52px;
  }

  .el-table__header-wrapper {
    .el-table__cell {
      background: var(--el-fill-color-light);
    }
  }
}
</style>
