<template>
  <div class="app-container">
    <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="$t('检测模板')" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
         
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('物料类型名称')" prop="itemTypeName">
        <el-input
          v-model="queryParams.itemTypeName"
         
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('工序名称')" prop="processName">
        <el-input
          v-model="queryParams.processName"
         
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('是否质检确认')" prop="isConfirm">
        <el-select v-model="queryParams.isConfirm" clearable>
          <el-option :label="$t('请选择字典生成')" value=""/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('是否新品')" prop="isNewProduct">
        <el-select v-model="queryParams.isNewProduct" clearable>
          <el-option :label="$t('请选择字典生成')" value=""/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</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']"
        >{{$t('新增')}}</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']"
        >{{$t('修改')}}</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']"
        >{{$t('删除')}}</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']"
        >{{$t('导出')}}</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']"
        >{{$t('导入')}}</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="$t('模板类型')" align="center" prop="qcType">
      </el-table-column>
      <el-table-column :label="$t('检测模板')" align="center" prop="templateName"/>
      <el-table-column :label="$t('物料类型名称')" align="center" prop="itemTypeName"/>
      <el-table-column :label="$t('工序名称')" align="center" prop="processName"/>
      <el-table-column :label="$t('最大数量')" align="center" prop="maxNum"/>
      <el-table-column :label="$t('是否质检确认')" align="center" prop="isConfirm" :formatter="yesNoFmt"/>
      <el-table-column :label="$t('是否新品')" align="center" prop="isNewProduct" :formatter="yesNoFmt"/>
      <el-table-column :label="$t('common.remark')" align="center" prop="remark"/>
      <el-table-column :label="$t('common.option')" 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']"
          >{{$t('修改')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qc:templateProcess:remove']"
          >{{$t('删除')}}</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="$t('模板类型')" prop="qcType">
          <el-radio-group v-model="form.qcType">
            <el-radio label="IPQC">IPQC</el-radio>
            <el-radio label="IQC">IQC</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('检测模板')" prop="templateId">
          <el-input v-model="form.templateName">
            <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="$t('物料类型')" prop="itemTypeId">
          <treeselect v-model="form.itemTypeId" :options="itemTypeOptions" :show-count="true"
                      @select="onItemTypeSelected"/>
        </el-form-item>
        <el-form-item :label="$t('工序名称')" prop="processName">
          <el-input v-model="form.processName" :disabled="form.qcType === 'IQC'">
            <el-button slot="append" @click="visible = true" icon="el-icon-search" :disabled="form.qcType === 'IQC'"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('最大数量')" prop="maxNum" >
          <el-input v-model="form.maxNum" :disabled="form.qcType === 'IQC'"/>
        </el-form-item>
        <el-form-item :label="$t('是否质检确认')" prop="isConfirm">
          <el-select style="width:100%;" v-model="form.isConfirm" :disabled="form.qcType === 'IQC'">
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('是否新品')" prop="isNewProduct" >
          <el-select style="width:100%;" v-model="form.isNewProduct" :disabled="form.qcType === 'IQC'">
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="form.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.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">{{$t('将文件拖到此处，或')}}<em>{{$t('点击上传')}}</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>{{$t('是否更新已经存在的用户数据')}}</div>
          <span>{{$t('仅允许导入xls、xlsx格式文件。')}}</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">{{$t('下载模板')}}</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 选择工序对话框 -->
    <el-dialog :title="$t('选择工序')" :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">{{ $t('common.confirm') }}</el-button>
        <el-button @click="visible = false">{{ $t('common.cancel') }}</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,
        qcType: 'IPQC',
        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"
      },
      visible: false
    };
  },
  computed: {
    rules (){
      return {
        templateId: [
          {required: true, message: this.$t('检测模板不能为空'), trigger: "blur"}
        ], processName: [
          {required: this.form.qcType !== 'IQC', message: this.$t('工序名称不能为空'), trigger: "blur"}
        ],
      }
    }
  },
  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(this.$t('请选择工序'))
        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,
        qcType: 'IPQC',
        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 = this.$t('添加IPQC/IQC检测模板');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplateProcess(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('修改IPQC/IQC检测模板');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplateProcess(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.edit_success'));
              this.open = false;
              this.getList();
            });
          } else {
            addTemplateProcess(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.add_success'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.id || this.ids;
      this.$modal.confirm(this.$t('common.confirm_del_data')).then(function () {
        return delTemplateProcess(recordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.del_success'));
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/qc/templateProcess/export', {
        ...this.queryParams
      }, this.$t('工序检测模板_{0}.xlsx', [new Date().getTime()]))
    },
    //选择检测项弹出框
    handleSelectTemplate() {
      this.$refs.templateSelect.showFlag = true;
    },
    yesNoFmt(row, column, cellValue) {
      if (cellValue == 1) {
        return this.$t('是');
      } else {
        return this.$t('否');
      }
    },
    //弹框返回值
    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>", this.$t('导入结果'), {dangerouslyUseHTMLString: true});
      this.getList();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('工序检测模版');
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/qc/templateProcess/importTemplate', {}, this.$t('工序检测模版导入模版_{0}.xlsx', [new Date().getTime()]))
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
