<template>
    <div class="default-main" :style="height">
        <splitpanes style="height: 100%" class="default-theme" id="navigation-splitpanes">
            <pane :size="size">
                <PointTree
                    :default-expand-all="false"
                    @node-click="handleNodeClick"
                    @init="handleNodeClick"
                ></PointTree>
            </pane>
            <pane style="background: #fff" :style="height">
                <TableHeader ref="TableHeaderRef" datePicker :show-search="false">
                    <template #operation>
                        <el-button icon="el-icon-Download" type="primary" @click="exportEvent" :loading="loading">
                            生成
                        </el-button>
                    </template>
                </TableHeader>
                <div class="box">
                    <!-- <div id="luckysheet">
                        <img
                            width="100%"
                            :style="`height: calc(${tableStore.table.height} + 40px)`"
                            src="@/assets/img/jss.png"
                        />
                    </div> -->
                    <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="formUploadRef"
                                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>
            </pane>
        </splitpanes>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, provide } from 'vue'
import 'splitpanes/dist/splitpanes.css'
import { Splitpanes, Pane } from 'splitpanes'
import TableStore from '@/utils/tableStore'
import PointTree from '@/components/tree/pqs/pointTree.vue'
import TableHeader from '@/components/table/header/index.vue'
import { useDictData } from '@/stores/dictData'
import { mainHeight } from '@/utils/layout'
import { exportModel } from '@/api/process-boot/reportForms'
import { ElMessage, ElNotification } from 'element-plus'
import type { UploadFile, UploadInstance, UploadProps } from 'element-plus'
import dayjs from 'dayjs'
defineOptions({
    // name: 'harmonic-boot/report/word'
})
const loading = ref(false)
const height = mainHeight(20)
const size = ref(19)
const dictData = useDictData()
const TableHeaderRef = ref()
const headerUploadRef = ref<UploadInstance>()
const formUploadRef = ref<UploadInstance>()
const dotList: any = ref({})
const uploadList = ref<UploadFile>()
const previewUrl = ref('')
const tableStore = new TableStore({
    url: '',
    method: 'POST',
    column: [],
    beforeSearchFun: () => {},
    loadCallback: () => {}
})
provide('tableStore', tableStore)

onMounted(() => {
    const dom = document.getElementById('navigation-splitpanes')

    if (dom) {
        size.value = Math.round((180 / dom.offsetHeight) * 120)
    }
})

const handleNodeClick = (data: any, node: any) => {
    dotList.value = data
}

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

const clearUploadRefs = () => {
    headerUploadRef.value?.clearFiles()
    formUploadRef.value?.clearFiles()
}

// 上传
const choose: UploadProps['onChange'] = file => {
    if (!file.raw) return

    const isJPG = file.raw.type === 'image/jpg'
    const isJPEG = file.raw.type === 'image/jpeg'
    const isPNG = file.raw.type === 'image/png'
    if (!isJPG && !isPNG && !isJPEG) {
        ElMessage.warning('上传文件只能是 jpg/png 格式!')
        clearUploadRefs()
        return
    }

    const isLt5M = file.raw.size / 1024 / 1024 < 5
    if (!isLt5M) {
        ElMessage.warning('上传图片大小不能超过 5MB!')
        clearUploadRefs()
        return
    }

    revokePreviewUrl()
    uploadList.value = file
    previewUrl.value = URL.createObjectURL(file.raw)
    ElMessage.success('上传成功')
}

const removeImage = () => {
    revokePreviewUrl()
    uploadList.value = undefined
    clearUploadRefs()
}
// 生成
const exportEvent = () => {
    if (dotList.value.level != 6) {
        return ElMessage.warning('请选择监测点进行报告生成!')
    }

    let form = new FormData()
    form.append('lineIndex', dotList.value.id)
    form.append('name', dotList.value.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])
    //console.log('🚀 ~ exportEvent ~ uploadList.value:', uploadList.value?.raw)
    form.append('file', uploadList.value?.raw || '')
    // 特殊字符正则表达式
    const specialCharRegex = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/
    if (
        specialCharRegex.test(tableStore.table.params.crmName) ||
        specialCharRegex.test(tableStore.table.params.reportNumber)
    ) {
        ElNotification({
            type: 'error',
            message: '包含特殊字符，请注意修改!'
        })
    } else {
        loading.value = true
        ElMessage('生成报告中...')
        exportModel(form)
            .then((res: any) => {
                if (res == undefined) {
                    loading.value = false
                    return
                }
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
                })
                // createObjectURL(blob); //创建下载的链接
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = dotList.value.name + dayjs().format('YYYYMMDD') // 设置下载的文件名
                document.body.appendChild(link)
                link.click() //执行下载
                document.body.removeChild(link)
                loading.value = false
            })
            .catch((err: any) => {
                loading.value = false
            })
    }
}

onBeforeUnmount(() => {
    revokePreviewUrl()
})
</script>
<style lang="scss">
.splitpanes.default-theme .splitpanes__pane {
    background: #eaeef1;
}

.box {
    padding: 10px;
}

.upload-preview {
    margin-top: 16px;
    padding: 12px;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    background: #fafafa;

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

    &-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
    }

    &-image {
        display: block;
        max-width: 100%;
        max-height: 400px;
        object-fit: contain;
        border-radius: 4px;
    }
}
</style>
