<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="规范名称" prop="specName">
        <el-input
          v-model="queryParams.specName"
          placeholder="请输入制造规范名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工艺路线" prop="processRoute">
        <el-input
          v-model="queryParams.processRoute"
          placeholder="请输入工艺路线"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.work_mspec_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规范类型" prop="specType">
        <el-select v-model="queryParams.specType" placeholder="请选择规范类型" clearable>
          <el-option
            v-for="dict in dict.type.work_mspec_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="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <KLPTable v-loading="loading" :data="manufacturingSpecList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="specId" v-if="false"/>
      <el-table-column label="制造规范编码" align="center" prop="specCode" />
      <el-table-column label="制造规范名称" align="center" prop="specName" />
      <!-- 工艺路线列：溢出显示省略号 -->
      <el-table-column 
        label="工艺路线" 
        align="center" 
        prop="processRoute" 
        width="220"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_mspec_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="规范类型" align="center" prop="specType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_mspec_type" :value="scope.row.specType"/>
        </template>
      </el-table-column>
      <el-table-column label="理论工时(h)" align="center" prop="standardHours" />
      <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)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </KLPTable>

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

    <!-- 添加或修改制造规范对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规范编码" prop="specCode">
          <el-input v-model="form.specCode" placeholder="请输入制造规范编码" />
        </el-form-item>
        <el-form-item label="规范名称" prop="specName">
          <el-input v-model="form.specName" placeholder="请输入制造规范名称" />
        </el-form-item>
        
        <!-- 工艺路线：动态输入框组 -->
        <el-form-item label="工艺路线" prop="processSteps">
          <div v-for="(step, index) in form.processSteps" :key="index" class="process-step-item">
            <el-input
              v-model="form.processSteps[index]"
              placeholder="请输入工艺步骤"
              class="step-input"
            />
            <el-button
              type="text"
              icon="el-icon-delete"
              size="mini"
              class="delete-btn"
              @click="removeStep(index)"
              :disabled="form.processSteps.length <= 1"
            />
          </div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addStep"
            class="add-step-btn"
          >
            添加工艺步骤
          </el-button>
          <div class="form-hint">提示：点击"+"添加步骤，点击"×"删除步骤</div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.work_mspec_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规范类型" prop="specType">
          <el-select v-model="form.specType" placeholder="请选择规范类型">
            <el-option
              v-for="dict in dict.type.work_mspec_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="理论工时(h)" prop="standardHours">
          <el-input v-model="form.standardHours" placeholder="请输入理论工时(h)" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManufacturingSpec, getManufacturingSpec, delManufacturingSpec, addManufacturingSpec, updateManufacturingSpec } from "@/api/work/manufacturingSpec";

export default {
  name: "ManufacturingSpec",
  dicts: ['work_mspec_status', 'work_mspec_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 制造规范表格数据
      manufacturingSpecList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        specCode: undefined,
        specName: undefined,
        processRoute: undefined,
        status: undefined,
        specType: undefined,
        standardHours: undefined,
      },
      // 表单参数
      form: {
        processSteps: [] // 用于存储多个工艺步骤的数组
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询制造规范列表 */
    getList() {
      this.loading = true;
      listManufacturingSpec(this.queryParams).then(response => {
        this.manufacturingSpecList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        specId: undefined,
        specCode: undefined,
        specName: undefined,
        businessUnit: undefined,
        projectTeam: undefined,
        productModule: undefined,
        identifier: undefined,
        material: undefined,
        specification: undefined,
        processRoute: undefined,
        processSteps: [''], // 初始化至少一个输入框
        processParams: undefined,
        scope: undefined,
        inspectionStandard: undefined,
        status: 1,
        specType: 1,
        version: undefined,
        versionDate: undefined,
        standardHours: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.specId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加制造规范";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const specId = row.specId || this.ids
      getManufacturingSpec(specId).then(response => {
        this.loading = false;
        const data = response.data;
        
        // 将工艺路线字符串拆分为步骤数组
        if (data.processRoute) {
          data.processSteps = data.processRoute
            .split('-')
            .filter(line => line); // 过滤空行
        } else {
          data.processSteps = [''];
        }
        
        this.form = data;
        this.open = true;
        this.title = "修改制造规范";
      });
    },
    /** 添加工艺步骤输入框 */
    addStep() {
      this.form.processSteps.push('');
    },
    /** 移除工艺步骤输入框 */
    removeStep(index) {
      if (this.form.processSteps.length <= 1) {
        this.$message.warning('至少保留一个工艺步骤');
        return;
      }
      this.form.processSteps.splice(index, 1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          
          // 验证至少有一个非空步骤
          const hasValidStep = this.form.processSteps.some(step => step.trim() !== '');
          if (!hasValidStep) {
            this.$message.error('请至少输入一个工艺步骤');
            this.buttonLoading = false;
            return;
          }
          
          // 处理工艺路线格式，将步骤数组合并为带-前缀的字符串
          this.form.processRoute = this.form.processSteps
            .map(step => step.trim())
            .filter(step => step) // 过滤空行
            .join('-');

          if (this.form.specId != null) {
            updateManufacturingSpec(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addManufacturingSpec(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const specIds = row.specId || this.ids;
      this.$modal.confirm('是否确认删除制造规范编号为"' + specIds + '"的数据项？').then(() => {
        this.loading = true;
        return delManufacturingSpec(specIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('klp/manufacturingSpec/export', {
        ...this.queryParams
      }, `manufacturingSpec_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.process-step-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.step-input {
  flex: 1;
  margin-right: 10px;
}

.delete-btn {
  color: #F56C6C;
}

.add-step-btn {
  margin-top: 10px;
}

.form-hint {
  margin-top: 5px;
  color: #606266;
  font-size: 12px;
  line-height: 1.5;
}
</style>
