<template>
    <div class="report-word-panel">
        <TableHeader ref="tableHeaderRef" datePicker :show-search="false">
            <template #select>
                <!-- <el-form-item label="客户名称">
                    <el-input v-model="tableStore.table.params.crmName" maxlength="32" show-word-limit clearable
                        placeholder="请输入客户名称" />
                </el-form-item>
                <el-form-item label="报表编号">
                    <el-input v-model="tableStore.table.params.reportNumber" maxlength="32" show-word-limit clearable
                        placeholder="请输入报表编号" />
                </el-form-item> -->
            </template>
            <template #operation>
                <!-- <el-upload :show-file-list="false" ref="uploadRef" action="" accept=".png,.jpg,.jpeg"
                    :on-change="choose" :auto-upload="false">
                    <template #trigger>
                        <el-button icon="el-icon-Upload" type="primary" class="mr10 ml10">上传接线图</el-button>
                    </template>
                </el-upload> -->
                <el-button icon="el-icon-Download" type="primary" @click="exportEvent" :loading="loading">
                    报告生成
                </el-button>
            </template>
        </TableHeader>
        <div v-if="lineFlag" class="box">
            <el-form label-width="auto" class="form-one">
                <el-form-item label="报表编号">
                    <el-input v-model="tableStore.table.params.reportNumber" style="width: 240px;" maxlength="32" show-word-limit clearable
                        placeholder="请输入报表编号" />
                </el-form-item>
                <el-form-item label="客户名称">
                    <el-input v-model="tableStore.table.params.crmName" style="width: 240px;" maxlength="32" show-word-limit clearable
                        placeholder="请输入客户名称" />
                </el-form-item>
               
                <el-form-item label="上传接线图">
                    <el-upload :show-file-list="false" ref="uploadRef" action="" accept=".png,.jpg,.jpeg"
                        :on-change="choose" :auto-upload="false">
                        <template #trigger>
                            <el-button icon="el-icon-Upload" type="primary" >上传接线图</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div v-if="previewUrl" class="upload-preview">
                <div class="upload-preview-header">
                    <span class="upload-preview-title">接线图预览</span>
                    <el-button type="danger" link @click="removeImage">删除</el-button>
                </div>
                <img :src="previewUrl" alt="接线图" class="upload-preview-image" />
            </div>
        </div>
        <el-empty v-else class="report-zl-sheet" description="治理监测点暂不支持出报告" />
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onUnmounted } from 'vue'
import TableStore from '@/utils/tableStore'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage, ElNotification } from 'element-plus'
import { exportModel } from '@/api/cs-harmonic-boot/datatrend'
import { buildExportFileName } from '@/utils/echartMethod'
import { isReportMonitorPoint } from '@/components/tree/govern/lineTreeUtils'

defineOptions({
    name: 'ReportWord',
})

const props = defineProps<{
    dotList: Record<string, any>
    lineFlag: boolean
}>()

const tableHeaderRef = ref()
const uploadRef = ref()
const uploadList = ref<any>(null)
const previewUrl = ref('')
const loading = ref(false)

const tableStore = new TableStore({
    url: '',
    method: 'POST',
    column: [],
    beforeSearchFun: () => { },
    loadCallback: () => { },
})

provide('tableStore', tableStore)

const revokePreviewUrl = () => {
    if (previewUrl.value) {
        URL.revokeObjectURL(previewUrl.value)
        previewUrl.value = ''
    }
}

const choose = (files: any) => {
    const isJPG = files.raw.type === 'image/jpg'
    const isJPEG = files.raw.type === 'image/jpeg'
    const isPNG = files.raw.type === 'image/png'
    if (!isJPG && !isPNG && !isJPEG) {
        ElMessage.warning('上传文件只能是 jpg/png 格式!')
        return false
    }
    revokePreviewUrl()
    uploadList.value = files
    previewUrl.value = URL.createObjectURL(files.raw)
    ElMessage.success('上传成功')
}

const removeImage = () => {
    revokePreviewUrl()
    uploadList.value = null
    uploadRef.value?.clearFiles()
}

onUnmounted(() => {
    revokePreviewUrl()
})

const exportEvent = () => {
    if (!isReportMonitorPoint(props.dotList)) {
        return ElMessage.warning('请选择监测点进行报告生成!')
    }
    if (!props.lineFlag) {
        return ElMessage.warning('治理监测点暂不支持出报告!')
    }

    const specialCharRegex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/
    if (
        specialCharRegex.test(tableStore.table.params.crmName) ||
        specialCharRegex.test(tableStore.table.params.reportNumber)
    ) {
        ElNotification({
            type: 'error',
            message: '包含特殊字符，请注意修改!',
        })
        return
    }

    const form = new FormData()
    form.append('lineIndex', props.dotList.id)
    form.append('name', props.dotList.name)
    form.append('crmName', tableStore.table.params.crmName || '')
    form.append('reportNumber', tableStore.table.params.reportNumber || '')
    form.append('type', '0')
    form.append('startTime', tableHeaderRef.value.datePickerRef.timeValue[0])
    form.append('endTime', tableHeaderRef.value.datePickerRef.timeValue[1])
    form.append('file', uploadList.value?.raw || '')

    loading.value = true
    ElMessage('生成报告中...')

    const now = new Date()

    exportModel(form)
        .then((res: any) => {
            if (res == undefined) return
            const blob = new Blob([res], {
                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8',
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = buildExportFileName({
                subject: props.dotList.name,
                feature: '报告',
                date: tableHeaderRef.value?.datePickerRef?.timeValue?.[1] || now,
                ext: 'docx'
            })
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        })
        .finally(() => {
            loading.value = false
        })
}
</script>

<style lang="scss" scoped>
.report-word-panel {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.box {
    flex: 1;
    min-height: 0;
    padding: 10px;
    overflow: auto;
}

.report-zl-sheet {
    height: 100%;
}

.upload-preview {
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #eee;
}

.upload-preview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.upload-preview-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
}

.upload-preview-image {
    display: block;
    height: 200px;
    max-width: 100%;
    object-fit: contain;
    border: 1px solid #eee;
    border-radius: 4px;
    background: #fafafa;
}
</style>
