<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.modelName"
          placeholder="请输入故障模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障模型类型" prop="type">
        <el-select
          v-model="queryParams.modelType"
          placeholder="请选择故障模型类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.biz_model_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="handleViews(null,'add')"
          v-hasPermi="['model:faultPhysical:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleViews(null,'edit')"
          v-hasPermi="['model:faultPhysical: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="['model:faultPhysical: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="['model:faultPhysical:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="faultPhysicalList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模型名称" align="center" prop="modelName"/>
      <el-table-column  label="模型接口地址" align="center" prop="modelPath"/>
      <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-link
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleViews(scope.row,'edit')"
            v-hasPermi="['model:faultPhysical:edit']"
          >修改
          </el-link>       |
          <el-link
            size="mini"
            type="warning"
            icon="el-icon-view"
            @click="handleViews(scope.row,'info')"
          >详情</el-link>
          |
          <el-link
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleViews(scope.row,'remove')"
            v-hasPermi="['model:faultPhysical:remove']"
          >删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>

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

    <FaultPhysicalForm
      v-model="dialogOpen"
      :data-info="currentRow"
      :options="options"
      @callback="getList"
    />
  </div>
</template>

<script>
import {
  listFaultPhysical,
  getFaultPhysical,
  delFaultPhysical,
  addFaultPhysical,
  updateFaultPhysical,
} from "@/api/model/faultPhysical";
import FaultPhysicalForm from './form.vue';

export default {
  name: "FaultPhysical",
  components: {
    FaultPhysicalForm
  },
  dicts: ["biz_model_type"],
  data() {
    return {
      options: 'add',
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      faultPhysicalList: [],
      currentRow:{},
      dialogOpen: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: '',
        modelName: '',
        modelType:'',
        modelPath: '',
        remark:'',
        modelAttribution:'',
        modelInputPath:'',
        modelOutputPath:''
      },
      form: {},
      rules: {},
    };
  },
  computed: {
    modelAtrtibution() {
      return this.$route.query.modelAttribution;
    }
  },
  created() {
    this.getList();
  },
  methods: {

    getList() {
      this.queryParams.modelAttribution = this.modelAtrtibution;
      this.currentRow={};
      this.loading = true;
      listFaultPhysical(this.queryParams).then((response) => {
        this.faultPhysicalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    reset() {
      this.form = {
        modelId: null,
        modelName: null,
        modelType: null,
        modelPath: null,
        modelDataParams: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        modelAttribution:'',
        modelInputPath:'',
        modelOutputPath:''
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams={};
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.modelId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleViews(row, option) {
      switch (option) {
        case 'add':
          this.reset();
          this.dialogOpen = true;
          this.options = option;
          break;
        case 'edit':
          this.reset();
          this.dialogOpen = true;
          if (row) {
            this.currentRow = Object.assign({}, row);
          } else if (this.ids.length === 1) {
            const selectedRow = this.faultPhysicalList.find(item => item.modelId === this.ids[0]);
            if (selectedRow) {
              this.currentRow = Object.assign({}, selectedRow);
            }
          }
          this.options = option;
          break;
        case 'info':
          this.reset();
          this.dialogOpen = true;
          this.currentRow = Object.assign({}, row);
          this.options = option;
          break;
        case 'remove':
          this.handleDelete(row);
          break;
      }
    },
    /** 删除按钮操作 */
    handleDelete(deleteTarget) {
      // 统一处理为数组格式（支持单选/多选）
      const deleteIds = Array.isArray(deleteTarget)
        ? deleteTarget.map(item => item.modelId) // 多选时提取modelId数组
        : [deleteTarget.modelId]; // 单选时包装成单元素数组
      // 提取删除项的故障模型名称（用于显示确认信息）
      const deleteNames = deleteIds.map(id => {
        const item = this.faultPhysicalList.find(row => row.modelId === id);
        return item ? item.modelName : `ID:${id}`; // 优先使用名称，找不到则用ID
      }).filter(name => name); // 过滤无效项（防止删除已被移除的数据）
      // 生成确认消息
      const confirmMessage = deleteNames.length > 1
        ? `是否确认删除以下 ${deleteNames.length} 条故障模型？\n${deleteNames.join('\n')}`
        : `是否确认删除故障模型：${deleteNames[0]}？`;
      this.$modal
        .confirm(confirmMessage)
        .then(() => {
          return delFaultPhysical(deleteIds); // 调用删除接口（支持批量传参）
        })
        .then(() => {
          this.getList(); // 刷新列表
          this.$modal.msgSuccess("删除成功");
        })
        .catch(error => {
          console.error('删除失败:', error);
          this.$modal.msgError("删除失败，请检查网络或重试");
        });
    },
    handleExport() {
      this.download(
        "model/faultPhysical/export",
        {
          ...this.queryParams,
        },
        `faultPhysical_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
