<template>
    <div class="device-control">
        <!--治理效果报表 -->
        <div v-show="fullscreen">
            <!-- <PointTree :height="flag ? 106 : 50" @node-click="nodeClick" @pointTypeChange="pointTypeChange"></PointTree> -->
            <APFTree :height="flag ? 126 : 70" @node-click="handleNodeClick" template @init="handleNodeClick"></APFTree>
        </div>
        <div>
            <TableHeader :showReset="false" :timeKeyList="prop.timeKey" ref="TableHeaderRef" datePicker
                @selectChange="selectChange" v-if="fullscreen">
                <template v-slot:select>
                    <el-form-item label="模板策略">
                        <el-select filterable v-model="tableStore.table.params.tempId" placeholder="请选择模板策略" clearable>
                            <el-option v-for="item in templateList" :key="item.id" :label="item.excelName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="监测对象">
                        <el-select filterable v-model="tableStore.table.params.sensitiveUserId" placeholder="请选择监测对象"
                            clearable>
                            <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">导出</el-button>
                </template>
            </TableHeader>

            <div style="display: flex">
                <div id="luckysheet" :style="{
                    width: `calc(${prop.width} - ${fullscreen ? 290 : 0}px)`,
                    height: `calc(${prop.height} - 57px + ${fullscreen ? 0 : 56}px)`
                }" v-if="tableStore.table.data.length"></div>
                <el-empty description="暂无报表" v-else style="flex: 1" :style="{
                    width: `calc(${prop.width} - ${fullscreen ? 290 : 0}px)`,
                    height: `calc(${prop.height} - 57px + ${fullscreen ? 0 : 56}px)`
                }"></el-empty>
            </div>
        </div>

    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, provide, reactive, watch, h, computed, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import { exportExcel } from '@/views/govern/reportForms/export.js'
import { destroyLuckysheet, renderLuckysheetReport } from '@/utils/luckysheetHelper'
import { buildExportBaseName } from '@/utils/echartMethod'
import TableHeader from '@/components/table/header/index.vue'
import { querySysExcel } from '@/api/harmonic-boot/luckyexcel'
import { getListByIds } from '@/api/harmonic-boot/cockpit/cockpit'
import { getTime } from '@/utils/formatTime'
import { ElMessage } from 'element-plus'
import APFTree from '@/components/tree/govern/APFTree.vue'
const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: Array as () => string[] },
    timeValue: { type: Object },
    interval: { type: Number },
    flag: { type: Boolean }
})

const TableHeaderRef = ref()

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

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


const exportSubjectName = ref('')

const handleNodeClick = async (data: any) => {
    if (templateList.value.length == 0) {
        await querySysExcel({}).then(res => {
            templateList.value = res.data.filter(item => item.excelType == 4)
            if (!tableStore.table.params.tempId && templateList.value?.length > 0) {
                tableStore.table.params.tempId = templateList.value[0].id
            }
        })
    }

    if (data?.level == 3 || data?.level == 2) {
        exportSubjectName.value = data.name || ''
        tableStore.exportName = { subject: exportSubjectName.value, feature: '治理效果报表' }
        tableStore.table.params.sensitiveUserId = data.id
        await tableStore.index()
    } else {
        tableStore.table.loading = false
    }
}


const templateListData = () => {
    querySysExcel({}).then(res => {
        templateList.value = res.data.filter(item => item.excelType == 4)
        if (!tableStore.table.params.tempId && templateList.value?.length > 0) {
            tableStore.table.params.tempId = templateList.value[0].id
        }
        nextTick(() => {
            tableStore.index()
        })
    })
}
// 下载表格
const downloadExcel = () => {
    exportExcel(
        luckysheet.getAllSheets(),
        buildExportBaseName({
            subject: exportSubjectName.value,
            feature: '治理效果报表',
            date: tableStore.table.params.searchEndTime || tableStore.table.params.searchBeginTime
        })
    )
}

onMounted(() => {

    // initListByIds()
})
onUnmounted(() => {
    destroyLuckysheet()
})

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
    }
})

const tableStore: any = new TableStore({
    url: '/cs-harmonic-boot/customReport/getSensitiveUserReport',
    method: 'POST',
    showPage: false,
    exportName: '治理效果报表',
    column: [],
    beforeSearchFun: () => {
        setTime()
        // if (!tableStore.table.params.sensitiveUserId && idList.value?.length > 0) {
        //     tableStore.table.params.sensitiveUserId = idList.value[0].id
        // }
        // if (!tableStore.table.params.tempId && templateList.value?.length > 0) {
        //     tableStore.table.params.tempId = templateList.value[0].id
        // }
        // if( !tableStore.table.params.tempId){
        //     return ElMessage.warning('请选择模板')
        // }
    },
    loadCallback: () => {
        renderLuckysheetReport('luckysheet', tableStore.table.data, { allowEdit: false })
    }
})

const tableRef = ref()
provide('tableRef', tableRef)

provide('tableStore', tableStore)

const setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || prop.interval) ?? 0,
        prop.timeKey,
        fullscreen.value
            ? [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
            : prop.timeValue
    )

    if (Array.isArray(time)) {
        tableStore.table.params.searchBeginTime = time[0]
        tableStore.table.params.searchEndTime = time[1]
        tableStore.table.params.startTime = time[0]
        tableStore.table.params.endTime = time[1]
        TableHeaderRef.value?.setInterval(time[2] - 0)
        TableHeaderRef.value?.setTimeInterval([time[0], time[1]])
    } else {
        console.warn('获取时间失败，time 不是一个有效数组')
    }
}

watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
watch(
    () => prop.height,
    val => {
        renderLuckysheetReport('luckysheet', tableStore.table.data, { allowEdit: false })
    }
)
watch(
    () => prop.timeValue,
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true
    }
)
</script>
<style lang="scss" scoped>
// :deep(.el-select) {
//     min-width: 80px;
// }
.device-control {
    display: flex;
}

:deep(.cn-tree) {
    padding: 0 10px 0 0 !important;
}
</style>
