<template>
    <div>
        <!--治理效果报表 -->
        <TableHeader :showReset="false" datePicker @selectChange="selectChange" v-if="fullscreen">
            <template v-slot:select>
                <el-form-item label="报表模板">
                    <el-select
                        v-model="tableStore.table.params.tempId"
                        placeholder="请选择报表模板"
                        clearable
                        style="width: 130px"
                    >
                        <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="监测对象">
                    <el-select
                        v-model="tableStore.table.params.sensitiveUserId"
                        placeholder="请选择监测对象"
                        clearable
                        style="width: 130px"
                    >
                        <el-option
                            v-for="item in idList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </template>
            <template v-slot:operation>
                <el-button @click="downloadExcel" class="" type="primary" icon="el-icon-Download">导出excel</el-button>
            </template>
        </TableHeader>
        <div style="display: flex; border: red solid 1px">
            <div
                id="luckysheet-before"
                :style="{
                    width: `calc(${prop.width} / 2 - 10px)`,
                    height: `calc(${prop.height} - 57px + ${fullscreen ? 0 : 56}px)`
                }"
                style="border: yellow solid 1px"
            ></div>
            <div
                id="luckysheet-after"
                :style="{
                    width: `calc(${prop.width} / 2 - 10px)`,
                    height: `calc(${prop.height} - 57px + ${fullscreen ? 0 : 56}px)`,
                    marginLeft: '10px'
                }"
            ></div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h, computed } from 'vue'
import TableStore from '@/utils/tableStore'
import { exportExcel } from '@/views/govern/reportForms/export.js'
import TableHeader from '@/components/table/header/index.vue'
import { useConfig } from '@/stores/config'
import Json from './index.json'
import JsonAfter from './index.json'
import { getTemplateList } from '@/api/harmonic-boot/luckyexcel'
import { getListByIds } from '@/api/harmonic-boot/cockpit/cockpit'

const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: [String, Number] },
    timeValue: { type: Object }
})
const config = useConfig()
const powerList: any = ref([
    {
        label: '1#变压器',
        value: '1'
    },
    {
        label: '2#变压器',
        value: '2'
    }
])

const tableStore: any = new TableStore({
    url: '/user-boot/role/selectRoleDetail?id=0',
    method: 'POST',

    showPage: false,
    exportName: '主要监测点列表',
    column: [],
    beforeSearchFun: () => {
        tableStore.table.params.searchBeginTime = tableStore.table.params.searchBeginTime || prop.timeValue?.[0]
        tableStore.table.params.searchEndTime = tableStore.table.params.searchEndTime || prop.timeValue?.[1]
    },
    loadCallback: () => {}
})

const tableRef = ref()
provide('tableRef', tableRef)
tableStore.table.params.power = '1'

provide('tableStore', tableStore)

// 报表模板列表
const templateList = ref([])

// 监测对象
const idList = ref()

// 监测对象
const initListByIds = () => {
    getListByIds({}).then((res: any) => {
        if (res.data.length > 0) {
            idList.value = res.data
            if (!tableStore.table.params.sensitiveUserId && idList.value?.length > 0) {
                tableStore.table.params.sensitiveUserId = idList.value[0].id
            }
        }
    })
}

const templateListData = () => {
    getTemplateList({}).then(res => {
        templateList.value = res.data
        if (!tableStore.table.params.tempId && templateList.value?.length > 0) {
            tableStore.table.params.tempId = res.data[0].id
        }
    })
}

// 治理前和治理后的Luckysheet实例
let luckysheetBefore: any
let luckysheetAfter: any

onMounted(() => {
    templateListData()
    // 等待DOM更新完成后再创建Luckysheet实例
    nextTick(() => {
        setTimeout(() => {
            createLuckysheets()
        }, 100)
    })
})

// 下载表格
const downloadExcel = () => {
    // 可以选择导出治理前、治理后或两个报表
    const beforeSheets = luckysheetBefore.getAllSheets()
    const afterSheets = luckysheetAfter.getAllSheets()
    exportExcel([...beforeSheets, ...afterSheets], '治理效果对比报表')
}

onMounted(() => {
    templateListData()
    initListByIds()
    nextTick(() => {
        setTimeout(() => {
            createLuckysheets()
        }, 100)
    })
})

const createLuckysheets = () => {
    try {
        // 检查容器
        const beforeContainer = document.getElementById('luckysheet-before')
        const afterContainer = document.getElementById('luckysheet-after')

        if (!beforeContainer) {
            return
        }

        if (!afterContainer) {
            return
        }

        // 验证并准备数据
        const beforeData = Json && Array.isArray(Json) ? Json : []
        const afterData = JsonAfter && Array.isArray(JsonAfter) ? JsonAfter : []

        // 创建治理前报表
        luckysheetBefore = luckysheet.create({
            container: 'luckysheet-before',
            title: '治理前',
            lang: 'zh',
            showtoolbar: false,
            showinfobar: false,
            showsheetbar: true,
            allowEdit: false,
            data: beforeData
        })

        // 创建治理后报表
        luckysheetAfter = luckysheet.create({
            container: 'luckysheet-after',
            title: '治理后',
            lang: 'zh',
            showtoolbar: false,
            showinfobar: false,
            showsheetbar: true,
            allowEdit: false,
            data: afterData
        })

        tableStore.index()
    } catch (error) {
        console.error('创建Luckysheet实例时发生错误:', error)
    }
}

const selectChange = (showSelect: any, height: any, datePickerValue?: any) => {
    if (datePickerValue && datePickerValue.timeValue) {
        // 更新时间参数
        tableStore.table.params.searchBeginTime = datePickerValue.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerValue.timeValue[1]
    }
}

// 计算是否全屏展示
const fullscreen = computed(() => {
    const w = Number(prop.w)
    const h = Number(prop.h)
    if (!isNaN(w) && !isNaN(h) && w === 12 && h === 6) {
        // 执行相应逻辑
        return true
    } else {
        return false
    }
})
watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
watch(
    () => prop.timeValue,
    (newVal, oldVal) => {
        // 当外部时间值变化时，更新表格的时间参数
        if (newVal && (!oldVal || newVal[0] !== oldVal[0] || newVal[1] !== oldVal[1])) {
            tableStore.table.params.searchBeginTime = newVal[0]
            tableStore.table.params.searchEndTime = newVal[1]
            tableStore.index()
        }
    },
    {
        deep: true
    }
)
</script>
<style lang="scss" scoped>
// :deep(.el-select) {
//     min-width: 80px;
// }
</style>
