<template>
    <div ref="tableHeader" class="cn-table-header">
        <div class="table-header ba-scroll-style">
            <el-form
                style="flex: 1; height: 32px; display: flex; flex-wrap: wrap"
                ref="headerForm"
                @submit.prevent=""
                @keyup.enter="onComSearch"
                label-position="left"
                :inline="true"
            >
                <el-form-item
                    v-if="datePicker"
                    style="grid-column: span 2"
                    :style="{ maxWidth: isStatisticData == 1 ? '750px' : '610px' }"
                >
                    <template #label>
                        <el-checkbox v-if="showTimeAll" v-model="timeAll" label="统计时间" />
                        <span v-else>{{ dateLabel }}</span>
                    </template>
                    <DatePicker
                        ref="datePickerRef"
                        v-if="timeAll"
                        :nextFlag="nextFlag"
                        :theCurrentTime="theCurrentTime"
                        :isStatisticData="isStatisticData"
                    ></DatePicker>
                </el-form-item>

                <el-form-item label="区域" v-if="area">
                    <Area
                        ref="areaRef"
                        v-model="tableStore.table.params.deptIndex"
                        @change-value="onAreaChange"
                        style="width: 200px"
                    />
                </el-form-item>
                <slot name="select"></slot>
            </el-form>
            <template v-if="$slots.select || datePicker || showSearch">
                <el-button type="primary" @click="showSelectChange" v-if="showUnfoldButton">
                    <Icon size="14" name="el-icon-ArrowUp" style="color: #fff" v-if="showSelect" />
                    <Icon size="14" name="el-icon-ArrowDown" style="color: #fff" v-else />
                </el-button>
                <el-button
                    @click="onComSearch"
                    v-if="showSearch"
                    :loading="tableStore.table.loading"
                    type="primary"
                    :icon="Search"
                >
                    查询
                </el-button>
                <el-button
                    @click="onResetForm"
                    v-if="showSearch && showReset"
                    :loading="tableStore.table.loading"
                    :icon="RefreshLeft"
                >
                    重置
                </el-button>
                <el-button
                    @click="onExport"
                    v-if="showExport"
                    :loading="tableStore.table.exportLoading"
                    type="primary"
                    icon="el-icon-Download"
                >
                    导出
                </el-button>
            </template>
            <slot name="operation"></slot>
            <el-button
                class="ml10"
                v-if="showCustomColumn"
                :icon="Setting"
                @mousedown="onCustomColumnMousedown"
                @click="openCustomColumn"
            >
                列设置
            </el-button>
        </div>
        <el-form
            :style="showSelect && showUnfoldButton ? headerFormSecondStyleOpen : headerFormSecondStyleClose"
            ref="headerFormSecond"
            @submit.prevent=""
            @keyup.enter="onComSearch"
            label-position="left"
            :inline="true"
        ></el-form>
    </div>
</template>

<script setup lang="ts">
import { inject, ref, onMounted, nextTick, onUnmounted, watch } from 'vue'
import type TableStore from '@/utils/tableStore'
import DatePicker from '@/components/form/datePicker/index.vue'
import Area from '@/components/form/area/index.vue'
import { mainHeight } from '@/utils/layout'
import { useDictData } from '@/stores/dictData'
import { Search, RefreshLeft, Setting } from '@element-plus/icons-vue'
const emit = defineEmits(['selectChange', 'areaChange'])
const tableStore = inject('tableStore') as TableStore
const tableHeader = ref()
const datePickerRef = ref()
const dictData = useDictData()
const areaRef = ref()
const headerForm = ref()
const headerFormSecond = ref()
const timeAll = ref(true)
interface Props {
    datePicker?: boolean
    area?: boolean
    showSearch?: boolean
    nextFlag?: boolean //控制时间是否可以往后推
    theCurrentTime?: boolean //控制时间前3天展示上个月时间
    showReset?: boolean //是否显示重置按钮
    showExport?: boolean //导出控制
    showTimeAll?: boolean //控制时间是否显示
    dateLabel?: string //设置时间名称
    isStatisticData?: number | string // 0统计数据 1分钟数据
    showCustomColumn?: boolean // 列设置
}

