<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-row>
        <el-form-item v-if="formData.modelType === '2'" label="模型参数">
          <el-input
            v-model="formData.bizParams"
            type="textarea"
            placeholder="请输入模型参数（JSON格式）"
          />
        </el-form-item>

        <el-form-item v-if="formData.modelType === '1'" label="模型参数">
          <el-row :gutter="10">
            <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1" :offset="22">
              <el-button
                icon="el-icon-plus"
                @click="addModelDataParams"
                size="mini"
                circle
                title="添加参数组"
              />
            </el-col>
          </el-row>

          <el-collapse :gutter="20" v-for="(paramGroup, groupIndex) in modelDataParams" :key="groupIndex">
            <el-collapse-item :title="'参数组' + (groupIndex + 1)" :name="groupIndex">
              <el-row :xl="4" v-for="(value, key) in paramGroup" :key="key" :gutter="20">
                <el-col >
                  <el-form-item :label="key" :prop="`modelDataParams.${groupIndex}.${key}`">
                    <el-input
                      v-model="paramGroup[key]"
                      :placeholder="'请输入' + key + '的值'"
                      style="width: 200px;"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-row>

      <el-row>
<!--        <el-form-item v-if="formData.modelType !== '2'" label="基础数据" prop="dataId">-->
<!--          <el-select v-model="formData.newFileName" placeholder="请选择基础数据">-->
<!--            <el-option-->
<!--              v-for="item in dataOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <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";

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    dataInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      modelDataParams: [], // 视图层显示的参数组数组
      dataOptions: [],
      faultPhysicalOptions: [],
      formData: {
        outputPath:null,
        newFileName:null,
        dataGenName: null,
        modelId: null,
        modelType: null,
        dataId: null,
        startTime: null,
        endTime: null,
        remark: null,
        modelDataParams: [], // 提交用的参数组数组
        modelPath: null,
        modelName:null
      },
      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: {

    initData() {
      this.loadOptions();
      if (this.dataInfo) {
        this.initFormData();
      }
    },

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

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

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

    onModelChange() {
      const selectedModel = this.faultPhysicalOptions.find(
        item => item.modelId === this.formData.modelId
      );
      if (!selectedModel) return;
      console.log('selectedModel',selectedModel)
      this.formData.modelType = selectedModel.modelType;
      this.formData.modelPath = selectedModel.modelPath;

      if (selectedModel.modelType === "2") {
        // 文本模式直接赋值
        this.formData.bizParams = selectedModel.modelDataParams || "";
        this.modelDataParams = []; // 清空数组模式
      } else {
        // 数组模式初始化参数组
        const exampleParams = this.parseParams(selectedModel.modelDataParams || "[]");
        this.modelDataParams = exampleParams.length ? exampleParams : [{}]; // 至少一个空参数组
        this.formData.modelDataParams = [...this.modelDataParams]; // 同步到提交数据
      }
    },

    addModelDataParams() {
      // 创建新参数组，结构与最后一个参数组一致
      const lastGroup = this.modelDataParams[this.modelDataParams.length - 1] || {};
      const newGroup = Object.fromEntries(
        Object.keys(lastGroup).map(key => [key, ""])
      );
      this.modelDataParams.push(newGroup);
      this.formData.modelDataParams = [...this.modelDataParams]; // 同步到提交数据
    },

    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;

        // 处理参数组数据（如果是数组模式则序列化为JSON）
        if (this.formData.modelType !== "2") {
          this.formData.modelDataParams = JSON.stringify(this.modelDataParams);
          this.formData.bizParams = JSON.stringify(this.modelDataParams);
        }

        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,
        modelDataParams: [],
        modelPath: null
      };
      this.modelDataParams = [];
      this.$emit("input", false);
    }
  }
};
</script>
