<template>
  <el-drawer v-model="props.drawer" title="执行" :before-close="handleClose">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="{ formData }"
      :rules="rules"
      label-width="auto"
    >
    <el-form-item label="执行机器人" prop="formData.robotId" :rules="[{ required: true, message: '请选择在线机器人', trigger: 'change' }]">
        <el-select v-model="formData.robotId" style="width: 260px" placeholder="请选择在线机器人">
            <el-option
                v-for="item in terminalIdOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
    </el-form-item>
      <el-table
        :data="formData.tableData"
        :border="parentBorder"
        :preserve-expanded-content="preserveExpanded"
        default-expand-all
        style="width: 100%"
      >
        <el-table-column type="expand">
            <template #default="{ row: pRow, $index: pIndex }">
                <el-table
                    v-if="pRow.config.length > 0"
                    :data="pRow.config"
                    style="width: 100%"
                    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="{ row }">
                        <el-tag>{{ 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.type !== 'object' && !row.type.includes('array')" label="" :prop="`formData.tableData.${pIndex}.config${row.propPath}value`" :rules="row.required ? [{ required: true, message: '请输入', trigger: 'blur' }] : []">
                                <el-input v-if="row.type === 'string'" v-model="row.value" :disabled="row.name === 'schemeId'" />
                                <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="`formData.tableData.${pIndex}.config${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>
          </template>
        </el-table-column>
        <el-table-column label="方案名称" prop="itemName" />
      </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, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { addValueProperty, formatTableData } from "@/utils/flow";
import { getRobotList } from '@/api/inspection/robot'
import { getExecuteRunParams, projectExecute } from "@/api/vi/project.js"

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

const emits = defineEmits(["close"]);

const ruleFormRef = ref();
const rules = ref({});

const formData = ref({
    robotId: '',
    tableData: []
})

const terminalIdOptions = ref([]);

/** 获取设备终端列表 */
const handleGetTerminalGroup = async (row) => {
  const res = await getRobotList({ pageNum: 1, pageSize: 1000, connectStatus: '1' });
  if (res.code === 200) {
    terminalIdOptions.value = res.rows?.map((item) => {
      return {
        label: `${item.robotName || item.robotId} (${item.robotId})`,
        value: item.robotId,
      };
    });
  }
};

const getProjectParams = async () => {
  const res = await getExecuteRunParams(props.projectId);
  if (res.code === 200) {
    const data = parseConfig(res.data)
    console.log('data', data)
    formData.value.tableData = data
    handleGetTerminalGroup();
  }
};

const parseConfig = (arr) => {
  arr.forEach(item => {
      if (item.config) {
        item.config = addValueProperty(JSON.parse(item.config), item.schemeId)
      } else {
        item.config = []
      }
  })
  return arr
}

const confirm = () => {
  ruleFormRef.value
    .validate()
    .then(async () => {
      const runParams = {}
      formData.value.tableData.forEach(item => {
        const data = formatTableData(item.config)
        runParams[item.itemId] = data
      })
      const res = await projectExecute({ runParams, projectId: props.projectId, robotId: formData.value.robotId })
      if (res.code === 200) {
        ruleFormRef.value.resetFields();
        ElMessage.success('执行成功')
        emits("close");
      } else {
        ElMessage.success(res.msg)
      }
    })
    .catch((err) => {
      console.log(err);
    });
}

const handleClose = () => {
  ruleFormRef.value.resetFields();
  emits("close");
};

watch(
  () => props.drawer,
  (newVal) => {
    if (newVal) {
      getProjectParams()
    }
  }
);
</script>