const props = withDefaults(defineProps<Props>(), {
    datePicker: false,
    area: false,
    showSearch: true,
    nextFlag: false,
    theCurrentTime: false,
    showReset: true,
    showExport: false,
    showTimeAll: false,
    dateLabel: '统计日期',
    isStatisticData: 0,
    showCustomColumn: false
})
// 动态计算table高度
const resizeObserver = new ResizeObserver(entries => {
    for (const entry of entries) {
        handlerHeight()
        computedSearchRow()
    }
})
const showUnfoldButton = ref(false)
const headerFormSecondStyleOpen = {
    opacity: 1,
    height: 'auto',
    padding: '0 15px 13px 15px'
}
const headerFormSecondStyleClose = {
    opacity: 0,
    height: '0',
    padding: '0'
}

const onAreaChange = data => {
    emit('areaChange', { label: data.label })
}

watch(
    () => tableStore?.table.params.deptIndex,
    newVal => {
        setTimeout(() => {
            areaRef.value && areaRef.value.change()
        }, 0)
    }
)
watch(
    () => timeAll.value,
    newVal => {
        tableStore.timeAll = newVal
        setTimeout(() => {
            computedSearchRow()
        }, 500)
    }
)
let customColumnVisibleOnPress = false
const onCustomColumnMousedown = () => {
    const table = tableStore?.table?.ref as any
    if (!table) return
    customColumnVisibleOnPress = table.getCustomVisible?.() ?? !!table.reactData?.customStore?.visible
    if (table.reactData?.customStore) {
        table.reactData.customStore.activeBtn = true
    }
}
const openCustomColumn = () => {
    const table = tableStore?.table?.ref as any
    if (!table) return
    if (table.reactData?.customStore) {
        table.reactData.customStore.activeBtn = false
    }
    if (customColumnVisibleOnPress) {
        table?.closeCustom?.()
    } else {
        table?.openCustom?.()
    }
}
onMounted(() => {
    if (props.showCustomColumn && tableStore?.table) {
        tableStore.table.customColumnInHeader = true
    }
    timeAll.value = props.showTimeAll ? false : true
    if (props.datePicker && timeAll.value) {
        tableStore.table.params.searchBeginTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.startTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.endTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.timeFlag = datePickerRef.value.timeFlag
        tableStore.table.params.interval = datePickerRef.value.interval
    }
    if (props.area) {
        tableStore.table.params.deptIndex = dictData.state.area[0].id
    }
    nextTick(() => {
        resizeObserver.observe(tableHeader.value)
        setTimeout(() => {
            computedSearchRow()
        }, 500)
    })
})
onUnmounted(() => {
    resizeObserver.disconnect()
})

const handlerHeight = () => {
    if (tableStore && tableStore.table) {
        tableStore.table.publicHeight + tableHeader.value.offsetHeight + (tableStore.showPage ? 58 : 0) + 20
        tableStore.table.height = mainHeight(
            tableStore.table.publicHeight + tableHeader.value.offsetHeight + (tableStore.showPage ? 58 : 0) + 20
        ).height as string
    }
}
const computedSearchRow = () => {
    if (!headerForm.value?.$el) return
    // 清空headerFormSecond.value.$el下的元素
    while (headerFormSecond.value.$el.firstChild) {
        headerForm.value.$el.appendChild(headerFormSecond.value.$el.firstChild)
    }
    // 获取第一行放了几个表单
    const elFormItem = headerForm.value.$el.querySelectorAll('.el-form-item')

    //  把第一行放不下的复制一份放到headerFormSecond.value.$el
    let width = 0
    for (let i = 0; i < elFormItem.length; i++) {
        width += elFormItem[i].offsetWidth + 32

        if (width > headerForm.value.$el.offsetWidth) {
            headerFormSecond.value.$el.appendChild(elFormItem[i])
        }
    }

    // 判断是否需要折叠
    if (headerFormSecond.value.$el.scrollHeight > 0) {
        showUnfoldButton.value = true
    } else {
        showUnfoldButton.value = false
    }
}

