<template>
    <el-dialog
        :append-to-body="appendToBody"
        class="dialog"
        title="数据查询"
        :model-value="visible"
        @close="close"
        v-bind="dialogBig"
        :draggable="false"
        width="1400px"
    >
        <div class="data-check-dialog">
            <div>
                <el-form :model="formContent" label-width="auto" class="form-three">
                    <el-form-item label="误差体系">
                        <el-select
                            :disabled="checkStore.showDetailType === 2 || checkStore.showDetailType === 0"
                            v-model="formContent.errorSysId"
                            placeholder="请选择误差体系"
                            autocomplete="off"
                        >
                            <el-option
                                v-for="option in pqErrorList"
                                :key="option.id"
                                :label="option.name"
                                :value="option.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据原则">
                        <el-input v-model="formContent.dataRule" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="设备名称">
                        <el-input v-model="formContent.deviceName" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="通道号">
                        <el-select v-model="formContent.chnNum" @change="getResults" :disabled="sourceKey == 1">
                            <el-option v-for="item in chnList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="检测次数" :disabled="sourceKey == 1">
                        <el-select v-model="formContent.num" clearable @change="getResults">
                            <el-option
                                v-for="item in chnMapList[formContent.chnNum]"
                                :key="item"
                                :label="item"
                                :value="item"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="checkStore.showDetailType === 1">
                        <el-button type="primary" :icon="Postcard">报告生成</el-button>
                    </el-form-item>
                    <el-form-item v-if="checkStore.showDetailType === 0">
                        <el-button type="primary" :icon="Histogram">重新计算</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="data-check-body">
                <div class="content-left-tree" v-if="sourceKey == 2">
                    <el-tree
                        style="width: 200px"
                        :data="scriptData"
                        :props="defaultProps"
                        highlight-current
                        node-key="id"
                        ref="treeRef"
                        @node-click="handleNodeClick"
                    />
                </div>
                <div class="content-right">
                    <div class="content-right-title">
                        <div style="width: 840px">
                            <span class="content-right-title-text">当前检测项目：</span>
                            <span style="color: var(--el-color-primary)">{{ rowList.scriptName }}</span>
                        </div>
                        <el-form-item
                            style="margin-left: 280px; margin-bottom: 0px !important; width: 280px"
                            label="测试项"
                        >
                            <el-select v-model="currentCheckItem">
                                <el-option
                                    v-for="item in tesList"
                                    :key="item"
                                    :label="item.replace(/\.0$/, '')"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div class="content-right-Tabs">
                        <el-tabs type="border-card" v-model="activeTab">
                            <el-tab-pane label="检测结果" name="resultTab">
                                <CompareDataCheckResultTable
                                    :tableData="currentCheckResultData"
                                    :currentCheckItem="currentCheckItem"
                                    :currentScriptTypeName="currentScriptTypeName"
                                    v-if="activeTab === 'resultTab'"
                                />
                            </el-tab-pane>
                            <el-tab-pane label="原始数据" name="rawDataTab">
                                <CompareDataCheckRawDataTable
                                    v-if="activeTab === 'rawDataTab'"
                                    :tableData="currentRawTableData"
                                    :currentCheckItem="currentCheckItem"
                                    :currentScriptTypeName="currentScriptTypeName"
                                />
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script setup lang="ts">
import { dialogBig } from '@/utils/elementBind'
import { reactive, ref, watch, computed } from 'vue'
import CompareDataCheckResultTable from './compareDataCheckResultTable.vue'
import CompareDataCheckRawDataTable from './compareDataCheckRawDataTable.vue'
import { CheckData } from '@/api/check/interface'
import { useCheckStore } from '@/stores/modules/check'
import { Histogram, Postcard } from '@element-plus/icons-vue'
import { getPqErrSysList } from '@/api/plan/plan'
import { useModeStore } from '@/stores/modules/mode' // 引入模式 store
import { useDictStore } from '@/stores/modules/dict'
import { getContrastFormContent, getContrastResult, getBigTestItem } from '@/api/check/test'

const { appendToBody } = withDefaults(
    defineProps<{
        appendToBody: boolean
    }>(),
    { appendToBody: true }
)

const checkStore = useCheckStore()
const modeStore = useModeStore()
const dictStore = useDictStore()
const visible = ref(false)
const treeRef = ref()

const pqErrorList = reactive<{ id: string; name: string }[]>([])
const activeTab = ref('resultTab')
const currentCheckItem = ref<any>()
const rowList: any = ref([])
let scriptType: string | null = null

const defaultProps = {
    children: 'children',
    label: 'scriptName'
}

const chnMapList: any = ref({})

// 表单数据
const formContent = reactive<CheckData.DataCheck>({
    scriptName: '',
    errorSysId: '',
    dataRule: '',
    deviceName: '',
    chnNum: '',
    deviceId: '',
    num: ''
})
const sourceKey = ref(1) //1:正式检测进入页面 2:检测数据查询进入

// 通道下拉列表
const chnList: any = ref([])

// 当前检测项目名称
const currentScriptTypeName = ref('')
// 检测结果表格数据
const checkResultData = ref<CheckData.CheckResult[]>([])
// 检测脚本配置数据
const scriptData = ref<CheckData.ScriptItem[]>([])
// 原始数据表格数据
const rawTableData = ref<CheckData.RawDataItem[]>([])
const tesList: any = ref([])
// 检测结果
const currentCheckResultData = computed(() => {
    const data = checkResultData.value[currentCheckItem.value]
    return Array.isArray(data) ? data : []
})
const currentRawTableData = computed(() => {
    const data = rawTableData.value[currentCheckItem.value]
    return Array.isArray(data) ? data : []
})

