<template>
  <div class="page-box InspectNoticePage" v-loading="Loading.appMainLoading">
    <tablePagination
      :currenButtonData="currenButtonData"
      :tableData="tableData"
      :tableLoading="Loading.tableLoading"
      :tableColumns="tableColumns"
      @rowDrop="rowDrop"
      :totalCount="totalCount"
      :multipleSelection="multipleSelection"
      :MaxResultCount="PageListParams.MaxResultCount"
      FormFixedLeft="0px"
      :Options="editOptions"
      @topbutton="topbutton"
      @inlineDialog="inlineDialog"
      @sortChange="sortChange"
      @alertoldSkipCount="alertoldSkipCount"
      @alterResultCount="alterResultCount"
      @handleSelectionChange="handleSelectionChange"
      :currentPageProps="oldSkipCount"
      :quicklySearchOption="quicklySearchOption"
      @quicklySearchClick="quicklySearchClick"
      @quicklySearchClear="quicklySearchClear"
      :primarySearchOption="primarySearchOption"
      @overallSearchFormClick="overallSearchFormClick"
      :httpOverallSearchData="httpOverallSearchData"
    >
    </tablePagination>
    <!-- 抽屉 -->
    <curren-Drawer
      :title="tableColumns"
      :DrawerLoading="Loading.DrawerLoading"
      :drawer="displayDialog.detailsDialog"
      :Butttondata="[]"
      :propsData.sync="propsData"
      :tabsDesTions="tabsDesTions"
      :dropdownTabsData="dropdownTabsData"
      firstTabs="hz"
      @currenTabsChange="currenTabsChange"
      @drawerShut="(val) => (displayDialog.detailsDialog = val)"
      @handleCommand="drawerHandle"
      @close-value="closeValue"
      :currenButtonData="currenButtonData"
      :tableColumns="detailsTableColumns"
      :summaryTableColumns="summaryTableColumns"
      @handleSelectionChange="handleSelectionChange"
      @inlineDialog="inlineDialog"
      :totalCount="totalCountDetails"
      :MaxResultCount="MaxResultCountDetails"
      @alterResultCountDetails="alterResultCountDetails"
      @alertoldSkipCountDetails="alertoldSkipCountDetails"
      @buttonClick="currenDrawerButtonClick">
      <template v-if="currentTagName == 'hz' ">
      <!-- @buttonClick="buttonClick" -->
        <el-table-column
          fixed="left"
          label="操作"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-button 
              type="primary"
              v-if="scope.row.summaryInspectStatus != 2"
              @click="buttonClick(scope.row)"
              size="small"
            >检验详情</el-button>
            <span v-else style="color:#31bb99">质检已完成</span>
          </template>
        </el-table-column>
      </template>		
    </curren-Drawer>
    <!-- 检验弹窗 -->
    <el-dialog
      title="检验"
      :visible.sync="inspectShow"
      top="5vh"
      width="88%"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="false">
      <el-row :gutter="24">
        <el-col :span="14" >
          <curren-Form
            class="handleForm"
            size="medium"
            :searchData="inspectFormData"
            :searchForm="inspectForm"
            :searchHandle="inspectHandle"
            :rules="inspectRules"
            @submitForm="inspectFormClick(arguments)"
          >
            <currenTable
              class="jyTable"
              :tableData="inspectFormData.details"
              :searchOptions="inspectOptions"
              :tableColumns="inspectDetailsTableColumns"
              :selectionTable="false"
              :isShowIndex="true"
              @buttonClick="inspectButtonClick"
            >
            </currenTable>
          </curren-Form>
        </el-col>
        <el-col :span="10" >
          <div style="padding-bottom:10px">作业指导书：</div>
          <curren-descriptions
            border
            :column="1"
            direction="vertical"
            :colon="false"
          >
            <template>
              <el-descriptions-item
                :label="item.label"
                v-for="(item, index) in tabsDesTionsGuideBook"
                :key="index"
              >
                <span v-if="item.type == 'uploadPictureCard'"  >
                  <div v-loading="guideBookLoading" id="uploadPictureCardGuideBook"></div>
                </span>
                <!-- 文本域 -->
                <span v-else>
                  <template>
                    <el-input
                      :type="item.type"
                      v-model="guideBookData[item.prop]"
                      :rows="item.rows"
                    ></el-input>
                  </template>
                </span>
                <!-- <span v-else>{{ guideBookData[item.prop] }}</span> -->
              </el-descriptions-item>
            </template>
          </curren-descriptions>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- <el-dialog
      title="查看供应商质检报告"
      :visible.sync="supplierShow"
      top="5vh"
      width="50%"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="false">
      <curren-Form
        class="handleForm"
        size="medium"
        :searchData="supplierFormData"
        :searchForm="supplierForm"
        :searchHandle="supplierHandle"
        @submitForm="supplierFormClick(arguments)"
      >
      </curren-Form>
    </el-dialog> -->
    <!-- 质检详情 -->
    <el-dialog
        title="质检详情"
        v-loading="loading"
        :visible="inspectNoticeDetailsShow"
        top="5vh"
        width="80%"
        :fullscreen="true"
        :modal="false"
        :modal-append-to-body="false"
        :show-close="false"
      >
        <curren-Form
          class="handleForm"
          size="medium"
          :searchData="inspectNoticeDetailsFormData"
          :searchForm="inspectNoticeDetailsForm"
          :searchHandle="inspectNoticeDetailsEditHandle"
          :rules="inspectNoticeDetailsRules"
          @uploadListView="uploadListView"
          @submitForm="formClick(arguments)"
        >
          <template>
            <template> 
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item
                    :label="'箱码'"
                    :prop="inputPackingCode"
                  >
                    <el-input v-model="inputPackingCode" placeholder="请输入箱码"></el-input>
                  </el-form-item>
                </el-col> 
                <el-col :span="8">
                  <el-button type="primary" @click="query">查询</el-button>
                  <el-button type="primary" @click="reset">重置</el-button>
                </el-col>
              </el-row>
            </template>
            <el-form-item
              class="formTable-box"
              prop="details"
            >
              <umyTable
                :setUTableHeight="470"
                :tableData="inspectNoticeDetailsFormData.details"
                :tableColumns="inspectNoticeDetailsTableColumns"
                :tableLoading = "inspectNoticeDetailsTableLoading"
                :isShowIndex="true"
                :selectionTable="false"
                :cellClassName="cellClassName"
                :tableBorder="true"
                :tableAlign="'center'"
                :tableHeaderAlign="'center'"
                @buttonClick="inspectDetailsButtonClick"
              >
              </umyTable>
            </el-form-item>
          </template>
        </curren-Form>
      </el-dialog>
    <pdf 
      :urlPDF="urlPDF"
      :base64PDF="base64PDF"
      :title="titlePDF"
      v-if="isShowPDF"
      :isShowPDF="isShowPDF"
      :loadingPDF="loadingPDF"
      @closePDF="closePDF"
      :showDownLoad="true"
    ></pdf>
    <!-- 拆箱弹窗 -->
    <el-dialog
      title="拆箱"
      v-loading="devanLoading"
      :visible.sync="devanShow"
      top="10vh"
      width="800px"
      :modal-append-to-body="false"
      :append-to-body="true"
      :show-close="false">
        <div>
          <el-form :inline="true" :model="devanForm" class="demo-form-inline">
            <el-form-item label="拆出数量">
              <el-input type="number" v-model="devanForm.qty" placeholder="拆出数量"></el-input>
            </el-form-item>
          </el-form>
          <!-- <currenTableFlex
            style="width:500px;margin:0 auto"
            :flexTableData="flexTableData"
            :flexSearchOptions="editOptions"
            :flexTableColumns="flexTableColumns"
            :showAddBtn="true"
            :showAllDeleteButton="true"
          ></currenTableFlex> -->
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="devanCancelHandel">取 消</el-button>
          <el-button type="primary" @click="devanSureHandel">确定拆箱</el-button>
        </div>
    </el-dialog>
  </div>
  
