<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogOpen"
    width="1000px"
    :close-on-click-modal="false"
    append-to-body
    @opened="initData"
    @close="handleCancel"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="130px">
      <el-row>
        <el-form-item label="数据生成名称" prop="dataGenName">
          <el-input v-model="formData.dataGenName" placeholder="请输入数据生成名称" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="数据生成模型" prop="modelId">
          <el-select
            v-model="formData.modelId"
            placeholder="请选择数据生成模型"
            @change="onModelChange"
          >
            <el-option
              v-for="item in faultPhysicalOptions"
              :key="item.modelId"
              :label="item.modelName"
              :value="item.modelId"
            />
          </el-select>
        </el-form-item>
      </el-row>
        <el-form-item v-if="formData.modelId" label="模型参数">
            <dynamic-parameter-form  :config-data="initialData" @submit="handleSubmitDataList" />
        </el-form-item>
      <el-row>
        <el-form-item v-if="formData.modelType === '2'" label="数据生成名称" prop="dataGenName">
          <el-input v-model="formData.newFileName" placeholder="请输入数据生成名称" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item v-if="formData.modelType === '2'" label="数据生成目录" prop="dataGenName">
          <el-input v-model="formData.outputPath" placeholder="数据生成目录" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="formData.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间"
          />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="formData.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间"
          />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="说明" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入说明内容"
            rows="3"
          />
        </el-form-item>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addPhyModel, updatePhyModel } from "@/api/dataGen/phyModel";
import { getDataOptions } from "@/api/data/data";
import { getFaultPhysicalOptions } from "@/api/model/faultPhysical";
import {getFaultPhysical} from "@/api/model/faultPhysical";
import DynamicParameterForm from '@/views/dataGen/DynamicParameterForm.vue'
export default {
  components:{
    DynamicParameterForm
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    dataInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      initialData:[],
      modelDataParams: [], // 视图层显示的参数组数组
      dataOptions: [],
      faultPhysicalOptions: [],
      formData: {
        outputPath:null,
        newFileName:null,
        dataGenName: null,
        modelId: null,
        modelType: null,
        dataId: null,
        startTime: null,
        endTime: null,
        remark: null,
        modelPath: null,
        modelName:null,
        postApiData:[]
      },
      rules: {
        dataGenName: [{ required: true, message: "请输入数据生成名称", trigger: "blur" }],
        modelId: [{ required: true, message: "请选择数据生成模型", trigger: "blur" }]
      },
      dialogOpen: false
    };
  },
  model: {
    prop: "value",
    event: "input"
  },
  computed: {
    title() {
      return this.dataInfo?.id ? "修改物理模型数据生成" : "新增物理模型数据生成";
    }
  },
  watch: {
    value(newVal) {
      this.dialogOpen = newVal;
      if (newVal && this.dataInfo) {
        this.initFormData();
      }
    }
  },
  methods: {
    //新增参数组
    openDialog(){},
    //初始化数据
    initData() {
      this.loadOptions();
      if (this.dataInfo) {
        this.initFormData();
      }
    },

    loadOptions() {
      // 加载基础数据选项
      getDataOptions().then(resp => {
        this.dataOptions = resp.data || [];
      });

      // 加载模型选项
      getFaultPhysicalOptions(0).then(resp => {
        this.faultPhysicalOptions = resp.data || [];
      });
    },

    initFormData() {
      // 初始化表单数据
      this.formData = {
        ...this.dataInfo,
        // 解析已有参数（如果是字符串格式）
        modelDataParams: this.parseParams(this.dataInfo?.modelDataParams || "[]")
      };
      this.modelDataParams = [...this.formData.modelDataParams]; // 同步到视图数组
    },

    onModelChange(modelId) {
      //获取模型参数详情
      getFaultPhysical(modelId).then(rest => {
        this.initialData  = rest.data.configData;
        this.formData.modelId = rest.data.modelId;
        console.log('modelDataParams',this.initialData)
      });
    },

    handleSubmitDataList(data) {
      this.formData.postApiData = JSON.stringify(data);
      console.log('submit', this.formData)
    },

    parseParams(params) {
      // 解析参数字符串为数组对象
      try {
        const parsed = JSON.parse(params);
        return Array.isArray(parsed) ? parsed : [parsed]; // 确保返回数组
      } catch (e) {
        console.error("参数解析错误", e);
        return [];
      }
    },

    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        const api = this.formData.id ? updatePhyModel : addPhyModel;
        api(this.formData).then(() => {
          this.$message.success(this.formData.id ? "修改成功" : "新增成功");
          this.handleCancel();
        });
      });
    },

    handleCancel() {
      // 重置表单数据
      this.formData = {
        dataGenName: null,
        modelId: null,
        modelType: null,
        dataId: null,
        startTime: null,
        endTime: null,
        remark: null,
        modelPath: null
      };
      this.modelDataParams = [];
      this.$emit("input", false);
    }
  }
};
</script>
<style scoped>
.body-toolbar {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 10px;;
}
</style>
