<template>
    <div class="default-main" :style="height">
        <splitpanes style="height: 100%" class="default-theme" id="navigation-splitpanes">
            <pane :size="size">
                <PointTree
                    v-if="showTree"
                    :default-expand-all="false"
                    @node-click="handleNodeClick"
                    @init="handleNodeClick"
                ></PointTree>
            </pane>
            <pane style="background: #fff" :style="height">
                <TableHeader ref="TableHeaderRef" datePicker :isStatisticData="isStatisticData" @selectChange="selectChange">
                    <template v-slot:select>
                        <el-form-item >
                            <el-radio-group v-model="isStatisticData" @change="onStatisticDataChange">
                                <el-radio-button value="0">统计数据</el-radio-button>
                                <el-radio-button value="1">分钟数据</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="模板策略">
                            <el-select v-model="Template" @change="changetype" placeholder="请选择模版" value-key="id" filterable>
                                <el-option
                                    v-for="item in templatePolicy"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="报表类型">
                            <el-input readonly type="text" value="分析报表"></el-input>
                           
                        </el-form-item> -->
                    </template>
                    <template #operation>
                        <el-button icon="el-icon-Download" type="primary" @click="exportEvent">导出excel</el-button>
                        <el-button
                            icon="el-icon-Download"
                            :loading="loading"
                            @click="exportReport"
                            type="primary"
                            v-if="VITE_FLAG"
                        >
                            下载报告
                        </el-button>
                    </template>
                </TableHeader>
                <div class="box">
                    <div id="luckysheet" :style="`height: calc(${tableStore.table.height} + 45px)`"></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 { exportModelJB } from '@/api/harmonic-boot/harmonic'
import { mainHeight } from '@/utils/layout'
import { getTemplateByDept } from '@/api/harmonic-boot/luckyexcel'
import { exportExcel } from '@/views/system/reportForms/export.js'
import { ElMessage } from 'element-plus'
defineOptions({
    name: 'harmonic-boot/xieboReport'
})
const VITE_FLAG = import.meta.env.VITE_NAME == 'jibei'
const showTree = ref(false)
const height = mainHeight(20)
const size = ref(19)
const dictData = useDictData()
const TableHeaderRef = ref()
const dotList: any = ref({})
const Template: any = ref({})
const reportForm: any = ref('')
const name = ref('')
const isStatisticData = ref('0')
const templatePolicy: any = ref([])
const reportFormList: any = ref([
    {
        value: '1',
        label: '分析报表'
    },
    {
        value: '2',
        label: '统计报表'
    },
    {
        value: '3',
        label: '自定义报表'
    }
])
const tableStore = new TableStore({
    url: '/harmonic-boot/customReport/getCustomReport',
    method: 'POST',
    column: [],
    beforeSearchFun: () => {
        tableStore.table.params.tempId = Template.value.id
        tableStore.table.params.lineId = dotList.value.id
        name.value = dotList.value.name
        if (Number(isStatisticData.value) === 1) {
            tableStore.table.params.isStatisticData = 1
        } else {
            delete tableStore.table.params.isStatisticData
        }
    },
    loadCallback: () => {
        tableStore.table.data.forEach((item: any) => {
            item.data1 ? (item.data = JSON.parse(item.data1)) : ''
            item.celldata.forEach((k: any) => {
                item.data[k.r][k.c].v ? (item.data[k.r][k.c] = k.v) : ''
            })
        })
      
        setTimeout(() => {
            luckysheet.create({
                container: 'luckysheet',
                title: '', // 表 头名
                lang: 'zh', // 中文
                showtoolbar: false, // 是否显示工具栏
                showinfobar: false, // 是否显示顶部信息栏
                showsheetbar: true, // 是否显示底部sheet按钮
                allowEdit: false, // 禁止所有编辑操作（必填）
                data: tableStore.table.data
            })
        }, 10)
    },
    resetCallback: () => {
        // 重置模板策略为第一个选项
        if (templatePolicy.value && templatePolicy.value.length > 0) {
            Template.value = templatePolicy.value[0]
            reportForm.value = templatePolicy.value[0]?.reportForm
        }
    }
})
const loading = ref(false)
provide('tableStore', tableStore)

onMounted(() => {
    const dom = document.getElementById('navigation-splitpanes')
    if (dom) {
        size.value = Math.round((180 / dom.offsetHeight) * 120)
    }
})
getTemplateByDept({ id: dictData.state.area[0].id })
    .then((res: any) => {
        templatePolicy.value = res.data
        Template.value = res.data[0]
        reportForm.value = res.data[0]?.reportForm
        showTree.value = true
    })
    .catch((err: any) => {
        showTree.value = true
    })
const changetype = (val: any) => {
    reportForm.value = val.reportForm
}
const onStatisticDataChange = () => {
    TableHeaderRef.value?.setTheDate(3)
    if (dotList.value?.id) {

    }
}
const selectChange = () => {
    //console.log('🚀 ~ selectChange ~ tableStore.table.data.lnegth :', tableStore.table.data.length)
    if (tableStore.table.data.length != 0) {
        setTimeout(() => {
            luckysheet && luckysheet?.resize()
        }, 10)
    }
}

const handleNodeClick = (data: any, node: any) => {
    if (data.level == 6) {
        dotList.value = data

        TableHeaderRef.value.setTheDate(3)
        // 重置模板策略为第一个选项
        if (templatePolicy.value && templatePolicy.value.length > 0) {
            Template.value = templatePolicy.value[0]
            reportForm.value = templatePolicy.value[0]?.reportForm
        }
        tableStore.index()
    }
}

const exportEvent = () => {
    // 基础获取
    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')}`
    exportExcel(luckysheet.getAllSheets(), name.value + formattedDate)
}
const exportReport = () => {
    loading.value = true
    let form = new FormData()
    form.append('isUrl', false)
    form.append('lineIndex', dotList.value.id)
    form.append('startTime', TableHeaderRef.value.datePickerRef.timeValue[0])
    form.append('endTime', TableHeaderRef.value.datePickerRef.timeValue[1])
    form.append('type', 0)
    form.append('name', dotList.value.name)
    ElMessage({
        message: '下载报告中,请稍等.....',
        duration: 1000
    })
    exportModelJB(form)
        .then(async res => {
            if (res == undefined) {
                loading.value = false
                return
            }
            let blob = new Blob([res], {
                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            })

            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a') // 创建a标签
            link.href = url
            link.download =
                dotList.value.name +
                TableHeaderRef.value.datePickerRef.timeValue[0] +
                '_' +
                TableHeaderRef.value.datePickerRef.timeValue[1] // 设置下载的文件名
            document.body.appendChild(link)
            link.click() //执行下载
            document.body.removeChild(link)
            loading.value = false
        })
        .catch(() => {
            loading.value = false
        })
}
</script>
<style lang="scss">
.splitpanes.default-theme .splitpanes__pane {
    background: #eaeef1;
}

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