<template>
    <div class="default-main" :style="height">
        <splitpanes style="height: 100%" id="navigation-splitpanes">
            <pane :size="size">
                <CloudDeviceEntryTree
                    ref="TerminalRef"
                    @node-click="handleNodeClick"
                    @init="handleNodeClick"
                ></CloudDeviceEntryTree>
            </pane>
            <pane style="background: #fff" :style="height">
                <TableHeader ref="TableHeaderRef" datePicker :show-search="false">
                    <template v-slot: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"
                                clearable
                                placeholder="请输入报表编号"
                                maxlength="12"
                                show-word-limit
                            />
                        </el-form-item>
                    </template>
                    <template #operation>
                        <el-upload
                            :show-file-list="false"
                            ref="uploadRef"
                            action=""
                            accept=".png,.jpg"
                            :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">生成</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>
                </div>
            </pane>
        </splitpanes>
    </div>
</template>

<script setup lang="ts">
import { onMounted, 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 pointTreeWx from '@/components/tree/govern/pointTreeWx.vue'
import { genFileId, ElMessage, ElNotification } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import CloudDeviceEntryTree from '@/components/tree/govern/cloudDeviceEntryTree.vue'
import { exportModel } from '@/api/cs-harmonic-boot/datatrend'
defineOptions({
    name: 'harmonic-boot/report/word'
})

const height = mainHeight(20)
const size = ref(0)
const dictData = useDictData()
const TableHeaderRef = ref()
const dotList: any = ref({})
const Template: any = ref({})
const uploadList: any = 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) * 100)
    }
})

const handleNodeClick = (data: any, node: any) => {
    dotList.value = data
}
// 上传
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
    }

    uploadList.value = files
    ElMessage.success('上传成功')
}
// 生成
const exportEvent = () => {
    console.log('🚀 ~ exportEvent ~ dotList.value:', dotList.value)
    if (dotList.value?.level != 4) {
        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 {
        ElMessage('生成报告中...')
        const now = new Date()
        const year = now.getFullYear() // 4位年份
        const month = now.getMonth() + 1 // 月份0-11，需+1
        const day = now.getDate() // 日期1-31

        // 格式化YYYY - MM - DD（补零）
        const formattedDate = `${year}${String(month).padStart(2, '0')}${String(day).padStart(2, '0')}`
        exportModel(form).then((res: any) => {
            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 + formattedDate // 设置下载的文件名
            document.body.appendChild(link)
            link.click() //执行下载
            document.body.removeChild(link)
        })
    }
}
</script>
<style lang="scss">
.splitpanes.default-theme .splitpanes__pane {
    background: #eaeef1;
}

.box {
    padding: 10px;
}
</style>
