<template>
    <div>
        <!--治理效果报表 -->
        <TableHeader :showReset="false" 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.name" :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">导出excel</el-button>
            </template>
        </TableHeader>
        <div style="display: flex">
            <div
                id="luckysheet"
                :style="{
                    width: `calc(${prop.width} )`,
                    height: `calc(${prop.height} - 57px + ${fullscreen ? 0 : 56}px)`
                }"
            ></div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h, computed, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import { exportExcel } from '@/views/govern/reportForms/export.js'
import TableHeader from '@/components/table/header/index.vue'
import { getTemplateList } from '@/api/harmonic-boot/luckyexcel'
import { getListByIds } from '@/api/harmonic-boot/cockpit/cockpit'
import { getTime } from '@/utils/formatTime'

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 },
    interval: { type: Number }
})

const TableHeaderRef = ref()

// 报表模板列表
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
            }
            templateListData()
        }
    })
}

const templateListData = () => {
    getTemplateList({}).then(res => {
        templateList.value = res.data
        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(), '治理效果报表')
}

onMounted(() => {
    initListByIds()
})

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
        }
    },
    loadCallback: () => {
        luckysheet.create({
            container: 'luckysheet',
            title: '', // 表 头名
            lang: 'zh', // 中文
            showtoolbar: false, // 是否显示工具栏
            showinfobar: false, // 是否显示顶部信息栏
            showsheetbar: true, // 是否显示底部sheet按钮
            allowEdit: false, // 禁止所有编辑操作（必填）
            data: tableStore.table.data
        })
    }
})

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]
        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.timeValue,
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true
    }
)
</script>
<style lang="scss" scoped>
// :deep(.el-select) {
//     min-width: 80px;
// }
</style>
