<template>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" @close="close" v-bind="dialogBig" width="1400px">
        <div class="dialog-content">
            <el-tabs type="border-card" class="right-tabs" style="height: 100%">
                <el-tab-pane label="检测">
                    <!-- 全局设置菜单内容 -->
                    <div style="height: 295px">
                        <el-radio-group v-model="form.subType">
                            <el-radio
                                v-for="item in tabChildren"
                                :key="item"
                                :label="item.label"
                                :value="item.code"
                                border
                                style="margin: 0 0 10px 10px"
                            />
                            <!-- <el-radio v-for="item in tabChildren" :value="item.value" border>{{ item.label }}</el-radio> -->
                        </el-radio-group>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <el-tabs type="border-card" class="left-tabs" style="height: 100%">
                <el-tab-pane label="输出菜单">
                    <!-- 输出菜单内容 -->
                    <el-table
                        :data="tableData"
                        style="width: 100%"
                        :style="{ height: '295px', overflow: 'hidden' }"
                        :show-header="false"
                        :span-method="arraySpanMethod"
                        :cell-style="tableStyle.cellStyle"
                        :header-cell-style="{ textAlign: 'center', backgroundColor: '#003078', color: '#fff' }"
                        @cell-click="handleRowClick"
                        :key="key"
                    >
                        <el-table-column prop="name" label="相别" width="60" align="center" />
                        <el-table-column prop="frequency" label="电压/电流" align="center" width="60" />
                        <el-table-column prop="L1" label="值" width="180" align="center">
                            <template #default="{ row, $index }">
                                <span>
                                    {{ row.type === 'V' ? '电压' : '电流' }}{{ form.channelList[$index].famp
                                    }}{{ valueCode == 'Absolute' ? (row.type === 'V' ? 'V' : 'A') : '%' }} 相角{{
                                        form.channelList[$index].fphase
                                    }}°
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="85">
                            <template #default="{ row, $index }">
                                <el-button
                                    type="primary"
                                    v-if="$index != 4"
                                    link
                                    :icon="CopyDocument"
                                    @click="copyRow($index)"
                                >
                                    复制
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template #default="{ row, $index }">
                                <el-checkbox-button
                                    v-model="form.channelList[$index].channelFlag"
                                    label="通道使能"
                                    size="small"
                                />
                                <el-checkbox-button
                                    v-model="form.channelList[$index].harmFlag"
                                    label="谐波使能"
                                    size="small"
                                />
                                <el-checkbox-button
                                    v-model="form.channelList[$index].inHarmFlag"
                                    label="间谐波使能"
                                    size="small"
                                />
                                <el-checkbox-button
                                    v-model="form.channelList[$index].flickerFlag"
                                    label="闪变使能"
                                    size="small"
                                />
                                <el-checkbox-button
                                    v-model="form.channelList[$index].dipFlag"
                                    label="暂态使能"
                                    size="small"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <el-tabs type="border-card" class="right-tabs" style="height: 100%">
                <el-tab-pane label="全局设置菜单">
                    <!-- 全局设置菜单内容 -->
                    <div style="height: 295px">
                        <div class="form-item-container">
                            <el-form-item label="频率：" prop="name">
                                <div class="input-label-container">
                                    <el-input
                                        type="number"
                                        @mousewheel.native.prevent
                                        style="width: 100px"
                                        v-model="form.ffreq"
                                    />
                                    <label>Hz</label>
                                </div>
                            </el-form-item>
                        </div>
                        <div class="button-label-container">
                            <label>参考设定值列表:</label>
                            <el-button type="primary" :icon="EditPen" @click="openDialog">编辑</el-button>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div style="margin-top: 10px">
            <el-tabs type="border-card" class="custom-tabs">
                <el-tab-pane label="电压/电流编辑" v-if="childForm[0].channelFlag || childForm[1].channelFlag">
                    <TestScriptVolCurTab :childForm="childForm" />
                </el-tab-pane>
                <el-tab-pane label="谐波编辑" v-if="childForm[0].harmFlag || childForm[1].harmFlag">
                    <TestScriptHarmTab :childForm="childForm" />
                </el-tab-pane>
                <el-tab-pane label="间谐波编辑" v-if="childForm[0].inHarmFlag || childForm[1].inHarmFlag">
                    <TestScriptInHarmTab :childForm="childForm" />
                </el-tab-pane>
                <el-tab-pane label="闪变编辑" v-if="childForm[0].flickerFlag || childForm[1].flickerFlag">
                    <TestScriptFlickerTab :childForm="childForm" />
                </el-tab-pane>
                <el-tab-pane label="暂态编辑" v-if="childForm[0].dipFlag || childForm[1].dipFlag">
                    <TestScriptDipTab :childForm="childForm" />
                </el-tab-pane>
            </el-tabs>
        </div>

        <SetValueTable ref="setValueTableRef" />

        <template #footer>
            <div>
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { dialogBig } from '@/utils/elementBind'
import { onMounted, reactive, ref } from 'vue'
import SetValueTable from '@/views/machine/testScript/components/setValueTable.vue'
import { EditPen, ArrowDown, Bottom, CopyDocument } from '@element-plus/icons-vue'
import { type TabsInstance } from 'element-plus'
import TestScriptVolCurTab from '@/views/machine/testScript/components/testScriptVolCurTab.vue'
import TestScriptHarmTab from '@/views/machine/testScript/components/testScriptHarmTab.vue'
import TestScriptInHarmTab from '@/views/machine/testScript/components/testScriptInHarmTab.vue'
import TestScriptFlickerTab from '@/views/machine/testScript/components/testScriptFlickerTab.vue'
import TestScriptDipTab from '@/views/machine/testScript/components/testScriptDipTab.vue'
import { useDictStore } from '@/stores/modules/dict'
import { addScriptDtls, scriptDtlsCheckDataList } from '@/api/device/testScript'
import scriptForm from './scriptForm'

