<template>
    <el-drawer
        :model-value="props.drawer"
        title="试运行"
        :before-close="handleClose"
    >
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="{ tableData }"
        :rules="rules"
        label-width="auto"
    >
        <el-table
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="name"
            default-expand-all
        >
            <el-table-column prop="name" label="入参名称">
                <template #default="{row}">
                    <span>{{ row.name }}</span>
                    <span v-if="row.required" style="color: #f56c6c; margin-left: 8px;">*</span>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="入参类型">
                <template #default="scope">
                    <el-tag>{{ scope.row.type }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="value" label="入参值">
                <template #default="{ row, column, $index }">
                    <el-form-item v-if="row.name === 'terminalId'"  label="" :prop="`tableData${row.propPath}value`" :rules="row.required ? [{ required: true, message: '请输入变量名', trigger: 'blur' }] : []">
                        <el-select v-model="row.value" style="width: 200px">
                            <el-option
                                v-for="item in terminalIdOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                
                    <el-form-item v-else-if="row.type !== 'object' && !row.type.includes('array')" label="" :prop="`tableData${row.propPath}value`" :rules="row.required ? [{ required: true, message: '请输入变量名', trigger: 'blur' }] : []">
                        <el-input v-if="row.type === 'string'" v-model="row.value" />
                        <el-input-number  v-if="row.type === 'number'" :controls="false" v-model="row.value" />
                        <el-switch v-if="row.type === 'boolean'" v-model="row.value" />
                    </el-form-item>
                    <el-form-item v-else-if="row.type !== 'object' && row.type.includes('array')" label="" :prop="`tableData${row.propPath}value`" :rules="row.required ? [{ required: true, message: '请输入变量名', trigger: 'blur' }] : []">
                        <el-input v-model="row.value" placeholder="请输入数组值，格式如：[1,2,3]" />
                    </el-form-item>
                </template>
            </el-table-column>
        </el-table>
    </el-form>
        <template #footer>
             <el-button @click="handleClose">关闭</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
        </template>
    </el-drawer>
</template>
<script setup>
import { ref, watch } from 'vue'
import { getStartNodeFormData, formatTableData } from '@/utils/flow'
// import { Plus, Minus } from '@element-plus/icons-vue'
import { flowExecuteTrial } from '@/api/device/flow'
import { emitter } from '@/utils/eventBus';
import { ElMessage } from 'element-plus';
import {listTerminal} from "@/api/device/terminal.js";

const props = defineProps({
    drawer: Boolean,
    flowId: String
})

const ruleFormRef = ref()
const rules = ref({});
const tableData = ref([])

const emits = defineEmits(['close', 'changeState'])

const handleClose = () => {
    ruleFormRef.value?.resetFields()
    emits('close')
}

watch(() => props.drawer,
    (newVal) => {
        if (newVal) {
            const data = getStartNodeFormData()
            tableData.value = data
            handleGetTerminalGroup()
        }
    }
)

const confirm = () => {
    lf.fitView()
    ruleFormRef.value.validate().then(async () => {
        const formData = formatTableData(tableData.value)
        const { nodes } = lf.getGraphData()
        nodes.forEach(item => {
            emitter.emit('contentChange', { id: item.id})
        })

        const flowData = JSON.stringify(lf.getGraphData())
        const { terminalId, ...runParams } = formData
        const res = await flowExecuteTrial({
            flowData,
            itemId: props.flowId,
            terminalId,
            runParams
        })
        if (res.code === 200) {
            emits('changeState', {
                type: 'testRunning',
                instId: res.msg
            })
        } else {
            ElMessage.error(res.msg)
        }
    })
    .catch(() => {})
}

const terminalIdOptions = ref([])

/** 获取设备终端列表 */
const handleGetTerminalGroup = async (row) => {
    const res = await listTerminal({ pageNum: 1, pageSize: 1000 })
    if (res.code === 200) {
        terminalIdOptions.value = res.rows?.map((item) => {
            return {
                label: `${item.name}(${item.host}:${item.port})`,
                value: item.id
            }
        })
    }
}

</script>
