<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="数据生成名称" prop="name">
        <el-input
          v-model="queryParams.dataGenName"
          placeholder="请输入数据生成名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dataGen:phyModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dataGen:phyModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete(ids)"
          v-hasPermi="['dataGen:phyModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dataGen:phyModel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="phyModelList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据生成名称" align="center" prop="dataGenName" />
      <el-table-column label="数据生成模型" align="center" prop="modelName" />
      <el-table-column label="参数" align="center" prop="bizParams" />
      <el-table-column label="数据" align="center" prop="dataId" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dataGen:phyModel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete([scope.row.dataGenId])"
            v-hasPermi="['dataGen:phyModel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 表单弹窗 -->
    <FormDialog
      v-model="open"
      :data-info="form"
      :data-options="dataOptions"
      :fault-physical-options="faultPhysicalOptions"
      @input="getList"
    />
  </div>
</template>

<script>
import {
  listPhyModel,
  getPhyModel,
  delPhyModel,
  addPhyModel,
  updatePhyModel,
} from "@/api/dataGen/phyModel";
import FormDialog from './form.vue';

export default {
  name: "PhyModel",
  components: {
    FormDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物理模型数据生成管理表格数据
      phyModelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        startTime: null,
        endTime: null,
        dataGenName: null
      },
      // 表单参数
      form: {
        dataGenId: '',
        dataGenName: '',
        modelId: '',
        bizParams: '',
        dataId: '',
        status: '',
        originalDataIds: '',
        generatedDataId: '',
        startTime: '',
        endTime: '',
        remark: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
      },
      // 数据Optipons
      dataOptions: [],
      faultPhysicalOptions: [],
    };
  },
  created() {
    // 同时请求列表数据和选项数据
    Promise.all([this.getList(), this.getOption()])
      .then(() => {
        this.loading = false;
      })
      .catch((error) => {
        console.error('数据加载失败:', error);
        this.loading = false;
      });
  },
  methods: {
    /** 查询物理模型数据生成管理列表 */
    getList() {
      this.loading = true;
      return listPhyModel(this.queryParams)
        .then((response) => {
          this.phyModelList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error('查询列表失败:', error);
          this.loading = false;
        });
    },

    // 获取选项数据
    getOption() {
      // 这里需要根据实际情况实现获取选项数据的逻辑
      return new Promise((resolve) => {
        // 模拟异步操作
        setTimeout(() => {
          // 这里可以调用 API 获取选项数据
          this.dataOptions = [];
          this.faultPhysicalOptions = [];
          resolve();
        }, 100);
      });
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        modelId: null,
        bizParams: null,
        dataId: null,
        status: null,
        startTime: null,
        endTime: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.dataGenId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物理模型数据生成管理";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.dataGenId || this.ids;
      getPhyModel(id)
        .then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改物理模型数据生成管理";
        })
        .catch((error) => {
          console.error('获取数据失败:', error);
        });
    },

    /** 删除按钮操作 */
    /** 删除按钮操作 */
    handleDelete(idsToDelete) {
      // 处理单个/多个删除时的名称展示
      const names = idsToDelete.map(id => {
        const item = this.phyModelList.find(row => row.dataGenId === id);
        return item ? item.dataGenName : `ID:${id}`; // 优先使用名称，找不到则用ID
      }).filter(name => name); // 过滤无效项

      const message = names.length > 1
        ? `是否确认删除以下 ${names.length} 条数据？\n${names.join('\n')}`
        : `是否确认删除数据项：${names[0]}？`;

      this.$modal
        .confirm(message)
        .then(() => {
          return delPhyModel(idsToDelete); // 假设接口支持批量删除（数组参数）
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(error => {
          console.error('删除失败:', error);
          this.$modal.msgError("删除失败，请检查网络或重试");
        });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "dataGen/phyModel/export",
        {
          ...this.queryParams,
        },
        `phyModel_${new Date().getTime()}.xlsx`
      );
    },
  }
};
</script>