const open = async (row: any, chnNum: string, deviceId: string | null, source: number) => {
    rowList.value = {}
    formContent.deviceId = deviceId || ''
    formContent.chnNum = chnNum
    sourceKey.value = source
    if (source == 1) {
        // 正式检测进入页面
        rowList.value = row
    } else if (source == 2) {
        // 检测数据查询进入
        await initScriptData(row)
    }
    visible.value = true

    scriptType = null

    formContent.errorSysId = checkStore.plan.errorSysId
    pqErrorList.length = 0
    // 获取误差体系
    let { data: resPqErrorList } = await getPqErrSysList()
    Object.assign(pqErrorList, resPqErrorList)
    // 获取基本信息
    await getBasicInformation()
}
// 查询大项树
const initScriptData = async (row: any) => {
    const pattern = dictStore.getDictData('Pattern').find(item => item.name === modeStore.currentMode)?.id ?? ''

    let response: any = await getBigTestItem({
        reCheckType: checkStore.reCheckType,
        planId: checkStore.plan.id,
        devIds: checkStore.devices.map(item => item.deviceId),
        patternId: pattern
    })
    // 格式化脚本数据
    let temp = response.data.map((item: any) => {
        return {
            ...item,
            scriptName: item.scriptName
        }
    })
    rowList.value.scriptName = temp[0].scriptName
    rowList.value.scriptType = temp[0].id
    // 保存脚本数据并设置总数
    scriptData.value = temp
    setTimeout(() => {
        treeRef.value?.setCurrentKey(temp[0].id)
    }, 0)
}
//获取基本信息
const getBasicInformation = async () => {
    getContrastFormContent({
        planId: checkStore.plan.id,
        scriptType: rowList.value.scriptType,
        deviceId: formContent.deviceId,
        chnNum: formContent.chnNum,
        num: formContent.num == '' ? null : parseInt(formContent.num)
    }).then((res: any) => {
        formContent.dataRule = res.data.dataRule
        formContent.deviceName = res.data.deviceName
        formContent.errorSysId = res.data.errorSysId
        chnMapList.value = res.data.chnMap
        formContent.num = res.data.checkNum
        let chnMap: string[] = []
        for (let key in res.data.chnMap) {
            chnMap.push(key)
        }
        chnList.value = chnMap
        formContent.chnNum = formContent.chnNum == null ? chnList.value[0] : formContent.chnNum
        // 查询表格数据
        getResults()
    })
}

// 左边树变化
const handleNodeClick = (data: any) => {
    rowList.value.scriptName = data.scriptName
    rowList.value.scriptType = data.id
    getResults()
}
// 获取结果
const getResults = async () => {
    checkResultData.value = []
    rawTableData.value = []

    getContrastResult({
        planId: checkStore.plan.id,
        scriptType: rowList.value.scriptType,
        deviceId: formContent.deviceId,
        chnNum: formContent.chnNum,
        num: formContent.num == '' ? null : formContent.num
    }).then((res: any) => {
        let list: string[] = []
        for (let key in res.data.resultMap) {
            list.push(key)
        }
        currentCheckItem.value = list[0]
        tesList.value = list
        checkResultData.value = res.data.resultMap
        rawTableData.value = res.data.rawDataMap
    })
}

const close = () => {
    visible.value = false
  formContent.num=''
    // 可以在这里添加其他清理逻辑
}

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.dialog {
    display: flex;
    flex-direction: column;

    .data-check-dialog {
        display: flex;
        flex-direction: column;

        .data-check-head {
            display: flex;
            flex-direction: row;
            width: 100%;
        }

        .data-check-body {
            height: 500px;
            width: 100%;
            display: flex;
            flex-direction: row;

            .content-left-tree {
                width: 18%;
                display: flex;
                flex-direction: column;
                align-items: center;
                max-height: 495px;

                padding: 10px 0.5% 0px 0.5%;
                border: 1px solid #ccc;
                overflow-y: auto;
                overflow-x: auto;
                margin-right: 10px;
                .content-tree {
                    width: 100%;
                    height: 100%;
                    margin-top: 10px;

                    .custom-tree-node {
                        overflow-x: hidden !important;
                        white-space: nowrap !important;
                        text-overflow: ellipsis !important;
                    }
                }
            }

            .content-right {
                width: 82%;

                flex: 1;

                .content-right-title {
                    display: flex;
                    padding: 10px 0;
                    margin-top: 0px;
                    line-height: 1.5;

                    .content-right-title-text {
                        font-size: 14px;
                        font-weight: bold;
                    }
                }
            }

            .content-right-Tabs {
                box-sizing: border-box;
                margin-top: 10px;
                margin-bottom: 10px;
                display: flex;
                .el-tabs {
                    width: 100%;
                }
            }
            .content-left {
                height: 100%;
                border: 1px solid #e0e0e0;
                padding: 10px;
                margin-right: 10px;
                height: 410px;
                overflow-y: auto;
            }
        }
    }
}
:deep(.el-tabs--border-card > .el-tabs__content) {
    height: 367px;
}
</style>