const emit = defineEmits(['addTab', 'close'])
const dictStore = useDictStore()
const props = defineProps({
    options: {
        type: [Array, Object],
        required: true
    },
    activeName: {
        type: String,
        required: true
    },
    childActiveName: {
        type: String,
        required: true
    },
    formContent: {
        type: [Object, Array],
        required: true
    }
})
const key = ref(0)
// let  valueType
const form: any = ref(JSON.parse(JSON.stringify(scriptForm)))
const childForm: any = ref([])
const ScriptValueType = ref('')
const setValueTableRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref()
const valueCode = ref('') //Absolute绝对值

const tableData = [
    { name: 'L1', frequency: 'Ua', type: 'V', electricity: 0, fphase: 0, sort: 0 },
    { name: 'L1', frequency: 'Ia', type: 'I', electricity: 0, fphase: 0, sort: 0 },
    { name: 'L2', frequency: 'Ub', type: 'V', electricity: 0, fphase: 0, sort: 1 },
    { name: 'L2', frequency: 'Ib', type: 'I', electricity: 0, fphase: 0, sort: 1 },
    { name: 'L3', frequency: 'Uc', type: 'V', electricity: 0, fphase: 0, sort: 2 },
    { name: 'L3', frequency: 'Ic', type: 'I', electricity: 0, fphase: 0, sort: 2 }
]

const tabChildren: any = ref([])
// 定义 span-method 逻辑
const arraySpanMethod = ({ rowIndex, columnIndex }: { rowIndex: number; columnIndex: number }) => {
    if (columnIndex === 0 || columnIndex === 3) {
        // 第一列
        if (rowIndex % 2 === 0) {
            return {
                rowspan: 2,
                colspan: 1
            }
        } else {
            return {
                rowspan: 0,
                colspan: 0
            }
        }
    }
}
const selectedRow = ref('')
const tableStyle = {
    cellStyle: ({ row }: { row: any }) => {
        return row.name === selectedRow.value
            ? { backgroundColor: '#dcdcdc' } // 设置选中行的背景颜色
            : {}
    }
}
const handleRowClick = async (row: any, column: any) => {
    if (column.label == '相别') {
        childForm.value = []
        selectedRow.value = row.name
        childForm.value.push(form.value.channelList[row.sort * 2])
        childForm.value.push(form.value.channelList[row.sort * 2 + 1])
        console.log('🚀 ~ handleRowClick ~  childForm.value:', childForm.value)
    }

    // childForm.value = row
}

// 关闭弹窗
const close = () => {
    dialogVisible.value = false
    emit('close')
}