const showSelect = ref(false)
const showSelectChange = () => {
    showSelect.value = !showSelect.value
    emit('selectChange', showSelect.value)
}
const onComSearch = async () => {
    if (props.datePicker && timeAll.value) {
        tableStore.table.params.searchBeginTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.startTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.endTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.timeFlag = datePickerRef.value.timeFlag
        tableStore.table.params.interval = datePickerRef.value.interval
    }

    await tableStore.onTableAction('search', {})
}
const setDatePicker = (list: any) => {
    datePickerRef.value.setTimeOptions(list)
}
const onResetForm = () => {
    //时间重置成默认值
    datePickerRef.value?.setTheDate(3)

    if (props.showTimeAll) {
        timeAll.value = false
        delete tableStore.table.params.searchBeginTime
        delete tableStore.table.params.searchEndTime
        delete tableStore.table.params.startTime
        delete tableStore.table.params.endTime
        delete tableStore.table.params.timeFlag
        delete tableStore.table.params.interval
    }

    if (props.datePicker && timeAll.value) {
        tableStore.table.params.searchBeginTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.startTime = datePickerRef.value.timeValue[0]
        tableStore.table.params.endTime = datePickerRef.value.timeValue[1]
        tableStore.table.params.timeFlag = datePickerRef.value.timeFlag
        tableStore.table.params.interval = datePickerRef.value.interval
    }

    tableStore.onTableAction('reset', {})
}
const setTheDate = (val: any) => {
    datePickerRef.value.setTheDate(val)
}
// 导出
const onExport = () => {
    tableStore.onTableAction('export', { showAllFlag: true })
}

defineExpose({
    onComSearch,
    areaRef,
    setDatePicker,
    setTheDate,
    datePickerRef,
    showSelectChange,
    showSelect,
    computedSearchRow,
    onExport
})
</script>

<style scoped lang="scss">
.cn-table-header {
    border: 1px solid var(--el-border-color);
}

.table-header {
    position: relative;
    overflow-x: auto;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    max-width: 100%;
    background-color: var(--ba-bg-color-overlay);

    border-bottom: none;
    padding: 13px 15px;
    font-size: 14px;
    overflow: hidden;

    .table-header-operate-text {
        margin-left: 6px;
    }
}

.table-com-search {
    box-sizing: border-box;
    width: 100%;
    max-width: 100%;
    background-color: var(--ba-bg-color-overlay);
    border: 1px solid var(--ba-border-color);
    border-bottom: none;
    padding: 13px 15px 20px 15px;
    font-size: 14px;
}

#header-form-second,
#header-form {
    // display: flex;
    // flex-wrap: wrap;
    transition: all 0.3s;
}

.mlr-12 {
    margin-left: 12px;
}

.mlr-12 + .el-button {
    margin-left: 12px;
}

.table-search {
    display: flex;
    margin-left: auto;

    .quick-search {
        width: auto;
    }
}

.table-search-button-group {
    display: flex;
    margin-left: 12px;
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-border-radius-base);
    overflow: hidden;

    button:focus,
    button:active {
        background-color: var(--ba-bg-color-overlay);
    }

    button:hover {
        background-color: var(--el-color-info-light-7);
    }

    .table-search-button-item {
        height: 30px;
        border: none;
        border-radius: 0;
    }

    .el-button + .el-button {
        margin: 0;
    }

    .right-border {
        border-right: 1px solid var(--el-border-color);
    }
}

html.dark {
    .table-search-button-group {
        button:focus,
        button:active {
            background-color: var(--el-color-info-dark-2);
        }

        button:hover {
            background-color: var(--el-color-info-light-7);
        }

        button {
            background-color: var(--ba-bg-color-overlay);

            el-icon {
                color: white !important;
            }
        }
    }
}

#header-form,
#header-form-second {
    :deep(.el-select) {
        --el-select-width: 220px;
    }

    :deep(.el-input) {
        --el-input-width: 220px;
    }
}
</style>
