<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="6">
          <el-form-item label="物料编号" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入物料编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="queryParams.version"
              placeholder="请输入版本号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="启用标志" prop="status">
            <DictSelect
              v-model="queryParams.status"
              placeholder="请选择启用标志"
              dict-type="WMS_ENABLE_FLAG"
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </div>
      </QueryFormWrapper>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:material-additional:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :loading="exportLoading"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          v-hasPermi="['wms:incoming-receipt-inspection:import']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :show-search.sync="showSearch"
        :columns="columnsList"
        @queryTable="handleQuery"
        @saveSetting="getColumnsList"
      />
    </el-row>

    <!-- 列表 -->
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="未提交" name="inspectionNoSubmit" lazy>
        <InspectionNoSubmit
          ref="inspectionNoSubmit"
          :active-name="activeName"
          :query-paramspro="queryParams"
          @approvalList="approvalNosubmitList"
          @columns="getColumns"
        />
      </el-tab-pane>
      <el-tab-pane label="待审核" name="awaitApproval" lazy>
        <AwaitApproval
          ref="awaitApproval"
          :active-name="activeName"
          :query-paramspro="queryParams"
          @approvalList="approvalList"
          @noPassApproval="handleNoPass"
        />
      </el-tab-pane>
      <el-tab-pane label="已审核" name="alreadyApproval" lazy>
        <!-- 已审批 -->
        <AlreadyApproval
          ref="alreadyApproval"
          :active-name="activeName"
          :query-paramspro="queryParams"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 新增检验 -->
    <UpdateInspection ref="updateInspection" @addComplete="handleNoPass" />

    <!-- 标准导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      @close="uploadClose"
    >
      <!-- 导入条件 -->
      <el-form
        ref="uploadForm"
        :rules="uploadRules"
        :model="uploadForm"
        label-width="108px"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="检验方案列" prop="masterColumn">
              <el-input-number
                v-model="uploadForm.masterColumn"
                :min="1"
                label="请填写检验方案列"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="物料编码列" prop="codeColumn">
              <el-input-number
                v-model="uploadForm.codeColumn"
                :min="1"
                label="请输入物料编码列"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检验项开始列" prop="beginColumn">
              <el-input-number
                v-model="uploadForm.beginColumn"
                :min="1"
                label="请输入检验项开始列"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标题行" prop="titleRowNum">
              <el-input-number
                v-model="uploadForm.titleRowNum"
                :min="1"
                label="请输入标题行"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 上传文件 -->
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url"
        :data="uploadForm"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-remove="handleRemove"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xlsx格式文件。</span>
        </div>
        <!-- 文件列表 -->
        <transition-group
          class="upload-file-list el-upload-list el-upload-list--text"
          name="el-fade-in-linear"
          tag="ul"
        >
          <li
            v-for="(file, index) in fileList"
            :key="file.url.fileId || file.id"
            class="el-upload-list__item ele-upload-list__item-content"
          >
            <el-link :href="`${file.url}`" :underline="false" target="_blank">
              <span class="el-icon-document">
                {{ getFileName(file.name) || file.sysName }}
              </span>
            </el-link>
            <div class="ele-upload-list__item-content-action">
              <el-link
                :underline="false"
                type="danger"
                :disabled="isUploadShow !== -1"
                @click="handleDelete(index, file)"
                >删除</el-link
              >
            </div>
          </li>
        </transition-group>
      </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>
  </div>
</template>

<script>
import AwaitApproval from "./AwaitApproval.vue";
import AlreadyApproval from "./AlreadyApproval.vue";
import InspectionNoSubmit from "./InspectionNoSubmit.vue";
import UpdateInspection from "../components/UpdateInspection.vue";
import { getBaseHeader } from "@/utils/request";

export default {
  name: "MaterialAdditional",
  components: {
    AwaitApproval,
    AlreadyApproval,
    InspectionNoSubmit,
    UpdateInspection,
  },
  provide() {
    return {
      paramsQuery: this.queryParams,
    };
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "inspectionNoSubmit",
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料附加信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        code: null,
        name: null,
        wmsMaterialItemMasterId: null,
        version: null,
        status: null,
        createTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "物料编号不能为空", trigger: "blur" },
        ],
        wmsMaterialItemMasterId: [
          { required: true, message: "检验项类别不能为空", trigger: "blur" },
        ],
      },
      uploadRules: {
        masterColumn: [
          { required: true, message: "检验方案列不能为空", trigger: "blur" },
        ],
        codeColumn: [
          { required: true, message: "物料编码列不能为空", trigger: "blur" },
        ],
        beginColumn: [
          { required: true, message: "检验项开始列不能为空", trigger: "blur" },
        ],
        titleRowNum: [
          { required: true, message: "标题行不能为空", trigger: "blur" },
        ],
      },
      // 显隐列参数
      columnsList: [],
      // 导入表单参数
      uploadForm: {
        processNo: "PURCHASE",
      },
      // 上传的文件列表
      fileList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/admin-api/wms/material-additional/import-excel",
      },
    };
  },
  methods: {
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        name: undefined,
        wmsMaterialItemMasterId: undefined,
        version: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs[this.activeName].getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs[this.activeName].handleQuery();
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    approvalList() {
      const alreadyApproval = this.$refs.alreadyApproval;
      alreadyApproval && alreadyApproval.handleQuery();
    },
    approvalNosubmitList() {
      const awaitApproval = this.$refs.awaitApproval;
      awaitApproval && awaitApproval.handleQuery();
    },
    handleNoPass() {
      const inspectionNoSubmit = this.$refs.inspectionNoSubmit;
      inspectionNoSubmit && inspectionNoSubmit.handleQuery();
    },
    // 新增未提交的标准
    handleAdd() {
      this.$refs.updateInspection.btnText = "add";
      this.$refs.updateInspection.commitDisable = true;
      this.$refs.updateInspection.queryObj.version = "草稿";
      this.$refs.updateInspection.queryParams.processNo = "PURCHASE";
      this.$refs.updateInspection.queryParams.type = 0;
      this.$refs.updateInspection.auditStatus = -11;
      this.$refs.updateInspection.visible = true;
    },
    materialChange(v) {
      const { materialNo } = v;
      this.form.code = materialNo;
    },
    getColumns(data) {
      this.columnsList = data;
    },
    // 获取显示隐藏列
    getColumnsList() {
      this.$nextTick(() => {
        this.$refs[this.activeName].getColumnsList();
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入标准";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$notify.error({
          title: "提示",
          message: response.msg,
          duration: 0,
        });
        this.upload.isUploading = false;
        // this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      const data = response.data;
      let text = "创建成功数量：" + data.createUsernames.length;
      for (const username of data.createUsernames) {
        text += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + username;
      }
      text += "<br />更新成功数量：" + data.updateUsernames.length;
      for (const username of data.updateUsernames) {
        text += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + username;
      }
      text +=
        "<br />更新失败数量：" + Object.keys(data.failureUsernames).length;
      for (const username in data.failureUsernames) {
        text +=
          "<br />&nbsp;&nbsp;&nbsp;&nbsp;" +
          username +
          "：" +
          data.failureUsernames[username];
      }
      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      try {
        this.$refs["uploadForm"].validate((valid) => {
          if (!valid) {
            return;
          }
          this.$refs.upload.submit();
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 导入标准弹窗关闭
    uploadClose() {
      this.uploadForm = {
        masterColumn: undefined,
        codeColumn: undefined,
        beginColumn: undefined,
        titleRowNum: undefined,
        processNo: "PURCHASE",
      };
      this.$refs.upload.clearFiles();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
  },
};
</script>
