<template>
  <div class="app-container">
    <el-row :gutter="20">
      <MaterialGroupAdd ref="MaterialGroupAdd" @onNodeClick="onNodeClick" @child-event="getCheckTypeList"></MaterialGroupAdd>
      <el-col :span="20" :xs="24"> 
        <el-row :gutter="10" class="mb8">
          <el-col :span="23" :xs="24">
            <el-tabs v-model="editableTabsValue" type="card" @tab-click="handleClick">
              <el-tab-pane
                :key="item.id"
                v-for="(item) in editableTabs"
                :label="item.checkName"
                :name="item.id"
              >
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="检验规则名称" prop="ruleName">
            <el-input
              v-model="queryParams.ruleName"
              placeholder="请输入检验规则名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </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="['quality:checkTypeProject: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="['quality:checkTypeProject: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"
              v-hasPermi="['quality:checkTypeProject: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="['quality:checkTypeProject:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="checkTypeProjectList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="检验规则名称" align="center" prop="ruleName" />
          <el-table-column label="标准值" align="center" prop="standardValue" />
          <el-table-column label="上差值" align="center" prop="upperDiff" />
          <el-table-column label="下差值" align="center" prop="downDiff" />
          <el-table-column label="抽样比例" align="center" prop="sample" />
          <el-table-column label="抽样数量" align="center" prop="sampleNum" />
          <el-table-column
            label="是否启用,0是1否"
            align="center"
            prop="status"
          /> 
          <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="['quality:checkTypeProject:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['quality:checkTypeProject: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"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改物料检验项目维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="projectId">
          <el-select v-model="form.projectId" @change="handleChange" placeholder="请选择检验规则属性" >
						<el-option
							v-for="item in checkRuleList"
							:key="item.id"
							:label="item.ruleName"
							:value="item.id"
						></el-option>
					</el-select>
        </el-form-item>
        <el-form-item label="抽样比例" prop="sample">
          <el-input v-model="form.sample" placeholder="请输入抽样比例" />
        </el-form-item>
        <el-form-item label="抽样数量" prop="sampleNum">
          <el-input v-model="form.sampleNum" placeholder="请输入抽样数量" />
        </el-form-item>
        <el-form-item label="规则方式" prop="propertyCode">
          <el-select v-model="form.propertyCode" disabled placeholder="请选择检验规则属性"  >
						<el-option
							v-for="dict in dict.type.qc_rule_prop"
							:key="dict.value"
							:label="dict.label"
							:value="dict.value"
						></el-option>
					</el-select>
        </el-form-item>
        <div v-if="form.propertyCode === '1'">
          <el-form-item label="标准值" prop="standardValue">
            <el-input v-model="form.standardValue" placeholder="请输入标准值" />
          </el-form-item>
          <el-form-item label="上差值" prop="upperDiff">
            <el-input v-model="form.upperDiff" placeholder="请输入上差值" />
          </el-form-item>
          <el-form-item label="下差值" prop="downDiff">
            <el-input v-model="form.downDiff" placeholder="请输入下差值" />
          </el-form-item>
        </div>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCheckTypeProject,
  getCheckTypeProject,
  delCheckTypeProject,
  addCheckTypeProject,
  updateCheckTypeProject,
} from "@/api/quality/checkTypeProject";
import MaterialGroupAdd from "./MaterialGroupAdd.vue";
import {listCheckType} from "@/api/quality/checkType";
import {listProject} from "@/api/quality/project";

export default {
  name: "CheckTypeProject",
  dicts: ["qc_rule_prop"],
  components: {MaterialGroupAdd,},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      groupId: null,
      materialCode: null,
      // 总条数
      total: 0,
      // 物料检验项目维护表格数据
      checkTypeProjectList: [],
      checkRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      editableTabsValue: '',
      editableTabs: [/* {
        title: 'Tab 1',
        name: '1',
        content: 'Tab 1 content'
      }, {
        title: 'Tab 2',
        name: '2',
        content: 'Tab 2 content'
      } */],
      tabIndex: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        ruleName: null,
        typeId: null,
        standardValue: null,
        upperDiff: null,
        downDiff: null,
        sample: null,
        sampleNum: null,
        status: null,
        attr1: null,
        factoryCode: null,
        groupName: null,
        groupId: null,
        materialCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "检验项目id不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //this.getList();
  },
  methods: {
    /** 查询物料检验项目维护列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams);
      listCheckTypeProject(this.queryParams).then((response) => {
        this.checkTypeProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**初始化表格信息 */
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        ruleName: null,
        propertyCode: null,
        typeId: null,
        standardValue: null,
        upperDiff: null,
        downDiff: null,
        sample: null,
        sampleNum: null,
        status: null,
        attr1: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        factoryCode: null,
        delFlag: null,
        groupId: null,
        materialCode: null,
        projectNo: null,
      };
      this.resetForm("form");
    },
    /**物料树点击 */
    onNodeClick(obj) {
      if(obj.level == 1) {
        this.queryParams.groupId = obj.id;
        this.groupId = obj.id;
        this.queryParams.materialCode = null;
        this.materialCode = null;
      }else{
        this.queryParams.materialCode = obj.materialCode;
        this.materialCode = obj.materialCode;
        this.queryParams.groupId = null;
        this.groupId = null;
      }
      this.queryParams.typeId = this.editableTabsValue;
      this.handleQuery();

    },
    /**获取检测节点*/
    getCheckTypeList(obj) {
      listCheckType().then((response) => {
        this.editableTabs = response.rows;
        this.editableTabsValue = response.rows[0].id;
        this.tabIndex = response.rows.length;
        this.queryParams.groupId = obj.id;
        this.queryParams.typeId = this.editableTabsValue;
        this.getList();
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /**检验规则改变事件 */
    handleChange() {
      const obj = this.checkRuleList.find(obj => obj.id === this.form.projectId);
      console.log(obj);
      this.form.propertyCode = obj.propertyCode;
      this.form.standardValue = obj.checkStandard;
      this.form.projectNo = obj.orderNum;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料检验项目维护";
      this.form.groupId = this.groupId;
      this.form.materialCode = this.materialCode;
      this.form.typeId = this.editableTabsValue;
      listProject().then((response) => {
          this.checkRuleList = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCheckTypeProject(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料检验项目维护";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCheckTypeProject(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCheckTypeProject(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }); 
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除物料检验项目维护编码为"' + ids + '"的数据项？')
        .then(function () {
          return delCheckTypeProject(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "quality/checkTypeProject/export",
        {
          ...this.queryParams,
        },
        `checkTypeProject_${new Date().getTime()}.xlsx`
      );
    },
    /**标签编辑事件 */
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + '';
        this.editableTabs.push({
          title: 'New Tab',
          name: newTabName,
          content: 'New Tab content'
        });
        this.editableTabsValue = newTabName;
      }
      if (action === 'remove') {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      }
    },
    /**标签点击事件 */
    handleClick(tab, event) {
      this.queryParams.typeId = tab.name;
      this.handleQuery();
    },
  },
};
</script>