</template>
<script>
import { 
  getPageList, 
  fileStorage, 
  getListByItemcode, 
  getDetailed,
  getFilestore,
  InspectSplitPackingk
} from "@/api/wms-api"
import { postSplitPacking,postInventoryLabelCode_count } from "@/api/wms-core"
import { completeSummaryDetailStatus, setDetailDefaultOkStatus, setDetailOkStatus, setDetailNookStatus } from "@/api/wms-job"
import { tableMixins } from "@/mixins/TableMixins"
import { LoadingMixins } from "@/mixins/LoadingMixins"
import { drawerMixins } from "@/mixins/drawerMixins"
import { TableHeaderMixins } from "@/mixins/TableHeaderMixins"
import { mixins } from "@/mixins/mixins"
import currenDescriptions from "@/components/currenDescriptions"
import currenTableFlex from "@/components/currenTableFlex"
import pdf from "@/components/pdf"
import store  from '@/store'
export default {
  name: "InspectRequest",
  mixins: [
    tableMixins,
    LoadingMixins,
    drawerMixins,
    TableHeaderMixins,
    mixins,
  ],
  components: {
    currenDescriptions,
    currenTableFlex,
    pdf
  },
  data () {
    return {
      URL: 'wms/store/inspect-job',
      // tab标签值
      currentTagName:'hz',
      uploadShow: false,
      supplierShow: false,
      inspectShow: false,
      // 拆箱表格信息
      // flexTableData:[{qty:null}],
      devanForm:{qty:null},
      // 拆箱表格头部信息
      // flexTableColumns:[
      //   {type:'inputNumber', label: "数量", prop: "qty", width:"auto",min:1 },
      // ],
      devanShow:false,//拆箱弹窗
      devanLoading:false,//拆箱弹窗加载
      devanCurrentRow:null,//拆箱当条行数据
      devanCurrentPackInfo:null,//拆箱当条行箱码对应信息
      inspectNoticeDetailsShow: false,
      summaryCurrentRow:null,
      loading:false,
      // 作业指导书loading
      guideBookLoading:false,
      // 作业指导书数据
      guideBookData:{},
      // 作业指导书临时存储文件编号 防止重复请求图片
      blobName: '',
      // 主表ID
      masterID: '',
      // 明细table表中记录的rowid，方便合格不合格后数据更新
      rowId: '',
      // pdf预览路径
      urlPDF: '',
      // 纯base64（去掉data:application/pdf;base64,）
      base64PDF:'',
      // titlePDF 文件预览标题
      titlePDF: '',
      // 是否显示文件预览框
      isShowPDF: false,
      // 加载PDF
      loadingPDF: false,
      // 箱码查询输入框
      inputPackingCode: '',
      inspectNoticeDetailsTableLoading: false,
      // 检验
      inspectFormData: {
        inspectUser: null,
        uom: null,
        samplePercent: 0,
        number: null,
        otherPropertyJson: null,
        detailInspectStatus: 0,
        arriveDate: null,
        crackQty: 0,
        lot: null,
        locationErpCode: null,
        failedQty: 0,
        supplierBatch: null,
        produceDate: null,
        lastModificationTime: null,
        creationTime: null,
        lastModifierId: null,
        receiveQty: 0,
        remark: null,
        expireDate: null,
        poNumber: null,
        inspectType: 0,
        notPassedQty: 0,
        locationCode: null,
        abcClass: null,
        locationGroup: null,
        containerCode: null,
        id:  null,
        warehouseCode: null,
        creatorId: null,
        poLine: null,
        masterID: null,
        status: 0,
        goodQty: 0,
        locationArea: null,
        failedReason: null,
        itemCode: null,
        itemName: null,
        itemDesc1: null,
        itemDesc2: null,
        stdPackQty: 0,
        packingCode:null,
        inspectQty: 0,
        appearance: null,
        volume: null,
        weight: null,
        otherPropertyJson: null,
        details: [{
          name: '',
          value: ''
        }],
        // supplierPackQty: 0,
        // inspectUserPhone: "18182874811",
        // stdPackUom: null,
        // otherPropertyJson 其他属性json,
        // inspectUserEmail: null,
        // tenantId: null,
        // supplierPackUom: null,
        // inspectUserName: null,
        // receiveUom: null,
      },
      inspectForm: [
        { type: "input", label: "物品代码", prop: "itemCode", disabled: true, colSpan: 12  },
        { type: "input", label: "物品名称", prop: "itemName", disabled: true, colSpan: 12  },
        { type: "input", label: "箱码", prop: "packingCode", disabled: true, colSpan: 12 },
        { type: "select", label: "外观", prop: "appearance", options: "inspectAppearanceStatus", colSpan: 12 },
        { type: "input", label: "尺寸", prop: "volume", colSpan: 12  },
        { type: "input", label: "重量", prop: "weight", colSpan: 12  },
        { type: "input", label: "检验数量", prop: "inspectQty", colSpan: 12  },
        { type: "button", label: "其他", buttonText: "添加", click: (val) => { this.inspectAddTable(val) }, colSpan: 24  },
      ],
      inspectHandle: [
        { label: "合格", name: "hege", type:"success" },
        { label: "不合格", name: "buhege", type:"danger" },
        { label: "取消", name: "cancel" },
      ],
      inspectRules: {
        appearance: { required: true, trigger: "blur", message: "不可为空" },
        // volume: { required: true, trigger: "blur", message: "不可为空" },
        // weight: { required: true, trigger: "blur", message: "不可为空" },
        inspectQty: { required: true, trigger: "blur", message: "不可为空" },
      },
      inspectOptions:{},
      inspectDetailsTableColumns:[
        { type: "input", label: "名称", prop: "name", width:'100%' },
        { type: "input", label: "值", prop: "value", width:'100%'  },
        { type: "button", label: "删除", prop: "delete", width:'100%'  },
      ],
      //新增table表
      childTableData: [
        {
          name: null,
          value: null,
        }
      ],
      // 查看供应商质检报告相关
      // supplierFormData: {
      //   itemCode: null,
      //   itemName: null,
      //   itemDesc1: null,
      //   itemDesc2: null,
      //   stdPackUom: null,
      //   stdPackQty: null,
      //   lot: null,
      //   formFile: [],
      //   details: [{
      //     itemCode: '11111'
      //   }]
      // },
      // supplierForm: [
      //   { type: "input", label: "物品代码", prop: "itemCode", disabled: true, colSpan: 12  },
      //   { type: "input", label: "物品名称", prop: "itemName", disabled: true, colSpan: 12  },
      //   { type: "input", label: "描述", prop: "lot", disabled: true, colSpan: 12 },
      //   { type: "input", label: "外观", prop: "jysl", disabled: true, colSpan: 12  },
      //   { type: "input", label: "尺寸", prop: "jysl", disabled: true, colSpan: 12  },
      //   { type: "input", label: "重量", prop: "jysl", disabled: true, colSpan: 12  },
      // ],
      // supplierHandle: [
      //   { label: "取消", name: "cancel" },
      // ],
      // 作业指导书
      tabsDesTionsGuideBook:[
        { label: "图片", prop: "pictureBlobName", type: "uploadPictureCard", limit: 1, picExt: ".png,.jpg", },
        { label: "步骤", prop: "step", type:'textarea', rows: 5  },
      ],
      // 质检详情页面-form数据
      inspectNoticeDetailsFormData: {
        warehouseCode: localStorage.getItem('warehouseCode'),
        supplierBatch: null,
        creationTime: null,
        summaryInspectStatus: 0,
        inspectUser: null,
        uom: null,
        receiveQty: 0,
        lot: null,
        notPassedQty: 0,
        remark: null,
        itemDesc1: null,
        itemDesc2: null,
        poLine: null,
        stdPackQty: 0,
        arriveDate: null,
        goodQty: 0,
        itemCode: null,
        samplePercent: 0,
        masterID: null,
        crackQty: 0,
        inspectType: 0,
        lastModifierId: null,
        creatorId: null,
        expireDate: null,
        number: null,
        itemName: null,
        abcClass: null,
        failedReason: null,
        failedQty: 0,
        poNumber: null,
        produceDate: null,
        inspectQty: 0,
        id: null,
        inspectReport: null,
        lastModificationTime: null,
        sampleQty: 0,  // 要求检验数量
        filesList:[],
        formFile: [],
        details: [],
        // inspectUserEmail: null,
        // supplierPackQty: 0,
        // tenantId: null,
        // inspectUserName: null,
        // receiveUom: null,
        
        // goodQty: 0,
        // supplierPackUom: null,
        // inspectUserPhone: null,
        // stdPackUom: null,
      },
      // 质检详情页面-form字段
      inspectNoticeDetailsForm: [
        { type: "input", label: "物品代码", prop: "itemCode", disabled: true, colSpan: 8  },
        { type: "input", label: "物品名称", prop: "itemName", disabled: true, colSpan: 8  },
        { type: "input", label: "单位", prop: "stdPackUom", disabled: true,  colSpan: 8  },
        // { type: "input", label: "整包数量", prop: "stdPackQty", disabled: true,  colSpan: 8  },
        { type: "input", label: "生产批次", prop: "lot", disabled: true, colSpan: 8 },
        { type: "input", label: "到货数量", prop: "receiveQty", disabled: true, colSpan: 8 },
        { type: "input", label: "要求检验数量", prop: "sampleQty", disabled: true, colSpan: 8 },
        { type: "input", label: "实际质检数量", prop: "inspectQty", disabled: true, colSpan: 8 },
        { type: "input", label: "不合格数量", prop: "failedQty", disabled: true, colSpan: 8  },
        { type: "input", label: "合格数量", prop: "goodQty", disabled: true, colSpan: 8  },
        { type: "select", label: "ABC类", prop: "abcClass", options: "abcClass", clearable: true, filterable: true, disabled: true, allowCreate: true, colSpan: 8 },
        { type: "uploadList", label: "检验报告", prop: "formFile", limit: 1, picExt: ".pdf", colSpan: 12 },
      ],
      inspectNoticeDetailsRules: {
        // formFile: { required: true, trigger: "change", message: "不可为空" },
      },
      inspectNoticeDetailsEditHandle: [
        { label: "取消", name: "cancel" },
        // { label: "查看供应商质检报告", type: "info", name: "print" },
        { label: "完成质检", type: "primary", name: "determine" },
      ],
      inspectNoticeDetailsTableColumns: [
        { label: "箱码", prop: "packingCode", width:'100%' },
        { label: "物品代码", prop: "itemCode", width:'100%'  },
        { label: "物品名称", prop: "itemName", width:'100%' },
        // { label: "单位", prop: "receiveUom", width:'100%' },
        { label: "收货数量", prop: "receiveQty", width:'100%' },
        { label: "状态", prop: "detailInspectStatus", type: "filter", filters: "detailInspectStatus", width:'100%' },
        { type: "button", label: "拆箱", alwaysShow:true, width:'130px' },
        { type: "button", label: "检验", prop: "buttonHide",alwaysShow:true, width:'130px' },
        { type: "button", label: "清除检验", alwaysShow:true,width:'150px' },
      ],
      //查询质检详情-表单数据
      QueryDetailsFormData: {
        packingCode: ''
      },
      QueryDetailsForm: [
        { type: "input", label: "箱码", prop: "packingCode", colSpan: 7 },
      ],
      //常用按钮数据
      currenButtonData: [
        this.defaultFieldSettingBtn(),//字段设置
        this.defaultFreshBtn(),//刷新
        this.defaultFilterBtn(),//筛选
      ],
      // 自定义详情明细汇总等table页
      dropdownTabsData: [
        {
          label: "汇总",
          name: 'hz'
        },
        {
          label: "详情",
          name: 'xq'
        },
        {
          label: "明细",
          name: 'mx',
        }
      ],
    };
  },
  mounted () {
    this.paging();
  },
  methods: {
    // 抽屉内部按钮
    currenDrawerButtonClick(val,index, label,item){
      if(item.prop == "inspectReport"){
        // 查看检验报告
        let _file_id = JSON.parse(val.inspectReport)[0].FileKey
        this.isShowPDF = true
        if(this.loadingPDF)return
        this.loadingPDF = true
        getFilestore({blobName:_file_id}).then(res=>{
          this.urlPDF = 'data:application/pdf;base64,'+res.bytes
          this.base64PDF=res.bytes
          this.titlePDF = res.fileName
          this.loadingPDF = false
        }).catch(res=>{
          this.loadingPDF = false
        })
      }
    },
    query() {
      let findRs = ''
      if (this.inputPackingCode == '') {
        findRs = this.tableDataDetails.details.filter(item => (
          item.itemCode == this.inspectNoticeDetailsFormData.itemCode
        ))
      } else {
        findRs = this.inspectNoticeDetailsFormData.details.filter(item => (
        item.packingCode == this.inputPackingCode
        ))
      }
      this.inspectNoticeDetailsFormData.details = findRs
      
    },
    reset() {
      this.inputPackingCode = ''
      let findRs = this.tableDataDetails.details.filter(item => (
        item.itemCode == this.inspectNoticeDetailsFormData.itemCode
      ))
      this.inspectNoticeDetailsFormData.details = findRs
    },
    quicklySearchClear() {
      this.oldSkipCount = 1
      this.PageListParams.SkipCount = 0
      this.PageListParams.condition.filters = []
      this.displayDialog.detailsDialog = false
      this.paging()
    },
    quicklySearchClick(val,option){
      if (val !== '') {
        this.oldSkipCount = 1
        this.PageListParams.SkipCount = 0
        this.PageListParams.condition.filters = [
          {
            logic: "And",
            column: option.prop,
            action: "==",
            value: val
          }
        ]
        this.Loading.tableLoading = true
        getPageList(this.PageListParams, this.URL).then(res => {
          this.tableData = res.items
          this.totalCount = res.totalCount
          if (res.items.length > 0 ) {
            this.inlineDialog(res.items[0])
          } else {
            this.$errorMsg(val + '发货单没有检验任务')
          }
          this.Loading.tableLoading = false
        }).catch(err => {
          console.log(err)
          this.Loading.tableLoading = false
        })
      }
    },
    // 检验详情按钮
    buttonClick(row) {
      this.summaryCurrentRow = row
      // 判断状态为完成情况下，不可点击
      if (row.summaryInspectStatus == 2) {
        this.$message.error('已完成质检')
        return
      }
      // 展现 质检详情窗口
      this.Loading.appMainLoading = true
      setTimeout(()=>{
        this.inspectNoticeDetailsFormData.formFile = []
        this.inspectNoticeDetailsFormData = {
          warehouseCode: localStorage.getItem('warehouseCode'),
          supplierBatch: null,
          creationTime: null,
          summaryInspectStatus: 0,
          inspectUser: null,
          uom: null,
          receiveQty: 0,
          lot: null,
          notPassedQty: 0,
          remark: null,
          itemDesc1: null,
          itemDesc2: null,
          poLine: null,
          stdPackQty: 0,
          arriveDate: null,
          goodQty: 0,
          itemCode: null,
          samplePercent: 0,
          masterID: null,
          crackQty: 0,
          inspectType: 0,
          lastModifierId: null,
          creatorId: null,
          expireDate: null,
          number: null,
          itemName: null,
          abcClass: null,
          failedReason: null,
          failedQty: 0,
          poNumber: null,
          produceDate: null,
          inspectQty: 0,
          id: null,
          inspectReport: null,
          lastModificationTime: null,
          sampleQty: 0,  // 要求检验数量
          filesList:[],
          formFile: [],
          details: []
          // inspectUserEmail: null,
          // supplierPackQty: 0,
          // tenantId: null,
          // inspectUserName: null,
          // receiveUom: null,
          // goodQty: 0,
          // supplierPackUom: null,
          // inspectUserPhone: null,
          // stdPackUom: null,
        }
        this.$listAssign(this.inspectNoticeDetailsFormData, row)
        let findRs = this.tableDataDetails.details.filter(item => (
          item.itemCode == row.itemCode
        ))
        this.inspectNoticeDetailsFormData.details = findRs
        // 根据合格不合格状态控制按钮显示隐藏，item.inspectType == 1免检的隐藏
        this.inspectNoticeDetailsFormData.details.forEach(item => {
          if (item.detailInspectStatus == 2 || item.detailInspectStatus == 3 || item.inspectType == 1) {
            item.buttonHide = false
          }
        })
        // 获取要求检验数量
        this.inspectNoticeDetailsFormData.sampleQty = 0
        getListByItemcode({itemCode: row.itemCode}, 'basedata/item-quality').then(res => {
          for(var i=0;i<res.length;i++) {
            if (res[i].supplierCode == this.propsData.supplierCode) {
              // 非免检
              if (res[i].inspectType !== 1) {
                getListByItemcode({itemCode: row.itemCode}, 'basedata/AQL').then(res => {
                  for(var i=0;i<res.length;i++) {
                    if (res[i].supplierCode == this.propsData.supplierCode) {
                      if (this.inspectNoticeDetailsFormData.receiveQty >= res[i].floorQty && this.inspectNoticeDetailsFormData.receiveQty <= res[i].ceilingQty) {
                        this.inspectNoticeDetailsFormData.sampleQty = res[i].sampleQty
                        break
                      }
                    }
                  }
                  if (this.inspectNoticeDetailsFormData.sampleQty == 0) {
                    this.$alert('没有找到当前物品代码对应的质检标准！')
                  //   this.$confirm('没有找到当前物品代码对应的质检标准！, 是否继续?', '提示', {
                  //   confirmButtonText: '继续',
                  //   cancelButtonText: '取消',
                  //   type: 'warning'
                  // }).then(() => {
                  // }).catch(() => {
                  // })
                  }
                    this.loading = false
                    this.Loading.appMainLoading = false
                }).catch(err=>{
                  this.loading = false
                  this.Loading.appMainLoading = false
                })
              }
            }
          }
          this.loading = false
          this.Loading.appMainLoading = false
        }).catch(err=>{
          this.loading = false
          this.Loading.appMainLoading = false
        })
        this.inspectNoticeDetailsShow = true
      },300)
    },
    // 质检合格不合格-删除按钮
    inspectButtonClick(row, index, label) {
      this.inspectFormData.details.splice(row.$index, 1)
    },
    // 质检详情-检验按钮 table中按钮
    inspectDetailsButtonClick(row, index, label) {
      // console.log('质检详情-检验按钮 table中按钮', row)
      this.masterID = this.propsData.id
      this.inspectFormData.appearance = ''
      this.inspectFormData.volume = ''
      this.inspectFormData.weight = ''
      this.inspectFormData.inspectQty = ''
      this.inspectFormData.details = []
      this.$listAssign(this.inspectFormData, row)
      // console.log('质检详情-检验按钮 label', label)
      if(label == '拆箱'){
        this.devanCurrentRow = row
        let params = {
          condition: {
            filters: [
              {
                logic: "And",
                column: "code",
                action: "==",
                value: row.packingCode
              }
            ]
          },
          Sorting: "",
          SkipCount: 0,
          MaxResultCount: 20
        }
        this.Loading.appMainLoading = true
        // 获取箱码相关信息
        getPageList(params, "label/inventory-label").then(res => {
          this.devanCurrentPackInfo = res.items[0]
          this.Loading.appMainLoading = false
          this.devanShow = true
        }).catch(err => {
          this.$errorMsg("获取箱数据失败，请重试！")
          this.Loading.appMainLoading = false
        })
      }
      else if (label == '检验') {
        getListByItemcode({itemCode: row.itemCode}, 'basedata/item-guide-book').then(res => {
          if (res.length > 0) {
            this.guideBookData = res[0]
            this.guideBookDatePicture(res[0].pictureBlobName)
          } else {
            this.guideBookData = []
            this.blobName = ''
            document.getElementById("uploadPictureCardGuideBook").innerHTML = ''
          }
          this.inspectShow = true
        }).catch(err => {
          console.log(err)
          this.inspectShow = true
        })
        this.rowId = row.id
      } else if (label == '清除检验') {
        this.$confirm('您确定清除检验吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.inspectNoticeDetailsTableLoading = true
          setDetailDefaultOkStatus({detailId: this.inspectFormData.id}, this.masterID).then(res => {
            this.$message.success('成功清除检验！')
            // 更新数据============================================================
            // this.$listAssign(this.inspectNoticeDetailsFormData, res)
            this.inspectNoticeDetailsFormData.itemCode = res.itemCode
            this.inspectNoticeDetailsFormData.itemName = res.itemName
            this.inspectNoticeDetailsFormData.stdPackUom = res.stdPackUom
            this.inspectNoticeDetailsFormData.stdPackQty = res.stdPackQty
            this.inspectNoticeDetailsFormData.lot = res.lot
            this.inspectNoticeDetailsFormData.receiveQty = res.receiveQty
            this.inspectNoticeDetailsFormData.abcClass = res.abcClass
            this.inspectNoticeDetailsFormData.inspectQty = res.inspectQty
            this.inspectNoticeDetailsFormData.failedQty = res.failedQty
            this.inspectNoticeDetailsFormData.goodQty = res.goodQty
            this.inspectNoticeDetailsFormData.details.forEach(item => {
              if (item.id == row.id) {
                item.detailInspectStatus = 1
                delete item.buttonHide
              }
            })
            // 成功清除检验！操作后,刷新明细列表
            this.loading = false
            getDetailed(this.propsData.id, this.URL).then(res => {
              this.propsData = res
            })
            this.paging()
            this.loading = false
            this.inspectNoticeDetailsTableLoading = false
          }).catch(err => {
            console.log(err)
            this.inspectNoticeDetailsTableLoading = false
          })
        }).catch((err) => {
          console.log(err)
          this.inspectNoticeDetailsTableLoading = false
        })
      }
    },
    // 检验详情 底部按钮
    formClick(val){
      if (val[0] == 0) {
        this.inspectNoticeDetailsShow = false
      } 
      // else if (val[0] == 1) {
      //   console.log('查看供应商质检报告')
      //   this.supplierShow = true
      //   // 查询数据，根据数据动态展现行数据
      //   this.supplierForm.push({
      //     type: "input", 
      //     label: "动态", 
      //     prop: "dt", 
      //     disabled: true, 
      //     colSpan: 12  
      //   })
      // }
       else if (val[0] == 1) {
        let that = this
        that.masterID = that.propsData.id
        // 取消质检报告上传必填项
        // if (this.inspectNoticeDetailsFormData.formFile.length == 0) {
        //   this.$message.error('请上传质检报告！');
        //   return
        // }
        // 判断检验数量是否满足 要求质检数量
        // let jyslSum = 0
        // this.inspectNoticeDetailsFormData.details.forEach(element => {
        //   jyslSum += element.inspectQty == undefined?0:element.inspectQty
        // })
        if (this.inspectNoticeDetailsFormData.inspectQty < this.inspectNoticeDetailsFormData.sampleQty) {
          this.$message.error('实际检验数量小于要求检验数量，请继续检验！');
          return
        }
        this.loading = true
        // 取消质检报告上传必填项
        if (this.inspectNoticeDetailsFormData.formFile.length !== 0) {
          let rd = new FileReader(); // 创建文件读取对象
          let fileName = this.inspectNoticeDetailsFormData.formFile[0].name
          rd.readAsDataURL(this.inspectNoticeDetailsFormData.formFile[0])
          rd.onloadend = function(){
            var arrayBuffer = rd.result
            that.inspectNoticeDetailsFormData.filesList = []
            that.inspectNoticeDetailsFormData.filesList.push(
              {
                fileName: fileName,
                bytes: arrayBuffer.substring(arrayBuffer.lastIndexOf(',')+1,arrayBuffer.length)
              }
            )
            console.log(830,{id: that.masterID, summaryDetailId: that.inspectNoticeDetailsFormData.id }, that.inspectNoticeDetailsFormData)
            completeSummaryDetailStatus(
              {id: that.masterID, summaryDetailId: that.inspectNoticeDetailsFormData.id }, 
              that.inspectNoticeDetailsFormData,
            ).then(res => {
              // 更新数据============================================================
              that.inspectNoticeDetailsShow = false
              this.loading = false
              getDetailed(that.propsData.id, that.URL).then(res => {
                that.propsData = res
              })
              that.paging()
              that.$message.success('成功完成检验！')
            }).catch(err => {
              that.loading = false
              that.$message.error('检验失败，请重试！')
              console.log(err)
            })
          }
        } else {
          completeSummaryDetailStatus({id: that.masterID, summaryDetailId: that.inspectNoticeDetailsFormData.id }, that.inspectNoticeDetailsFormData).then(res => {
            // 更新数据============================================================
            that.inspectNoticeDetailsShow = false
            this.loading = false
            getDetailed(that.propsData.id, that.URL).then(res => {
              that.propsData = res
            })
            that.paging()
            that.$message.success('成功完成检验！')
          }).catch(err => {
            that.loading = false
            that.$message.error('检验失败，请重试！')
            console.log(err)
          })
        }
      }
    },
    // 供应商查看 底部按钮
    supplierFormClick(val) {
      if (val[0] == 0) {
        this.supplierShow = false
      }
    },
    // 检验 底部按钮：合格，不合格，取消
    inspectFormClick(val){
      if (val[0] == 0) {
        // 合格
        val[1].validate((valid) => {
          if (valid) {
            let otherPropertyJson = JSON.stringify(this.inspectFormData.details)
            this.inspectFormData.otherPropertyJson = otherPropertyJson
            setDetailOkStatus({id: this.masterID}, this.masterID, this.inspectFormData).then(res => {
              this.inspectShow = false
              this.$message.success('检验成功！')
              // 更新数据============================================================
              // this.$listAssign(this.inspectNoticeDetailsFormData, res)
              this.inspectNoticeDetailsFormData.itemCode = res.itemCode
              this.inspectNoticeDetailsFormData.itemName = res.itemName
              this.inspectNoticeDetailsFormData.stdPackUom = res.stdPackUom
              this.inspectNoticeDetailsFormData.stdPackQty = res.stdPackQty
              this.inspectNoticeDetailsFormData.lot = res.lot
              this.inspectNoticeDetailsFormData.receiveQty = res.receiveQty
              this.inspectNoticeDetailsFormData.abcClass = res.abcClass
              this.inspectNoticeDetailsFormData.inspectQty = res.inspectQty
              this.inspectNoticeDetailsFormData.failedQty = res.failedQty
              this.inspectNoticeDetailsFormData.goodQty = res.goodQty
              this.inspectNoticeDetailsFormData.details.forEach(item => {
                if (item.id == this.rowId) {
                  item.detailInspectStatus = 2
                  item.buttonHide = false
                }
              })
              // 检验操作后,刷新明细列表
              this.loading = false
              getDetailed(this.propsData.id, this.URL).then(res => {
                this.propsData = res
              })
              this.paging()
              this.loading = false
            }).catch(err => {
              console.log(err)
            })
          } else {
            this.$errorMsg('请按照提示继续操作')
            return false;
          }
        })
      } else if (val[0] == 1) {
        // 不合格
        val[1].validate((valid) => {
          if (valid) {
            let otherPropertyJson = JSON.stringify(this.inspectFormData.details)
            this.inspectFormData.otherPropertyJson = otherPropertyJson
            setDetailNookStatus({id: this.masterID}, this.masterID, this.inspectFormData).then(res => {
              this.inspectShow = false
              this.$message.success('检验成功！')
              // 更新数据============================================================
              // this.$listAssign(this.inspectNoticeDetailsFormData, res)
              // 汇总数据更新
              this.inspectNoticeDetailsFormData.itemCode = res.itemCode
              this.inspectNoticeDetailsFormData.itemName = res.itemName
              this.inspectNoticeDetailsFormData.stdPackUom = res.stdPackUom
              this.inspectNoticeDetailsFormData.stdPackQty = res.stdPackQty
              this.inspectNoticeDetailsFormData.lot = res.lot
              this.inspectNoticeDetailsFormData.receiveQty = res.receiveQty
              this.inspectNoticeDetailsFormData.abcClass = res.abcClass
              this.inspectNoticeDetailsFormData.inspectQty = res.inspectQty
              this.inspectNoticeDetailsFormData.failedQty = res.failedQty
              this.inspectNoticeDetailsFormData.goodQty = res.goodQty
              this.inspectNoticeDetailsFormData.details.forEach(item => {
                if (item.id == this.rowId) {
                  item.detailInspectStatus = 3
                  item.buttonHide = false
                }
              })
              // 检验操作后,刷新明细列表
              this.loading = false
              getDetailed(this.propsData.id, this.URL).then(res => {
                this.propsData = res
              })
              this.paging()
              this.loading = false
            }).catch(err => {
              console.log(err)
            })
          } else {
            this.$errorMsg('请按照提示继续操作')
            return false;
          }
        })
      } else if (val[0] == 2) {
        this.inspectShow = false
      }
      
    },
    // 检验 table添加按钮
    inspectAddTable(val) {
      this.editFormData = this.inspectFormData
      this.openAddNew()
    },
    deleteChildTable($event, scope){
      this.childTable($event, scope)
    },
    guideBookDatePicture(val) {
      if (val !== undefined && this.blobName !== val) {
        this.blobName = val
        this.guideBookLoading = true
        fileStorage({blobName: val}).then(res => {
          var byteString = atob(res.bytes)
          var arrayBuffer = new ArrayBuffer(byteString.length) // 创建缓冲数组
          var intArray = new Uint8Array(arrayBuffer) // 创建视图
          for (var i = 0; i < byteString.length; i++) {
            intArray[i] = byteString.charCodeAt(i)
          }
          const blob = new Blob([intArray], { type: '' })
          var img = new Image()
          img.width="300" 
          img.height="300"
          img.src = URL.createObjectURL(blob)
          var otest = document.getElementById("uploadPictureCardGuideBook")
          otest.appendChild(img)
          this.guideBookLoading = false
        }).catch(err => {
          console.log(err)
          this.guideBookLoading = false
        })
      }
    },
    // 上传文件查看
    uploadListView() {
      let that = this
      if (this.inspectNoticeDetailsFormData.formFile.length !== 0) {
        this.loadingPDF = true
        let pdfName = this.inspectNoticeDetailsFormData.formFile[0].name
        var reader =  new FileReader()
        reader.readAsDataURL(this.inspectNoticeDetailsFormData.formFile[0])
        reader.onload = function () {
          that.urlPDF = reader.result
          that.titlePDF = pdfName
          that.isShowPDF = true
          that.loadingPDF = false
        }
      } else {
        this.$message('请先上传文件！')
        return
      }

    },
    closePDF(){
      this.isShowPDF = false
      this.urlPDF = ''
      this.titlePDF = ''
      this.loadingPDF = false
    },
    //设置指定行、列、具体单元格颜色
    cellClassName({row, column, rowIndex, columnIndex}){
      if (row.detailInspectStatus == 1 && columnIndex === 5) {
        return 'cell-class-mrhg' //默认合格
      } else if (row.detailInspectStatus == 2 && columnIndex === 5) {
        return 'cell-class-hg'//合格
      } else if (row.detailInspectStatus == 3 && columnIndex === 5) {
        return 'cell-class-nohg'//不合格
      }else{
        return ''
      }
    },
    currenTabsChange(row){
      this.currentTagName = row.name
    },
    // 拆箱事件
    postSplitPackingHandle(newPackData){
      this.devanLoading = true
      let _data = {
        useOnTheWayLocation: false,
        requestNumber: null,
        worker: store.getters.name.userName,
        jobNumber: null,
        remark: null,
        extraProperties: this.devanCurrentRow.extraProperties || null,
        activeDate: new Date(),
        confirmed: true,
        confirmTime: new Date(),
        details: [{
          fromLocationCode: this.devanCurrentRow.locationCode,
          fromLocationErpCode: this.devanCurrentRow.locationErpCode,
          fromLot: this.devanCurrentRow.lot,
          fromPackingCode: this.devanCurrentRow.packingCode,
          fromWarehouseCode: this.devanCurrentRow.warehouseCode,
          itemCode: this.devanCurrentRow.itemCode,
          itemName: this.devanCurrentRow.itemName,
          toLocationCode: this.devanCurrentRow.locationCode,
          toLocationErpCode: this.devanCurrentRow.locationErpCode,
          toLot: this.devanCurrentRow.lot,
          toPackingCode: newPackData[0].code,
          toWarehouseCode: this.devanCurrentRow.warehouseCode,
          uom: this.devanCurrentRow.uom,
          itemDesc1: this.devanCurrentRow.itemDesc1,
          onTheWayLocationCode: "",
          expireDate: this.devanCurrentRow.expireDate,
          fromLocationArea: this.devanCurrentRow.locationArea,
          itemDesc2: this.devanCurrentRow.itemDesc2,
          fromLocationGroup: this.devanCurrentRow.locationGroup,
          toLocationArea: this.devanCurrentRow.locationArea,
          reason: null,
          fromStatus: this.devanCurrentRow.status,
          stdPackQty: this.devanCurrentRow.stdPackQty,
          arriveDate: this.devanCurrentRow.arriveDate,
          toContainerCode: this.devanCurrentRow.containerCode,
          produceDate: this.devanCurrentRow.produceDate,
          supplierBatch: this.devanCurrentRow.supplierBatch,
          toStatus: this.devanCurrentRow.status,
          toLocationGroup: this.devanCurrentRow.locationGroup,
          qty: Number(this.devanForm.qty),
          remark: null,
          fromContainerCode: this.devanCurrentRow.containerCode,
        }],
        type: "SplitPacking"
      }
      postSplitPacking(_data)
        .then(res=>{
          // todo:拆分成功后，重新获取列表数据验证
          this.devanCancelHandel()
          let _url = this.detailURL ? this.detailURL : this.URL
          getDetailed(this.propsData.id, _url).then(res => {
            // 前端分页处理
            this.tableDataDetails = JSON.parse(JSON.stringify(res))
            let linshiTableDataDetails = JSON.parse(JSON.stringify(this.tableDataDetails))
            this.totalCountDetails = res.details.length
            // 删除除当前页面最大数以外数据
            linshiTableDataDetails.details.splice(this.MaxResultCountDetails,this.totalCountDetails); 
            this.propsData = linshiTableDataDetails
            this.buttonClick(this.summaryCurrentRow)
            this.devanLoading = false
          }).catch(err => {
            this.devanLoading = false
          })
        })
        .catch(err=>{

        })
    },
    // 拆箱取消
    devanCancelHandel(){
      this.devanForm = {qty:null}
      this.devanShow = false
      this.devanLoading = false
    },
    // 拆箱确定
    devanSureHandel(){
      // if(this.flexTableData.length <= 0){
      //   this.$errorMsg("请添加拆箱数据")
      //   return
      // }
      // let _noNumber = 0
      // let _allNumber = 0
      // // 拆箱数量最大值限制
      // this.flexTableData.forEach(item=>{
      //   if(!item.qty || item.qty == 0){
      //     _noNumber ++
      //   }else{
      //     _allNumber += Number(item.qty)
      //   }
      // })
      // if(Number(_noNumber) > 0){
      //   this.$errorMsg(`单条拆分数量必须大于0，请修改数量`)
      //   return
      // }
      // if(Number(_allNumber) > Number(this.devanCurrentRow.goodQty)){
      //   this.$errorMsg(`拆箱总数必须小于${this.devanCurrentRow.goodQty}，请修改数量`)
      //   return
      // }
      if(!this.devanForm.qty || Number(this.devanForm.qty) <=0 || Number(this.devanForm.qty) >= Number(this.devanCurrentRow.receiveQty)){
        this.$errorMsg(`拆箱数必须大于0且小于${this.devanCurrentRow.receiveQty}，请修改数量`)
        return
      }
      // 先生成箱码
      let _creatPackData = {
        itemCode: this.devanCurrentPackInfo.itemCode || null,
        itemName: this.devanCurrentPackInfo.itemName || null,
        itemDesc1: this.devanCurrentPackInfo.itemDesc1 || null,
        itemDesc2: this.devanCurrentPackInfo.itemDesc2 || null,
        lot: this.devanCurrentPackInfo.lot || null,
        supplierBatch: this.devanCurrentPackInfo.supplierBatch || null,
        arriveDate: this.devanCurrentPackInfo.arriveDate || null,
        produceDate: this.devanCurrentPackInfo.produceDate || null,
        expireDate: this.devanCurrentPackInfo.expireDate || null,
        stdPackQty: Number(this.devanCurrentPackInfo.stdPackQty) || 0,
        uom: this.devanCurrentPackInfo.uom || null,
        qty: Number(this.devanForm.qty),
        labelStatus: this.devanCurrentPackInfo.labelStatus,//标签状态
        recommendLocationCode: this.devanCurrentPackInfo.recommendLocationCode || null,
        locationErpCode: this.devanCurrentPackInfo.locationErpCode || null,
        containerCode: this.devanCurrentPackInfo.containerCode || null,
        supplierCode: this.devanCurrentPackInfo.supplierCode || null,
        poNumber: this.devanCurrentPackInfo.poNumber || null,
        rpNumber: this.devanCurrentPackInfo.rpNumber || null,
        asnNumber: this.devanCurrentPackInfo.asnNumber || null,
        qLevel: this.devanCurrentPackInfo.qLevel || null,
        qualityFile: this.devanCurrentPackInfo.qualityFile || null,
        prodLine: this.devanCurrentPackInfo.prodLine || null,
        team: this.devanCurrentPackInfo.team || null,
        shift: this.devanCurrentPackInfo.shift || null,
        specifications:  this.devanCurrentPackInfo.specifications || null,
        supplierName: this.devanCurrentPackInfo.supplierName || null,
        supplierSimpleName: this.devanCurrentPackInfo.supplierSimpleName || null,
        supplierItemCode: this.devanCurrentPackInfo.supplierItemCode || null,
        supplierItemName: this.devanCurrentPackInfo.supplierItemName || null,
        labelType: this.devanCurrentPackInfo.labelType || null,
        planArriveDate: this.devanCurrentPackInfo.planArriveDate || null,
        remark:null,
      }
      // 生成标签（接口）
      this.devanLoading = true
      postInventoryLabelCode_count({count:1}, _creatPackData)
        .then(res => {
          this.postSplitPackingHandle(res)
        })
        .catch(err => {
          this.devanLoading = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../../styles/mainbasicData.scss";
::v-deep .handleForm {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .el-form {
    justify-content: flex-start;
    align-content: flex-start;
    flex-wrap: wrap;
    overflow: hidden;
    overflow-y: auto;
    height: 100%;
  }
  .el-table {
    height: 220px !important;
  }
  .formButton {
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-bottom: 15px;
  }
}
::v-deep .jyTable{
  .el-form-item{
    margin-bottom: 0 !important;
  }
}
.formButton {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
::v-deep {
  .el-form-item{
    margin-bottom: 15px !important;
  }
  .drawer-main{
    .el-form-item {
      margin-bottom: 0 !important;
    } 
  }    
}
::v-deep .formTable-box {
  height: calc(100% - 270px) !important;
  .el-form-item{
    margin-bottom: 0 !important;
  }
  
  .el-form-item__content {
    margin: 0 !important;
    height: 100% !important;
      .el-table {
        height: 100% !important;
      }
  }
}
::v-deep .cell-class-mrhg{
  background:#42a9b9 !important;
  color:#fff !important
}
::v-deep .cell-class-hg{
  background:#42b983 !important;
  color:#fff !important
}
::v-deep .cell-class-nohg{
  background:#c3503e !important;
  color:#fff
}
</style>
<style lang="scss">
.upload-demo {
  .el-upload-list.el-upload-list--text {
    float: right !important;
    margin-right: 200px !important;
  }
}
</style>