<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="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入检测模板"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料类型名称" prop="itemTypeName">
        <el-input
          v-model="queryParams.itemTypeName"
          placeholder="请输入物料类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入工序名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否质检确认" prop="isConfirm">
        <el-select v-model="queryParams.isConfirm" placeholder="请选择是否质检确认" clearable>
          <el-option label="请选择字典生成" value=""/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否新品" prop="isNewProduct">
        <el-select v-model="queryParams.isNewProduct" placeholder="请选择是否新品" clearable>
          <el-option label="请选择字典生成" 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"
          v-hasPermi="['qc:templateProcess: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="['qc:templateProcess: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="['qc:templateProcess: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="['qc:templateProcess:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['mes:qc:templateProcess:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateProcessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="检测模板" align="center" prop="templateName"/>
      <el-table-column label="物料类型名称" align="center" prop="itemTypeName"/>
      <el-table-column label="工序名称" align="center" prop="processName"/>
      <el-table-column label="最大数量" align="center" prop="maxNum"/>
      <el-table-column label="是否质检确认" align="center" prop="isConfirm" :formatter="yesNoFmt"/>
      <el-table-column label="是否新品" align="center" prop="isNewProduct" :formatter="yesNoFmt"/>
      <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="['qc:templateProcess:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qc:templateProcess: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-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="templateId">
          <el-input v-model="form.templateName" placeholder="请选择检测模板">
            <el-button slot="append" @click="handleSelectTemplate" icon="el-icon-search"></el-button>
          </el-input>
          <TemplateSelect ref="templateSelect" @onSelected="onTemplateSelected"></TemplateSelect>
        </el-form-item>
        <el-form-item label="物料类型" prop="itemTypeId">
          <treeselect v-model="form.itemTypeId" :options="itemTypeOptions" :show-count="true"
                      @select="onItemTypeSelected" placeholder="请选择所属分类"/>
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称">
            <el-button slot="append" @click="visible = true" icon="el-icon-search"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="最大数量" prop="maxNum">
          <el-input v-model="form.maxNum" placeholder="请输入最大数量"/>
        </el-form-item>
        <el-form-item label="是否质检确认" prop="isConfirm">
          <el-select style="width:100%;" v-model="form.isConfirm" placeholder="请选择是否质检确认">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" prop="isNewProduct">
          <el-select style="width:100%;" v-model="form.isNewProduct" placeholder="请选择是否新品">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </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 type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择工序对话框 -->
    <el-dialog title="选择工序" :visible.sync="visible" width="1200px" append-to-body>
      <processList ref="processListRef" v-if="visible" type="single" :operation="false"></processList>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitProcess">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listTemplateProcess,
  getTemplateProcess,
  delTemplateProcess,
  addTemplateProcess,
  updateTemplateProcess
} from "@/api/mes/qc/templateProcess";
import {treeselect} from "@/api/mes/md/itemtype";
import TemplateSelect from "@/components/qctemplateSelect/single.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import processList from '@/views/mes/pro/process/index'
import {getToken} from "@/utils/auth";

export default {
  name: "TemplateProcess",
  components: {
    Treeselect,
    TemplateSelect,
    processList
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测模板-工序表格数据
      templateProcessList: [],
      itemTypeOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        itemTypeId: null,
        itemTypeName: null,
        processName: null,
        maxNum: null,
        isConfirm: null,
        isNewProduct: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
      },
      // 表单参数
      form: {
        id: null,
        templateId: null,
        templateName: null,
        itemTypeId: null,
        itemTypeName: null,
        processId:null,
        processName: null,
        maxNum: null,
        isConfirm: 0,
        isNewProduct: null,
        remark: null,
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/qc/templateProcess/importData"
      },
      // 表单校验
      rules: {
        templateId: [
          {required: true, message: "检测模板不能为空", trigger: "blur"}
        ], processName: [
          {required: true, message: "工序名称不能为空", trigger: "blur"}
        ],
      },
      visible: false
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询检测模板-工序列表 */
    getList() {
      this.loading = true;
      listTemplateProcess(this.queryParams).then(response => {
        this.templateProcessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSubmitProcess() {

      if (!this.$refs.processListRef.selectedItemId) {
        this.$message.warning('请选择工序')
        return
      }
      this.form.processName = this.$refs.processListRef.currentData.processName
      this.form.processId = this.$refs.processListRef.currentData.processId
      this.visible = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateId: null,
        templateName: null,
        itemTypeId: null,
        itemTypeName: null,
        processId:null,
        processName: null,
        maxNum: null,
        isConfirm: 0,
        isNewProduct: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.itemTypeOptions = response.data;
      });
    },
    // 多选框选中数据
    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 = "添加工序检测模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplateProcess(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) {
            updateTemplateProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplateProcess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除工序检测模板编号为"' + recordIds + '"的数据项？').then(function () {
        return delTemplateProcess(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/qc/templateProcess/export', {
        ...this.queryParams
      }, `工序检测模板_${new Date().getTime()}.xlsx`)
    },
    //选择检测项弹出框
    handleSelectTemplate() {
      this.$refs.templateSelect.showFlag = true;
    },
    yesNoFmt(row, column, cellValue) {
      if (cellValue == 1) {
        return "是";
      } else {
        return "否";
      }
    },
    //弹框返回值
    onTemplateSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.templateId = obj.id;
        this.form.templateName = obj.templateName;
      }
    },
    onItemTypeSelected(obj) {
      this.form.itemTypeName = obj.label;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工序检测模版";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/qc/templateProcess/importTemplate', {}, `工序检测模版导入模版_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