// 保存数据
const save = () => {
    let copyForm = handleHarmData()
    addScriptDtls({ ...copyForm, scriptId: props.formContent.id, scriptType: props.activeName }).then(res => {
        if (res.code === 'A0000') {
            ElMessage.success({
                message: dialogTitle.value == '新增检测项目信息' ? '添加检测脚本成功!' : '编辑检测脚本成功!',
                type: 'success'
            })
            dialogVisible.value = false
            emit('addTab', form.value)
        }
    })
    // emit('addTab', form.value)
}
//处理谐波数据
const handleHarmData = () => {
    let copyForm = JSON.parse(JSON.stringify(form.value))

    copyForm.channelList.forEach((channel: any) => {
        // 筛选出 famp 和 fphase 不同时为 0 的对象
        channel.harmList = channel.harmList.filter((item: any) => item.famp !== 0 || item.fphase !== 0)
        channel.inharmList = channel.inharmList.filter(
            (item: any) => item.inharm !== '' || item.famp !== 0 || item.fphase !== 0
        )
    })
    return copyForm
}

// 打开弹窗，可能是新增，也可能是编辑
const open = (sign: string, row: any) => {
    dialogVisible.value = true

    dialogTitle.value = sign === 'add' ? '新增检测项目信息' : '编辑检测项目信息'
    // 添加选择检测项目
    tabChildren.value = props.options.filter(item => item.value == props.activeName)[0].children || []
    // subType.value = tabChildren.value[0].code || ''
    if (sign == 'add') {
        form.value.subType = props.childActiveName == '' ? tabChildren.value[0].code || '' : props.childActiveName
    } else {
        form.value = setharmList(JSON.parse(JSON.stringify(row)))
    }
    handleRowClick({ name: 'L1', sort: 0 }, { label: '相别' })
    dictStore.getDictData('Script_Value_Type')
    valueCode.value = dictStore
        .getDictData('Script_Value_Type')
        .filter(item => item.id == props.formContent.valueType)[0].code
}

// 判断后台没有谐波，简谐波值 用于回显
const setharmList = (row: any) => {
    row.channelList.forEach((item: any) => {
        let harmList = []

        for (let i = 2; i < 51; i++) {
            let data = item.harmList.filter((harm: any) => harm.harm == i)
            if (data.length > 0) {
                harmList.push({ harm: i, famp: data[0].famp, fphase: data[0].fphase })
            } else {
                harmList.push({ harm: i, famp: 0, fphase: 0 })
            }
        }
        item.harmList = harmList

        if (item.inharmList.length == 0) {
            item.inharmList.push({ inharm: 0, famp: 0, fphase: 0 })
        }
    })

    return row
}
// 复制
const copyRow = (index: number) => {
    form.value.channelList[index + 2] = JSON.parse(JSON.stringify(form.value.channelList[index]))
    form.value.channelList[index + 3] = JSON.parse(JSON.stringify(form.value.channelList[index + 1]))
    form.value.channelList[index].channelType == 'Ua'
        ? (form.value.channelList[index + 2].channelType = 'Ub')
        : (form.value.channelList[index + 2].channelType = 'Uc')
    form.value.channelList[index + 1].channelType == 'Ia'
        ? (form.value.channelList[index + 3].channelType = 'Ib')
        : (form.value.channelList[index + 3].channelType = 'Ic')
    key.value += 1
    ElMessage.success({
        message: '复制成功!',
        type: 'success'
    })
}

// 打开 drawer(新增、编辑)
const openDialog = () => {
    let copyForm = JSON.parse(JSON.stringify(form.value))
    scriptDtlsCheckDataList({ ...copyForm, scriptId: props.formContent?.id, scriptType: props.activeName }).then(
        res => {}
    )
    // setValueTableRef.value?.open()
}

// 对外映射
defineExpose({ open })
</script>

<style scoped>
.dialog-content {
    display: flex;
    justify-content: flex-start;
    align-items: stretch;
    height: 100%;
}

.tabs-container {
    display: flex;
    flex-direction: row;
    height: 100%;
    width: 100%;
}

.left-tabs {
    width: 900px;
    margin: 0 10px; /* 可选：添加间距 */
}

.right-tabs {
    flex: 1;
}

.form-item-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    margin-bottom: 10px; /* 可选：添加间距 */
}

.button-label-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
}

.button-label-container label {
    margin-right: 10px; /* 按钮和文字之间的距离 */
}
.input-label-container {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
}

.input-label-container label {
    margin-left: 5px; /* 添加标签与输入框之间的间距 */
}
</style>
