<template>
    <div id="previewDataset">
        <info-dialog
            :options="options"
            @closeDialog="closeDialog"
        >
            <template
                v-if="props.isCustomTitle"
                #title
            >
                <slot name="title" />
            </template>
            <el-container>
                <el-main>
                    <infoTable
                        :key="updateKey"
                        :columns="columns"
                        :list="list"
                        :options="tableOption"
                    />
                </el-main>
                <el-footer height="22px">
                    <span class="timer">{{ $t('alreadyWaiting') }} {{ formatSeconds(count) }}</span>
                </el-footer>
            </el-container>
        </info-dialog>
        <errorList
            ref="errorRef"
            :errorData="errorData"
        />
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onUnmounted, PropType, computed } from 'vue'
import infoDialog from '../../../components/infoDialog/index.vue'
import infoTable from '../../../components/table/table.vue'
import { serverApi, globalGetDate, ObjectInterface, __getItem } from '../../../script/index'
import errorList from './errorList.vue'
import dataset from '../api/table/table'

const props = defineProps({
    schemaColumnsSort: {
        type: Object as PropType<ObjectInterface>,
        default: () => {}
    }, // 传入schema,按照schema字段顺序显示预览字段顺序
    apiCancel: {
        type: String,
        default: 'analyzeCancel'
    },
    apiInit: {
        type: String,
        default: 'previewinit'
    },
    apiRes: {
        type: String,
        default: 'previewresult'
    },
    secondTitle: {
        type: String,
        default: ''
    },
    isCustomTitle: {
        type: Boolean,
        default: false
    }
})
// dialog
const options = reactive({
    title: 'previewDataset',
    secondTitle: props.secondTitle,
    isCustomTitle: props.isCustomTitle,
    isShowDialog: false,
    width: '60%',
    modalClass: 'preview-dataset',
    clickModalClose: false,
    isShowBtn: false,
    dialogOperates: [
        {
            label: () => 'cancel',
            type: 'primary',
            plain: true,
            method: () => {
                closeDialog()
            }
        }, {
            label: () => 'terminateQuery',
            type: 'primary',
            plain: true,
            show: () => !useStarRocks.value,
            disabled: () => {
                return termination.value || !initResult.statementId
            },
            method: () => {
                analyzeCancel()
            }
        }, {
            label: () => 'refresh',
            type: 'primary',
            plain: true,
            disabled: () => {
                return !termination.value
            },
            method: () => {
                previewinit(datasetRow)
            }
        }
    ]
})
// table
const tableOption = reactive({
    rowKey: 'id',
    i18n: true,
    // height: '445px',
    loading: {
        isLoading: false
    },
    isHideSet: true,
    index: false
})
let columns = reactive([] as any[])
let list = reactive([] as any[])
// 错误信息
const errorRef = ref()
let errorData = reactive({})
// 当前行dataset信息
let datasetRow = reactive({})
// 计数参数
const termination = ref(true)
const count = ref(666)
const retryTimes = ref(0)
const updateKey = ref(0)
let countTimer:any
let queryTimer:any
// 接口参数
let initResult:ObjectInterface = reactive({})
// methods
const closeDialog = () => {
    // analyzeCancel()
    clearTimer()
    options.isShowDialog = false
}
// 终止查询
const analyzeCancel = async () => {
    try {
        if (!initResult.statementId) {
            return false
        }
        serverApi({
            params: initResult,
            interface: dataset[props.apiCancel],
            success: (res: ObjectInterface) => {
                showError(res)
            }
        })
    } catch (err: any) {
        showError(err)
    }
}
// 请求错误
const showError = (error: any) => {
    clearTimer()
    const data = error.response?.data || error.data?.content
    if (data.errorlog) {
        // 展示错误信息
        errorRef.value.showDialog()
        Object.assign(errorData, { errorList: { error: data.errorlog } })
    }
}
const clearTimer = () => {
    clearInterval(countTimer)
    clearTimeout(queryTimer)
    tableOption.loading.isLoading = false
    termination.value = true
}
    const DBType = ref('')
    const storage = ref('')
    const useStarRocks = computed(() => {
        const serveConfig = __getItem('serveConfig')
        const defaultType = ['MySQL', 'Oracle', 'PostgreSQL', 'Greenplum', 'SQLServer', 'ClickHouse', 'Presto', 'HIVE', 'SearchOne', 'ElasticSearch', 'S3A', 'MINIO', 'STARROCKS']
        // const isStarRocks = storage.value === 'STARROCKS' && DBType.value === 'STARROCKS'
        return serveConfig.useStarRocks && defaultType.includes(DBType.value)
    })
    const previewStarrocks = (params) => {
        serverApi({
            params,
            // loading: tableOption.loading,
            interface: dataset.previewStarrocks,
            success: (data: any) => {
                if (Array.isArray(data)) {
                    list.push(...data)
                    if (list.length > 0) {
                        for (let value of Object.keys(list[0])) {
                            columns.push({
                                minWidth: (value.length * 12 + 20),
                                prop: value,
                                label: value
                            })
                        }
                    }
                    // updateKey.value = Math.random()
                    clearTimer()
                }
            },
            error: (error: any) => {
                clearTimer()
            }
        })
    }
