<!-- components/MonitorPointTable.vue -->
<template>
    <div class="table-box">
        <ProTable
            ref="proTable"
            :pagination="false"
            :toolButton="false"
            :columns="columns"
            :data="tableData"
            :style="{ height: tableHeight + 'px', overflow: 'hidden' }"
        >
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
                <el-button
                    type="primary"
                    :icon="CirclePlus"
                    @click="openDialog('add')"
                >
                    新增
                </el-button>
                <el-button
                    v-auth.device="'delete'"
                    type="danger"
                    :icon="Delete"
                    plain
                    :disabled="!scope.isSelected"
                    @click="batchDelete(scope.selectedListIds)"
                >
                    删除
                </el-button>
            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
                <el-button
                    v-auth.device="'edit'"
                    type="primary"
                    link
                    :icon="EditPen"
                    :model-value="false"
                    @click="openDialog('edit', scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    v-auth.device="'delete'"
                    type="primary"
                    link
                    :icon="Delete"
                    @click="handleDelete(scope.row.id)"
                    :disabled="scope.row.resultType!=null"
                >
                   删除
                </el-button>
            </template>
        </ProTable>
    </div>
    <MonitorPopup @getParameter="getParameter" ref="monitorPopup" :DevFormContent="props.DevFormContent"/>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import ProTable from '@/components/ProTable/index.vue' // 假设 ProTable 是自定义组件
import { CirclePlus, Delete, EditPen } from '@element-plus/icons-vue'
import MonitorPopup from '@/views/machine/device/components/monitorPopup.vue'
import { type ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import { type Monitor } from '@/api/device/interface/monitor'
import { useDictStore } from '@/stores/modules/dict'
import { Device } from '@/api/device/interface/device'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义 props
const props = defineProps<{
    DevFormContent: Device.ResPqDev
    tableHeight?: number // 接收外部传入的高度
    selectOptions: Record<string, Device.SelectOption[]>
}>()

// ProTable 实例
const proTable = ref<ProTableInstance>()
const dictStore = useDictStore()
const monitorPopup = ref()
const tableData = ref<any[]>([])
const title_Type = ref('add')

// 表格配置项
const columns = reactive<ColumnProps<Monitor.ResPqMon>[]>([
    { type: 'selection', fixed: 'left', width: 70 },
    { type: 'index', fixed: 'left', width: 70, label: '序号' },
    {
        prop: 'name',
        label: '名称',
        width: 200
    },
    {
        prop: 'busbar',
        label: '母线名称',
        width: 200
    },
    {
        prop: 'num',
        label: '线路号',
        width: 200
    },
    {
        prop: 'pt',
        label: 'PT变比',
        width: 110
    },
    {
        prop: 'ct',
        label: 'CT变比',
        width: 130
    },
    {
        prop: 'connection',
        label: '接线方式',
        enum: dictStore.getDictData('Dev_Connect'),
        fieldNames: { label: 'name', value: 'id' },
        width: 130
    },
    {
        prop: 'statInterval',
        label: '统计间隔',
        width: 130
    },
    {
        prop: 'checkFlag',
        label: '是否参与检测',
        render: (scope: any) => {
            return scope.row.checkFlag === 1 ? '是' : '否'
        },
        width: 130
    },
    { prop: 'operation', label: '操作', fixed: 'right', width: 200 }
])

const emit = defineEmits(['get-parameter'])

const getParameter = (data: Monitor.ResPqMon) => {

    if (title_Type.value === 'edit') {
        // 编辑：替换已有的数据
        const index = tableData.value.findIndex(item => item.id === data.id)
        if (index > -1) {
            tableData.value = [...tableData.value.slice(0, index), data, ...tableData.value.slice(index + 1)]
        }
    } else {
        // 新增：追加数据
        tableData.value = [...tableData.value, data]
    }
    emit('get-parameter', tableData.value)
}

// 打开 drawer(新增、编辑)
const openDialog = (titleType: string, row: Partial<Monitor.ResPqMon> = {}) => {
    if (props.DevFormContent.devType == '' || props.DevFormContent.devType == undefined) {
        ElMessageBox.confirm('请先选择被检设备类型', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        return
    }
    // 新增时检查线路号是否全部被占用
    if (titleType === 'add') {
        if(props.DevFormContent.devChns == tableData.value.length){
            ElMessageBox.confirm(`线路号已全部被占用，无法新增监测点`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            return
        }

    }
    title_Type.value = titleType
    monitorPopup.value?.open(titleType, row, props.DevFormContent, tableData.value, props.selectOptions)
}

// 批量删除监测点台账
const batchDelete = (ids: string[]) => {
    ElMessageBox.confirm(`是否批量删除监测点?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        draggable: true
    }).then(async () => {
        tableData.value = tableData.value.filter(item => !ids.includes(item.id))
        proTable.value?.clearSelection()
        emit('get-parameter', tableData.value)
        ElMessage({
            type: 'success',
            message: `批量删除监测点成功!`
        })
    })
}

// 删除监测点台账
const handleDelete = (id: string) => {
    ElMessageBox.confirm(`是否删除监测点?`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        draggable: true
    }).then(async () => {
        tableData.value = tableData.value.filter(item => item.id !== id)
        proTable.value?.clearSelection()
        emit('get-parameter', tableData.value)
        ElMessage({
            type: 'success',
            message: `删除监测点成功!`
        })
    })
}

watch(
    () => props.DevFormContent.monitorList,
    newVal => {
        tableData.value = newVal || []
    },
    { immediate: true }
)
</script>