<template>
    <el-dialog
        :title="dialogMode === 'detail' ? '定检详情' : '上传周期检测报告'"
        :width="dialogMode === 'detail' ? '1000px' : '600px'"
        v-model="dialogShow"
        v-if="dialogShow"
    >
        <!-- 详情区域 -->
        <div v-if="dialogMode === 'detail'">
        </div>
        <!-- 上传报告表单区域 -->
        <div v-if="dialogMode === 'upload'">
            <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="120px">
                <el-form-item label="定检日期" prop="thisCheckTime">
                    <el-date-picker
                        v-model="uploadForm.thisCheckTime"
                        type="date"
                        placeholder="请选择定检日期"
                        @change="calcNextCheckTime"
                        style="width:100%"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item label="下次定检日期" prop="nextCheckTime">
                    <el-date-picker
                        v-model="uploadForm.nextCheckTime"
                        type="date"
                        placeholder="请选择下次定检日期"
                        style="width:100%"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item class="uploadFile" for="-" label="设备检测报告：">
                    <el-upload
                        v-model:file-list="uploadForm.checkUrl"
                        ref="uploadRef"
                        action=""
                        :accept="acceptType"
                        :limit="1"
                        :on-change="(file) => choose(file, 'checkUrl')"
                        :auto-upload="false"
                        :on-remove="removeFile('checkUrl')"
                    >
                        <template #trigger>
                            <el-button type="primary">上传文件</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <el-button v-if="dialogMode === 'upload'" @click="dialogShow = false">取消</el-button>
            <el-button
                v-if="dialogMode === 'upload'"
                type="primary"
                :loading="submitLoading"
                @click="submitUploadReport"
            >
                提交
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import type { UploadFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { uploadFile } from '@/api/system-boot/file'
import { userCheckUpload } from '@/api/device-boot/device'

const emit = defineEmits(['onSubmit'])

const acceptType = '.pdf,.docx'

const detailId = ref('')
const dialogShow = ref(false)
const dialogMode = ref<'detail' | 'upload'>('detail')
const submitLoading = ref(false)

const uploadFormRef = ref()
const uploadForm = reactive({
    thisCheckTime: '',
    nextCheckTime: '',
    checkUrl: [] as any[],
    devId: '',
    objId: ''
})
const checkUrlFile = ref('')

const calcNextCheckTime = (dateVal: string) => {
    if (!dateVal) {
        uploadForm.nextCheckTime = ''
        return
    }
    const date = new Date(dateVal)
    date.setFullYear(date.getFullYear() + 3)
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    uploadForm.nextCheckTime = `${y}-${m}-${d}`
}

const uploadRules = reactive({
    thisCheckTime: [{ required: true, message: '请选择定检日期', trigger: 'change' }],
    checkUrl: [{ required: true, message: '请上传设备检测报告', trigger: 'change' }]
})

const submitUploadReport = async () => {
    await uploadFormRef.value?.validate(async (valid: boolean) => {
        if (!valid) return
        submitLoading.value = true
        try {
            const params = {
                devId: uploadForm.devId,
                objId: uploadForm.objId,
                thisCheckTime: uploadForm.thisCheckTime,
                nextCheckTime: uploadForm.nextCheckTime,
                checkUrl: checkUrlFile.value
            }
            const res = await userCheckUpload(params)
            if (res.code === 'A0000') {
                ElMessage.success('提交成功')
                dialogShow.value = false
                emit('onSubmit')
            }
        } catch (err: any) {
            ElMessage.error(err.msg || '提交失败')
        } finally {
            submitLoading.value = false
        }
    })
}

const getFileName = (filePath: string) => {
    if (!filePath) return ''
    const parts = filePath.split('/')
    return parts[parts.length - 1] || filePath.replace(/^.*?\/(.*?)\//, '')
}

const openUpload = (row: any) => {
    uploadForm.devId = row.devId
    uploadForm.objId = row.objId
    uploadForm.thisCheckTime = row.thisCheckTime || ''
    uploadForm.nextCheckTime = row.nextCheckTime || ''
    if (row.checkUrl) {
        checkUrlFile.value = row.checkUrl
        uploadForm.checkUrl = [{ name: getFileName(row.checkUrl), url: row.checkUrl }]
    } else {
        checkUrlFile.value = ''
        uploadForm.checkUrl = []
    }
    dialogMode.value = 'upload'
    dialogShow.value = true
    nextTick(() => {
        uploadFormRef.value?.clearValidate()
    })
}

const openDetail = (id: string) => {
    detailId.value = id
    dialogMode.value = 'detail'
    dialogShow.value = true
}

const removeFile = (val: string) => {
    return (_file: UploadFile, fileList: UploadFile[]) => {
        if (val === 'checkUrl') {
            checkUrlFile.value = ''
        }
        uploadForm[val] = fileList
    }
}

const choose = (e: any, field: string) => {
    uploadFile(e.raw, '/supervision/').then(res => {
        if (field === 'checkUrl') {
            checkUrlFile.value = res.data.name
        }
    })
}

defineExpose({ openUpload, openDetail })
</script>
