<script setup lang="ts">
import { FiveIotProjectDailyReportApi } from '@/api/pms/fiveconstructiondailyreport'
import dayjs from 'dayjs'
import type { FormInstance } from 'element-plus'
import ConstructionDailyReportFormSection from './ConstructionDailyReportFormSection.vue'
import {
  createEmptyConstructionDailyReport,
  formSections,
  type ConstructionDailyReportRow
} from './report-config'

interface Props {
  visible: boolean
  loadList: () => void | Promise<void>
}

const props = defineProps<Props>()
const emits = defineEmits(['update:visible'])

const formRef = ref<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)
const drawerMode = ref<'edit' | 'readonly'>('edit')
const form = ref<ConstructionDailyReportRow>(createEmptyConstructionDailyReport())
const message = useMessage()

const drawerTitle = computed(() =>
  drawerMode.value === 'readonly' ? '查看施工日报' : '填报施工日报'
)
const disabled = computed(() => drawerMode.value === 'readonly')

function normalizeDetail(detail: Record<string, any> = {}) {
  const createTime = detail.createTime
  const constructionEndDate = detail.constructionEndDate
  return {
    ...createEmptyConstructionDailyReport(),
    ...detail,
    createTime: createTime
      ? dayjs(createTime).isValid()
        ? dayjs(createTime).format('YYYY-MM-DD')
        : createTime
      : detail.createTime,
    constructionEndDate: constructionEndDate
      ? dayjs(constructionEndDate).isValid()
        ? dayjs(constructionEndDate).format('YYYY-MM-DD')
        : constructionEndDate
      : detail.constructionEndDate
  } as ConstructionDailyReportRow
}

async function loadDetail(id: number) {
  loading.value = true
  try {
    const detail = await FiveIotProjectDailyReportApi.getIotProjectDailyReport(id)
    form.value = normalizeDetail(detail)
  } finally {
    loading.value = false
  }
}

async function handleOpenForm(id: number, type: 'edit' | 'readonly') {
  drawerMode.value = type
  emits('update:visible', true)
  await loadDetail(id)
  nextTick(() => formRef.value?.clearValidate())
}

async function handleSubmit() {
  // console.log('handleSubmit', form.value)
  // return
  if (drawerMode.value === 'readonly') {
    emits('update:visible', false)
    return
  }

  submitLoading.value = true
  try {
    const payload = { ...form.value } as Record<string, any>
    await FiveIotProjectDailyReportApi.updateIotProjectDailyReport(payload)
    message.success('保存成功')
    emits('update:visible', false)
    await props.loadList()
  } finally {
    submitLoading.value = false
  }
}

function handleModelChange(value: ConstructionDailyReportRow) {
  form.value = value
}

defineExpose({ handleOpenForm })
</script>

<template>
  <el-drawer
    :model-value="props.visible"
    size="80%"
    destroy-on-close
    header-class="mb-0!"
    @update:model-value="emits('update:visible', $event)">
    <template #header>
      <span class="text-xl font-bold text-[var(--el-text-color-primary)]">{{ drawerTitle }}</span>
    </template>

    <el-form ref="formRef" :model="form" label-position="top" v-loading="loading">
      <div class="flex flex-col gap-6">
        <ConstructionDailyReportFormSection
          v-for="section in formSections"
          :key="section.title"
          :model="form"
          :section="section"
          :disabled="disabled"
          @update:model="handleModelChange" />
      </div>
    </el-form>

    <template #footer>
      <el-button size="default" @click="emits('update:visible', false)">取消</el-button>
      <el-button
        size="default"
        v-if="!disabled"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-drawer>
</template>
