<script setup lang="ts">
import { FiveIotProjectDailyReportApi } from '@/api/pms/fiveconstructiondailyreport'
import { useUserStore } from '@/store/modules/user'
import { rangeShortcuts } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'
import ConstructionDailyReportDrawer from './components/ConstructionDailyReportDrawer.vue'
import ConstructionDailyReportTable from './components/ConstructionDailyReportTable.vue'
import type {
  ConstructionDailyReportQuery,
  ConstructionDailyReportRow
} from './components/report-config'

defineOptions({ name: 'ConstructionDailyReport' })

const userStore = useUserStore()
const deptId = userStore.getUser.deptId
const route = useRoute()

const parseQueryNumber = (value: unknown) => {
  if (Array.isArray(value)) {
    return parseQueryNumber(value[0])
  }
  if (value === undefined || value === null || value === '') {
    return undefined
  }
  const parsedValue = Number(value)
  return Number.isNaN(parsedValue) ? undefined : parsedValue
}

const resolveCreateTimeFromRoute = () => {
  const createTime = route.query.createTime
  if (Array.isArray(createTime)) {
    const values = createTime.filter((item): item is string => typeof item === 'string')
    return values.length === 2 ? values : undefined
  }
  if (typeof createTime === 'string') {
    const values = createTime.split(',').filter(Boolean)
    return values.length === 2 ? values : undefined
  }
  return undefined
}

const createDefaultQuery = (): ConstructionDailyReportQuery => ({
  pageNo: 1,
  pageSize: 10,
  deptId: parseQueryNumber(route.query.deptId) ?? deptId,
  projectDeptId: parseQueryNumber(route.query.projectDeptId),
  teamId: parseQueryNumber(route.query.teamId),
  createTime: resolveCreateTimeFromRoute()
})

const query = ref<ConstructionDailyReportQuery>(createDefaultQuery())
const list = ref<ConstructionDailyReportRow[]>([])
const total = ref(0)
const loading = ref(false)
const visible = ref(false)
const formRef = ref<InstanceType<typeof ConstructionDailyReportDrawer>>()

function syncQueryFromRoute() {
  const nextQuery = createDefaultQuery()
  query.value = {
    ...query.value,
    deptId: nextQuery.deptId,
    projectDeptId: nextQuery.projectDeptId,
    teamId: nextQuery.teamId,
    createTime: nextQuery.createTime
  }
}

const loadList = useDebounceFn(async () => {
  loading.value = true
  try {
    const data = await FiveIotProjectDailyReportApi.getIotProjectDailyReportPage(query.value as any)
    list.value = data.list ?? []
    total.value = data.total ?? 0
  } finally {
    loading.value = false
  }
}, 200)

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

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

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

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

function handleOpenForm(id: number, type: 'edit' | 'readonly') {
  formRef.value?.handleOpenForm(id, type)
}

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

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

onMounted(() => {
  if (route.query.id) {
    handleOpenForm(Number(route.query.id), 'edit')
  }
})
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[62px_1fr] gap-4 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="deptId"
      :show-title="false"
      class="row-span-2" />
    <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.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery()"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="生产任务">
          <el-input
            v-model="query.wellName"
            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-260px" />
        </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>

    <ConstructionDailyReportTable
      :list="list"
      :loading="loading"
      :total="total"
      :page-no="query.pageNo"
      :page-size="query.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <template #action="{ row }">
        <el-button
          v-if="row.status === 0"
          link
          type="primary"
          @click="handleOpenForm(row.id!, 'edit')"
          v-hasPermi="['pms:iot-five-daily-report:update']">
          填报
        </el-button>
        <el-button
          v-else-if="row.status === 1"
          link
          type="success"
          @click="handleOpenForm(row.id!, 'readonly')"
          v-hasPermi="['pms:iot-five-daily-report:query']">
          查看
        </el-button>
      </template>
    </ConstructionDailyReportTable>
  </div>

  <ConstructionDailyReportDrawer ref="formRef" v-model:visible="visible" :load-list="loadList" />
</template>

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