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

defineOptions({ name: 'IotRdDailyReport' })

const { t } = useI18n()
const router = useRouter()
const message = useMessage()
const userStore = useUserStore()
const id = userStore.getUser.deptId
const deptId = id

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

const initQuery: Query = {
  deptId: id
}

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

const currentPage = ref(1)
const pageSize = ref(10)

interface ListItem {
  rdStatus: string
  period: string
  taskStartDate: string
  projectDeptName: string
  deptName: string
  wellName: string
  taskId: number
  items: any[]
  techniques: string
  workloadDesign: string
  totalDailyFuel: string
  nonProductionRate: number
  manufactureName: string
}

const allList = ref<ListItem[]>([])
const total = ref(0)
const loading = ref(false)

const pagedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allList.value.slice(start, end)
})

const loadList = useDebounceFn(async function () {
  loading.value = true
  try {
    const data: any = await IotRdDailyReportApi.statistics(query.value)

    let rawList: ListItem[] = []
    rawList = data
    allList.value = rawList
    total.value = rawList.length
  } finally {
    loading.value = false
  }
})

const dynamicColumns = computed(() => {
  const units = new Set()
  allList.value.forEach((item) => {
    item.items.forEach((subItem) => {
      if (subItem.unit) {
        units.add(subItem.unit)
      }
    })
  })
  return Array.from(units) as string[]
})

const getWorkloadByUnit = (items: any[], unit: string) => {
  if (!items || !Array.isArray(items)) return ''
  const targetItem = items.find((item) => item.unit === unit)
  return targetItem ? targetItem.workload : ''
}

function handleSizeChange(val: number) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val: number) {
  currentPage.value = val
}

// 搜索事件
function handleQuery() {
  currentPage.value = 1
  loadList()
}

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

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

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const exportLoading = ref(false)

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

    exportLoading.value = true
    const res = await IotRdDailyReportApi.exportIotRdDailyReport(query.value)

    download.excel(res, '瑞都日报汇总.xlsx')
  } finally {
    exportLoading.value = false
  }
}

const { ZmTable, ZmTableColumn } = useTableComponents<ListItem>()

function realValue(type: any, value: string) {
  const option = getDictOptions(type).find((item) => item.value === value)
  return option?.label || value
}

function handleWellNameClick(taskId: number) {
  if (!taskId) return

  router.push({
    name: 'IotRdDailyReport',
    query: {
      taskId: taskId
    }
  })
}
</script>

<template>
  <div
    class="grid grid-cols-[auto_minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]">
    <DeptTreeSelect
      :top-id="163"
      :deptId="deptId"
      v-model="query.deptId"
      :show-title="false"
      class="row-span-2" />

    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-2"> </div> -->
    <el-form
      size="default"
      :model="query"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 py-3 gap-6 flex items-center justify-between flex-wrap min-w-0">
      <div class="flex items-center gap-6 flex-wrap">
        <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="创建时间" 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-300px max-w-full"
            :shortcuts="rangeShortcuts" />
        </el-form-item>
      </div>
      <el-form-item class="daily-report-actions shrink-0">
        <div class="flex flex-wrap items-center justify-end gap-3">
          <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-rd-daily-report:create']">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button type="success" plain @click="handleExport" :loading="exportLoading">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <div class="min-h-0 bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4">
      <div class="flex-1 relative">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <zm-table
              :data="pagedList"
              :loading="loading"
              :width="width"
              :max-height="height"
              :height="height"
              show-border>
              <zm-table-column
                prop="rdStatus"
                :label="t('project.status')"
                :real-value="
                  (row: ListItem) => realValue(DICT_TYPE.PMS_PROJECT_RD_STATUS, row.rdStatus ?? '')
                ">
                <template #default="scope">
                  <dict-tag
                    :type="DICT_TYPE.PMS_PROJECT_RD_STATUS"
                    :value="scope.row.rdStatus ?? ''" />
                </template>
              </zm-table-column>
              <zm-table-column prop="period" label="施工周期(D)" />
              <zm-table-column prop="taskStartDate" label="任务开始日期" />
              <zm-table-column prop="projectDeptName" label="项目部" />
              <zm-table-column prop="deptName" label="队伍" />
              <zm-table-column prop="wellName" label="井号">
                <template #default="scope">
                  <el-link
                    type="primary"
                    @click="handleWellNameClick(scope.row.taskId)"
                    underline="never">
                    {{ scope.row.wellName }}
                  </el-link>
                </template>
              </zm-table-column>
              <zm-table-column prop="techniques" label="工艺" />
              <zm-table-column prop="workloadDesign" label="总工作量" />
              <zm-table-column prop="totalDailyFuel" label="油耗(L)" />
              <zm-table-column label="已完成工作量">
                <template v-for="(column, index) in dynamicColumns" :key="index">
                  <zm-table-column :prop="column" :label="column">
                    <template #default="scope">
                      {{ getWorkloadByUnit(scope.row.items, column) }}
                    </template>
                  </zm-table-column>
                </template>
              </zm-table-column>
              <zm-table-column
                prop="nonProductionRate"
                label="非生产时效"
                cover-formatter
                :real-value="
                  (row) => (Number(row.nonProductionRate ?? 0) * 100).toFixed(2) + '%'
                " />
              <zm-table-column prop="manufactureName" label="甲方" action />
            </zm-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="currentPage"
          v-model:page-size="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>

  <IotRdDailyReportForm ref="formRef" @success="loadList" />
</template>

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

.daily-report-actions :deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>
