<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="机器人IP" prop="formData.terminalId"  :rules="[{ required: true, message: '请输入', trigger: 'blur' }]">
        <el-select v-model="formData.terminalId" 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-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" />
                                <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>
                        </template>
                    </el-table-column>
                </el-table>
          </template>
        </el-table-column>
        <el-table-column label="流程ID" prop="itemId" show-overflow-tooltip/>
        <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 { addValueProperty, formatTableData } from "@/utils/flow";
import { emitter } from "@/utils/eventBus";
import { ElMessage } from "element-plus";
import { listTerminal, getFlowParamsApi } from "@/api/device/terminal.js";
import { taskExecute } from "@/api/test/config"

const props = defineProps({
  drawer: Boolean,
  currentRow: Object,
});

const parentBorder = ref(false);
const preserveExpanded = ref(false);

const ruleFormRef = ref();
const rules = ref({});
const formData = ref({
    terminalId: '',
    tableData: []
})

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

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

const getFlowParams = async () => {
  const res = await getFlowParamsApi(props.currentRow.id);
  if (res.code === 200) {
    const data = parseConfig(res.rows)
    formData.value.tableData = data
    handleGetTerminalGroup();
  }
};

const parseConfig = (arr) => {
    arr.forEach(item => {
        if (item.config) {
            item.config = addValueProperty(JSON.parse(item.config))
        } 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 taskExecute({ runParams, taskId: props.currentRow.id, terminalId: formData.value.terminalId })
      if (res.code === 200) {
        ruleFormRef.value.resetFields();
        ElMessage.success('执行成功')
        emits("close");
      } else {
        ElMessage.success(res.msg)
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

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,
      };
    });
  }
};


watch(
  () => props.drawer,
  (newVal) => {
    if (newVal) {
      getFlowParams()
    }
  }
);

onUnmounted(() => {
  emitter.off("contentChange");
});
</script>