const previewinit = async (row: ObjectInterface) => {
    datasetRow = row
    options.isShowDialog = true
    !props.secondTitle && (options.secondTitle = row.name)
    // 定时器清空
    clearTimer()
    list.splice(0)
    columns.splice(0)
    // 请求计时
    count.value = 0
    termination.value = false
    tableOption.loading.isLoading = true
    countTimer = setInterval(() => {
        count.value++
    }, 1000)
    DBType.value = row.storageConfigurations?.DBType || ''
    storage.value = row.storage || ''
    let params = { id: row.id, rows: 50 }
    try {
        if (DBType && useStarRocks.value) {
            previewStarrocks(params)
            return
        }
        await serverApi({
            params,
            interface: dataset[props.apiInit],
            success: (data: ObjectInterface) => {
                Object.assign(initResult, data)
                // result
                retryTimes.value = 0
                !termination.value && previewresult(params.id, initResult)
            },
            error: (error: any) => {
                clearTimer()
            }
        })
    } catch (error: any) {
        showError(error)
    }
}
const previewresult = (id: string, initResult: ObjectInterface) => {
    let params = { id, retryTimes: retryTimes.value, ...initResult }
    queryTimer = setTimeout(async () => {
        try {
            serverApi({
                params,
                interface: dataset[props.apiRes],
                errTips: false,
                // eslint-disable-next-line complexity
                success: (data: ObjectInterface) => {
                    if (data.statement === 'available' || data.statement === 'error' || data.statement === 'cancelled') {
                        // 数据列
                        Object.assign(list, data.content)
                        if (props.schemaColumnsSort?.fields?.length > 0) {
                            columns = props.schemaColumnsSort.fields.map(item => {
                                let name = item.alias || item.name
                                return {
                                    minWidth: ((name.length + 6) * 12 + 20),
                                    prop: name,
                                    label: `${$t('name')}：${item.name}`,
                                    columns: [
                                        {
                                            minWidth: ((item?.alias?.length || 0 + 6) * 12 + 20),
                                            prop: name,
                                            label: `${$t('alias')}：${item?.alias || ''}`,
                                            columns: [
                                                {
                                                    minWidth: ((item?.description?.length || 10 + 6) * 12 + 20),
                                                    prop: name,
                                                    label: `${$t('description')}：${item?.description || ''}`
                                                }
                                            ]
                                        }
                                    ]
                                }
                            })
                        } else {
                            if (list.length > 0) {
                                for (let value of Object.keys(list[0])) {
                                    columns.push({
                                        minWidth: (value.length * 12 + 20),
                                        prop: value,
                                        label: value
                                    })
                                }
                            }
                        }
                        // updateKey.value = Math.random()
                        clearTimer()
                    } else {
                        // 等数据回来之后再轮询接口
                        retryTimes.value++
                        previewresult(id, initResult)
                    }
                },
                error: (error: any) => {
                    showError(error)
                }
            })
        } catch (error: any) {
            showError(error)
        }
    }, 2 * 1000)
}
const formatSeconds = (value: number) => {
    let dur = globalGetDate.dur(value * 1000)
    return `${dur.hours()}${$t('hour')}${dur.minutes()}${$t('minute')}${dur.seconds()}${$t('second')}`
}
// methods end---
onUnmounted(() => {
    // analyzeCancel()
    clearTimer()
})
defineExpose({
    previewinit
})

</script>
<style lang="scss" scoped>
.tableListBtn {
    margin-top: -15px;
    :deep(.is-group) {
        th.el-table__cell {
            padding: 0;
        }
    }
}
.timer {
    color: var(--info-primary-color);
}
</style>
<style lang="scss">
.preview-dataset {
    .el-dialog__body {
        display: flex;
        .info-table {
            min-height: 320px;
        }
    }
}
</style>
