<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">{{ funTitle }}</div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:ckOrders:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single || isAudit != 0"
            @click="handleUpdate"
            v-hasPermi="['system:ckOrders:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple || isAudit != 0"
            @click="handleDelete"
            v-hasPermi="['system:ckOrders:remove']"
          >删除
          </el-button>
        </el-col>


        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-thumb"
            size="mini"
            :disabled="multiple || isAudit != 0 "
            @click="selectAuditPerson"
            v-hasPermi="['system:ckOrders:remove']"
          >提交审核
          </el-button>
        </el-col>


        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-printer"
            size="mini"
            :disabled="multiple"
            @click="println()"
            v-hasPermi="['system:ckOrders:remove']"
          >打印
          </el-button>
        </el-col>


        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleEnable"
            v-hasPermi="['system:ckOrders:edit']"
          >恢复
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDisabled"
            v-hasPermi="['system:ckOrders:remove']"
          >作废
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:ckOrders:export']"
          >导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:ckOrders:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >刷新
          </el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            icon="el-icon-info"
            size="mini"
            :disabled="single"
            @click="sendNotice">发送通知单消息
          </el-button>
        </el-col> -->

        <!--        <el-col :span="1.5">
                  <el-button
                    icon="el-icon-info"
                    size="mini"
                    :disabled="single"
                    @click="sendIwms">发送iwms
                  </el-button>
                </el-col>-->

        <right-toolbar
          ref="toolBarRef"
          @customCols="customColsHandler"
          :showSearch.sync="showSearch"
          showColumnsType="transfer"
          :columns="columns"
        ></right-toolbar>
      </el-row>
    </div>

    <div class="search-container" ref="searchPanel">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="mini"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="来源单号" prop="deliveryId">
          <el-input
            v-model="queryParams.deliveryId"
            placeholder="请输入来源单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>


        <!-- <el-form-item label="仓库编号" prop="storageId">
          <el-input
            v-model="queryParams.storageId"
            placeholder="请输入仓库编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="库区编号" prop="storageAreaId">
          <el-input
            v-model="queryParams.storageAreaId"
            placeholder="请输入库区编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="出库类型" prop="ckType">
          <el-select
            v-model="queryParams.ckType"
            placeholder="请选择出库类型"
            clearable
            :disabled="ckTypeMasterEnabled"
          >
            <el-option
              v-for="dict in dict.type.outbound_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请人" prop="applicant">
          <el-input
            v-model="queryParams.applicant"
            placeholder="请输入申请人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="isAudit">
          <el-select
            v-model="queryParams.isAudit"
            placeholder="请选审核状态"
            clearable>
            <el-option
              v-for="dict in dict.type.is_audit"
              :key="dict.label"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库名称" prop="storageShortName">
          <el-input
            v-model="queryParams.storageShortName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

      </el-form>
    </div>
    <div class="table-container">
      <div ref="mainTablePanel" :style="{ height: mainTableDivHeight }">
        <el-table
          :key="rndKey"
          ref="providerTableRef"
          v-loading="loading"
          border
          :stripe="false"
          size="mini"
          :height="mainTableHeight"
          :data="ckOrdersList"
          @selection-change="handleSelectionChange"
          @header-dragend="handleHeaderDragEnd"
          @row-click="handleMainTableClick"
          :row-style="rowStyle"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column
            v-for="item in columns"
            :key="item.seq"
            :label="item.label"
            align="center"
            :prop="item.columnName"
            v-if="item.visible"
            :filters="item.filters"
            :filter-method="filterHandler"
            :width="item.width"
            sortable
          >
            <template v-slot="scope">
              <dict-tag
                v-if="item.columnName === 'confirmStatus'"
                v-slot="scope"
                :options="dict.type.out_status"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'isAudit'"
                v-slot="scope"
                :options="dict.type.is_audit"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'status'"
                v-slot="scope"
                :options="dict.type.common_status"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'ckType'"
                v-slot="scope"
                :options="dict.type.outbound_type"
                :value="scope.row[item.columnName]"
              />
              <!-- <span v-else-if="item.columnName === 'createTime'">
                {{ scope.row[item.columnName] }}
              </span> -->
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </template>
          </el-table-column>

          <!--          <el-table-column
                      label="操作"
                      align="center"
                      width="100"
                      fixed="right"
                      class-name="small-padding fixed-width"
                    >
          &lt;!&ndash;            handleMainAuditTableClick(scope.row)&ndash;&gt;
                      <template slot-scope="scope">
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-detail"
                          @click="selectAuditPerson(scope.row)"
                          :disabled="scope.row.isAudit != '0' && scope.row.isAudit != '3'"
                        >提交审核
                        </el-button>
                      </template>
                    </el-table-column>-->
        </el-table>
        <div class="pagePanel">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>

      <div ref="subTablePanel" :style="{ height: subTableDivHeight }">
        <el-row class="mb5">
          <label class="subTableTitle"
          ><i class="el-icon-notebook-1"/>{{ funTitle }}申请单
            <span style="margin-left: 10px; font-size: 13px"
            >(来源单号：{{ deliveryId }})</span
            ></label
          >
        </el-row>
        <el-row :gutter="5" class="mb5">
          <el-col :span="1.5">
            <el-button
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTCkOrderdetail"
              :disabled="isAudit"
            >添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-check"
              size="mini"
              @click="handleSaveTCkOrderdetail"
              :disabled="
                checkedTCkOrderdetail.length <= 0 ||
                disableUpdate
              "
            >保存
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              icon="el-icon-remove"
              size="mini"
              @click="confirmOut"
              :disabled="!isAudit"
            >出库
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteTCkOrderdetail"
              :disabled="
                checkedTCkOrderdetail.length <= 0 ||
                isAudit != 0 ||
                disableUpdate
              "
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-search" size="mini" @click="handleSubQuery"
            >搜索
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-refresh" size="mini" @click="resetSubQuery"
            >刷新
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-select
              v-model="storageId"
              filterable
              placeholder="选择仓库"
              @change="mxStash">
              <el-option
                v-for="storage in storageList"
                :key="storage.storageId"
                :label="storage.storageShortName"
                :value="storage.storageId">
              </el-option>
            </el-select>
          </el-col>


          <el-col :span="1.5">
            <el-select v-model="ckType" :disabled="true" placeholder="出库类型">
              <el-option
                v-for="dict in dict.type.outbound_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <div class="search-container" ref="subSearchPanel">
          <el-form
            :model="querySubParams"
            ref="querySubForm"
            size="mini"
            :inline="true"
            v-show="showSubSearch"
            label-width="75px"
          >
          </el-form>
        </div>
        <el-table
          border
          size="mini"
          :data="tckOrderdetailList"
          :row-class-name="rowTCkOrderdetailIndex"
          @selection-change="handleTCkOrderdetailSelectionChange"
          ref="tCkOrderdetail"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
            :selectable="selectable"
          />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <!-- <el-table-column label="子需求编号" prop="businessId" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.businessId"
                placeholder="请输入子需求编号"
              />
              <span v-else>{{ scope.row.businessId }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="物料编号" prop="goodsId" width="160">
            <template slot="header">
              <span style="color: red;">*</span> 物料编号
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.addFlg">
                <el-input
                  v-model="scope.row.goodsId"
                  placeholder="物料编号"
                  style="width: 85% !important"
                  disabled
                />
                <el-button
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleRowGoodsSelect(scope.row)"
                  style="border: none; width: 15%; padding-left: 3px"
                ></el-button>
              </div>
              <span v-else>{{ scope.row.goodsId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="goodsName" width="200">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.goodsName"
                placeholder="物料名称"
                disabled
              />
              <span v-else>{{ scope.row.goodsName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="子需求编号" prop="businessId" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.businessId"
                placeholder="子需求编号"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="specification" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.specification"
                placeholder="规格"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="库级" prop="levelType" width="150">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.levelType"
                placeholder="请选择库级"
                clearable
                disabled
              >
                <el-option
                  v-for="dict in dict.type.data_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" prop="storageShortName" width="200">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.storageShortName"
                placeholder="所在仓库"
                disabled
              />
              <span v-else>{{ scope.row.storageShortName }}</span>
            </template>
          </el-table-column>

          <!--          <el-table-column label="所在仓库" prop="storageId" width="200">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-input-->
          <!--                v-if="scope.row.addFlg"-->
          <!--                v-model="scope.row.storageId"-->
          <!--                placeholder="所在仓库"-->
          <!--                disabled-->
          <!--              />-->
          <!--              <span v-else>{{ scope.row.storageId }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

          <el-table-column label="所在容器" prop="ctl" width="200">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.ctl"
                placeholder="所在容器"
                disabled
              />
              <span v-else>{{ scope.row.ctl }}</span>
            </template>
          </el-table-column>

          <el-table-column label="库位" prop="locationId" width="200">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.locationId"
                placeholder="库位"
                disabled
              />
              <span v-else>{{ scope.row.locationId }}</span>
            </template>
          </el-table-column>

          <el-table-column label="库存数量" prop="stockNum" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.stockNum"
                placeholder="请输入库存数量"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="已出库数量" prop="callShelvesNum" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.callShelvesNum"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column
            label="需求数量"
            prop="shelvesNum"
            width="150"
          >
            <template slot="header">
              <span style="color: red;">*</span> 需求数量
            </template>
            <template slot-scope="scope">
              <el-input-number
                :min="0"
                v-if="scope.row.editFlg"
                v-model="scope.row.shelvesNum"
                placeholder="0"
              />
              <span v-else>{{ scope.row.shelvesNum }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column label="已出库数量" prop="pickNum" width="150">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.pickNum" placeholder="0" disabled/>
                      </template>
                    </el-table-column>
                    <el-table-column label="拣选数量" prop="trNum" width="150">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.trNum" placeholder="0" disabled/>
                      </template>
                    </el-table-column>-->
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                placeholder="备注"
              />
            </template>
          </el-table-column>

          <el-table-column label="单价" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                disabled
              />
            </template>
          </el-table-column>

          <!--          <el-table-column label="总价" prop="totalMoney" width="150">
                      <template slot-scope="scope">
                        <el-input
                          v-model="scope.row.totalMoney"
                          disabled
                        />
                      </template>
                    </el-table-column>-->

          <el-table-column label="关联设备" prop="equipment" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.equipment"
                placeholder=""
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="物资流向" prop="goodsTo" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.goodsTo"
                placeholder=""
                disabled
              />
            </template>
          </el-table-column>

          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.goods_unit"
                :value="scope.row.unit"
              />
              <!-- <el-select v-model="scope.row.unit" placeholder="请选择单位">
                <el-option
                  v-for="dict in dict.type.goods_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select> -->
            </template>
          </el-table-column>
          <el-table-column label="确认状态" align="center" prop="confirmStatus">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.out_status"
                :value="scope.row.confirmStatus"
              />
            </template>
          </el-table-column>

          <!--          <el-table-column label="物料分类" prop="goodsTypeId" width="150">
                      <template slot-scope="scope">
                        <el-input
                          v-model="scope.row.goodsTypeId"
                          placeholder="物料分类"
                          disabled
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="供应商" prop="providerId" width="150">
                      <template slot-scope="scope">
                        <el-input
                          v-model="scope.row.providerId"
                          placeholder="请输入供应商"
                          disabled
                        />
                      </template>
                    </el-table-column>-->


          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="!scope.row.editFlg"
                @click="handleRowEdit(scope.row, '1')"
                :disabled="disableUpdate"
              >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.editFlg"
                @click="handleRowEdit(scope.row, '0')"
                :disabled="disableUpdate"
              >取消编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加或修改出库对话框 -->
    <el-dialog
      id="dialog-audit"
      title="选择审核人"
      :visible.sync="auditOpen"
      width="450px"
      append-to-body
    >
      <div class="edit-container">
        <el-form ref="form" :model="auditForm" :rules="rules" label-width="85px">
          <el-form-item label="第一审核人">
            <el-select
              v-model="auditForm.person1"
              placeholder="请选择"
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="item in personList1"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="第二审核人">
            <el-select v-model="auditForm.person2" placeholder="请选择" size="small" style="width: 240px">
              <el-option
                v-for="item in personList2"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="  ">
            <el-button type="primary" @click="addAudit" :disabled="disabledAudit" icon="el-icon-plus"></el-button>
          </el-form-item>
          <el-form-item label="第三审核人" v-show="showThird">
            <el-select
              v-model="auditForm.person3"
              filterable
              remote
              reserve-keyword
              placeholder="请选择"
              :remote-method="remoteMethod"
              :loading="auditLoading"
              size="small" style="width: 240px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="原因" v-show="showThird">
            <el-input
              v-model="auditForm.why"
              placeholder="请输入原因"
              type="textarea"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改出库对话框 -->
    <el-dialog
      id="dialog-container"
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="来源单号" prop="deliveryId">
                <el-input v-model="form.deliveryId = generateUniqueId()" placeholder="请输入来源单号" disabled/>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="仓库编号" prop="storageId">
                <el-input
                  v-model="form.storageId"
                  placeholder="请输入仓库编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="库区编号" prop="storageAreaId">
                <el-input
                  v-model="form.storageAreaId"
                  placeholder="请输入库区编号"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="出库类型" prop="ckType">
                <el-select v-model="ckType">
                  <el-option
                    v-for="dict in dict.type.outbound_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="申请人" prop="applicant">
                <el-input v-model="form.applicant" placeholder="请输入申请人"/>
              </el-form-item>
            </el-col>

            <!--           <el-col :span="6">-->
            <!--              <el-form-item label="操作人" prop="deliveryId">-->
            <!--                <el-input v-model="form.deliveryId = generateUniqueId()" placeholder="请输入来源单号" disabled/>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <!--            <el-col :span="12">
                          <el-form-item label="agv执行" prop="isAvgExec">
                            <el-radio-group v-model="form.isAvgExec">
                              <el-radio :label="1">是</el-radio>
                              <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                          </el-form-item>
                        </el-col>-->
          </el-row>
          <!-- <el-row> -->
          <!-- <el-col :span="6">
              <el-form-item label="出库方式" prop="deliveryMethod">
                <el-input
                  v-model="form.deliveryMethod"
                  placeholder="请输入出库方式"
                />
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="收货人备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option
                    v-for="dict in dict.type.common_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="审核人" prop="auditMan">
                <el-input v-model="form.auditMan" placeholder="请输入审核人" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="6">
              <el-form-item label="审核时间" prop="auditDate">
                <el-date-picker
                  clearable
                  v-model="form.auditDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择审核时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="订单来源" prop="orderSource">
                <el-input
                  v-model="form.orderSource"
                  placeholder="请输入订单来源"
                />
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="站台" prop="outStand">
                <el-input v-model="form.outStand" placeholder="请输入站台" />
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="订单类型" prop="orderType">
                <el-select
                  v-model="form.orderType"
                  placeholder="请选择订单类型"
                >
                  <el-option
                    v-for="dict in dict.type.outbound_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          <!-- </el-row> -->
          <!--   <el-row>
            <el-col :span="6">
              <el-form-item label="确认状态" prop="confirmStatus">
                <el-select
                  v-model="form.confirmStatus"
                  placeholder="请选择确认状态"
                >
                  <el-option
                    v-for="dict in dict.type.out_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="操作人" prop="recordPerson">
                <el-input
                  v-model="form.recordPerson"
                  placeholder="请输入操作人"
                />
              </el-form-item>
            </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="申请人" prop="applicant">
                <el-input v-model="form.applicant" placeholder="请输入申请人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="操作时间" prop="recordDate">
                <el-date-picker
                  clearable
                  v-model="form.recordDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择操作时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>-->
          <!-- <el-row>
            <el-col :span="6">
              <el-form-item label="生产订单号" prop="productId">
                <el-input
                  v-model="form.productId"
                  placeholder="请输入生产订单号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工位" prop="stationId">
                <el-input v-model="form.stationId" placeholder="请输入工位" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="任务号" prop="taskId">
                <el-input v-model="form.taskId" placeholder="请输入任务号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="下单时间" prop="orderDate">
                <el-input
                  v-model="form.orderDate"
                  placeholder="请输入下单时间"
                />
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row> </el-row> -->
        </el-form>
      </div>
      <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">
      <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" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的通知单数据
          <el-link
            type="primary"
            style="font-size: 12px"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </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>
    <StockSelect ref="goodsSelect" :storageIdFrom="storageId"></StockSelect>
    <print-page v-if="data" :data="data" ref="ticket"/>
  </div>

</template>
<script>
import {
  addCkOrders,
  auditCkOrders,
  changeStatus,
  confirmOut,
  delCkOrderDetails,
  delCkOrders,
  disabled,
  enabled,
  getCkOrders,
  listCkOrders,
  updateCkOrders,
  updateTckOrderDetails,
  create
} from "@/api/system/ckOrders";
import {listCOLUMN} from "@/api/system/column";
import {listOrderdetail} from "@/api/system/orderdetail";
import {selectStorageList} from "@/api/system/storage";
import {queryUserList, queryAuditUserList} from '@/api/system/user';
import TableMixin from "@/api/tableMixin";
import {getToken} from "@/utils/auth";
import StockSelect from "@/views/system/dialog/StockSelect";
import PrintPage from '@/views/system/print/PrintPage.vue'; // 确保路径正确
export default {
  name: "CkOrders",
  components: {
    StockSelect,
    'print-page': PrintPage
  },
  mixins: [TableMixin],
  dicts: [
    "out_status",
    "goods_unit",
    "common_status",
    "outbound_type",
    "is_audit",
    "data_source"
  ],
  data() {
    return {

      //打印数据
      data: {},
      rndKey: 0,
      dialogVisible: false,
      // 遮罩层
      loading: true,
      //托盘号
      ctlNo: '',
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTCkOrderdetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示搜索条件
      showSubSearch: true,
      // 总条数
      total: 0,
      //明细总条数
      subTotal: 0,
      // 出库表格数据
      ckOrdersList: [],
      // 出库物料明细表格数据
      tckOrderdetailList: [],
      storageList: [],
      //是否审核
      isAudit: false,
      disabledAudit: false,
      //
      shouldPrint: false,
      selectedRowId: '',

      //明细编辑按钮
      disableUpdate: false,
      id: 0,
      orderId: "",
      // 仓库Id
      storageId: "",
      // 库区ID
      storageAreaId: "",
      // 出库类型
      ckType: "",
      //主表下拉是否可用
      ckTypeMasterEnabled: true,
      ckTypeEnabled: true,
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      subTableDivHeight: "0px",
      businessCodeTrk: "ckOrders",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      deliveryId: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        deliveryId: null,
        storageId: null,
        storageAreaId: null,
        ckType: null,
        status: null,
        auditMan: null,
      },
      // 查询子表参数
      querySubParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        businessId: null,
        goodsId: '',
        goodsName: null,
        providerId: null,
        specification: null,
      },
      // 表单参数
      form: {
        isAvgExec: 0,
        ckType: '0',
        deliveryId: "",
        applicant: "",
      },
      auditOpen: false,
      //审核人
      auditForm: {
        person1: "",
        person2: "",
        person3: "",
        why: "",
      },
      auditRow: {},
      //候选人
      personList1: [],
      personList2: [],
      personList3: [],
      //第三审核人搜索条件
      userName: "",
      auditLoading: false,
      showThird: false,
      options: [],
      // 表单校验
      rules: {
        deliveryId: [
          {required: true, message: "来源单号不能为空", trigger: "blur"},

        ],
        /*isAvgExec: [
          {required: true, message: "请选择", trigger: "blur"},
        ]*/
      },
      columns: [],
      subColumns: [],
      //选中的仓库id
      stash: '',
      //判断是否有一级库
      isFirst: false,
      //
      agv: [],

      //选中的数据单据
      datas: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/ckOrders/importData",
      },
      printList: [],
      selectedRows: []
    };
  },
  created() {
    this.form.applicant = this.nickName();
    this.getStorageList();
    this.getAuditUserList();
    // 生产领用
    if (this.$route.path.indexOf("useProduction") > -1) {
      this.ckType = "1";
      this.funTitle = "领料";
    } else if (this.$route.path.indexOf("purchaseReturn") > -1) {
      // 采购退货
      this.ckType = "2";
      this.funTitle = "一级库退货";
      this.title = '采购退货出库'
    } else if (this.$route.path.indexOf("transferOut") > -1) {
      // 挑拨出库
      this.ckType = "3";
      this.funTitle = "调拨出库";
    } else if (this.$route.path.indexOf("scrapOut") > -1) {
      // 报废出库
      this.ckType = "4";
      this.funTitle = "报废出库";
    } else if (this.$route.path.indexOf("deliveryOut") > -1) {
      // 寄存出库
      this.ckType = "6";
      this.funTitle = "VMI出库";
    } else if (this.$route.path.indexOf("deliveryReturnOut") > -1) {
      // 寄存退货出库
      this.ckType = "7";
      this.funTitle = "VMI退货";
    } else {
      // 出库可选择
      this.ckTypeMasterEnabled = false;
      this.ckType = "";
      this.funTitle = "出库";
      this.ckTypeEnabled = false;
    }

    // 出库类型
    this.queryParams.ckType = this.ckType;
    this.form.ckType = this.ckType;
    this.$nextTick(() => {
      // 确保 DOM 更新
      console.log('Updated DOM');
      this.form.ckType = this.ckType;
      console.log(this.form.ckType, '1232')
    });
    this.getList();
  },
  mounted() {
    this.computedTableHeight();
    this.generateFilters();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo
    },
    searchHeight() {
      return this.$refs.searchPanel.clientHeight;
    },
  },
  methods: {
    generateUniqueId() {
      const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      const date = new Date();
      const uniqueId = date.getTime().toString(36).toUpperCase();
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      const timeString = hours + minutes + seconds;
      const randomLetter = letters.charAt(Math.floor(Math.random() * letters.length));
      return uniqueId + timeString + randomLetter;
    },
    nickName() {
      return this.$store.state.user.nickName;
    },
    //获取用户
    getThirdUserList(query) {
      console.log("query userlist ", query)
      console.log("this.person3 ", this.auditForm.person3)
      if (query == "" || query.trim() == "") {
        return;
      }
      queryUserList({userName: query}).then((response) => {
        console.log(response)
        this.options = [];
        if (response.code == 200) {
          let _this = this;
          response.data.forEach((element) => {
            let obj = {};
            console.log(element.dept)
            obj.label = element.dept.deptName + '--' + element.nickName;
            obj.value = element.userName;
            _this.options.push(obj);
          });
        } else {
          this.$modal.msgError("查询用户失败");
        }
      });
    },
    addAudit() {
      this.showThird = true;
      this.disabledAudit = true;
      // this.getThirdUserList();
    },
    remoteMethod(query) {
      if (query !== '') {
        this.auditloading = true;
        let _this = this;
        setTimeout(() => {
          _this.auditloading = false;
          _this.getThirdUserList(query);
        }, 200);
      } else {
        this.options = [];
      }
    },
    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      this.columns.forEach((obj) => {
        if (obj.columnName === column.property) obj.width = newWidth;
      });
      this.$refs.toolBarRef.saveConfig(this.columns);
    },
    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },
    removeDuplicateNames(auditManString) {
      if (!auditManString) {
        return ""; // 如果字符串为空或 null，则返回空字符串
      }

      const names = auditManString.split("->");
      const uniqueNames = [];
      const seenNames = new Set();

      for (const name of names) {
        if (!seenNames.has(name)) {
          uniqueNames.push(name);
          seenNames.add(name);
        }
      }

      return uniqueNames.join("->");
    },
    getAuditUserList() {
      console.log("query getAuditUserList ")
      queryAuditUserList({}).then((response) => {
        console.log(response)
        if (response.code == 200) {
          this.personList1 = [];
          this.personList2 = [];
          let _this = this;
          console.log(response.data)
          response.data.audit1.forEach((element) => {
            _this.personList1.push(element);
          });
          response.data.audit2.forEach((element) => {
            _this.personList2.push(element);
          });
        } else {
          //this.$modal.msgError("查询仓库失败");
        }
      });
    },
    handleRowGoodsSelect(row) {
      const callBack = (item) => {
        console.log("item:", item)
        row.goodsId = `${item.goodsId}`;
        row.goodsName = `${item.goodsName}`;
        row.goodsTypeId = `${item.goodsTypeId}`;
        row.unit = `${item.unit}`;
        row.recoil = `${item.recoil}`;
        row.specification = `${item.specification}`;
        row.providerId = `${item.providerId}`;
        row.stockNum = `${item.shelvesNum}`;
        row.storageShortName = `${item.storageShortName}`;
        row.storageId = `${item.storageId}`;
        row.ctl = `${item.ctl}`;
        row.price = `${item.price}`;
        row.levelType = `${item.levelType}`;
        row.callShelvesNum = `${item.totalNetWeigh}`;
        row.businessId = `${item.salesOrderNumber}`;
        row.locationId = `${item.locationId}`;
      };
      this.$refs.goodsSelect.showModal(callBack);

    },

    /* handleRowGoodsSelect() {
       console.log("4444", this.storageId);
       const callBack = (selectedItems) => {
         // 删除最初的空表格行，假设它总是在数组的第一个位置
         if (
           this.tckOrderdetailList.length > 0 &&
           this.tckOrderdetailList[0].goodsId === ""
         ) {
           this.tckOrderdetailList.shift();
         }

         selectedItems.forEach((item) => {
           let newRow = {
             goodsId: `${item.goodsId}`,
             goodsName: `${item.goodsName}`,
             goodsTypeId: `${item.goodsTypeId}`,
             unit: `${item.unit}`,
             recoil: `${item.recoil}`,
             specification: `${item.specification}`,
             providerId: `${item.providerId}`,
             stockNum: `${item.shelvesNum}`,
             // 添加默认值
             businessId: "", // 示例默认值，根据需要修改
             locationId: "", // 示例默认值，根据需要修改
             storageId: "", // 示例默认值，根据需要修改
             shelvesNum: "", // 示例默认值，根据需要修改
             goodsNum: "", // 示例默认值，根据需要修改
             callShelvesNum: "", // 示例默认值，根据需要修改
             remark: "", // 示例默认值，根据需要修改
             price: "", // 示例默认值，根据需要修改
             storageAreaId: "", // 示例默认值，根据需要修改
             pickNum: "0", // 默认拣货数量
             trNum: "0", // 默认转运数量
             status: "", // 示例默认值，根据需要修改
             confirmStatus: "", // 示例默认值，根据需要修改
             taskId: "", // 示例默认值，根据需要修改
             addFlg: true,
             editFlg: true,
             isNewRecord: true,
           };
           this.tckOrderdetailList.push(newRow);
         });
       };
       this.$refs.goodsSelect.showModal(callBack);
     },*/
    /** 查询仓库列表 */
    getStorageList() {
      selectStorageList({}).then((response) => {
        if (response.code == 200) {
          this.storageList = [];
          response.data.forEach((element, index) => {
            // 假设 element 有一个唯一的 id 属性可以用作 key
            this.storageList.push({...element, key: element.id || `unique-${index}`});
          });
        } else {
          this.$modal.msgError("查询仓库失败");
        }
      });
    },

    handleRowEdit(row, type) {
      if (type == "1") {
        row.editFlg = true;
        if (row.isNewRecord) {
          row.addFlg = true;
        }
      } else {
        row.editFlg = false;
        row.addFlg = false;
      }
    },
    /** 确认出库 */
    confirmOut() {
      // console.log(this.checkedTCkOrderdetail);
      if (this.checkedTCkOrderdetail.length == 0) {
        this.$modal.msgError("请选择要提交的出库通知单明细！");
        return;
      }

      if (this.ckType == "") {
        this.$modal.msgError("请选择出库类型");
        return;
      }

      const commitTCkOrderdetailList = [];
      var checkResult = true;
      for (var i = 0; i < this.checkedTCkOrderdetail.length; i++) {
        var tckOrderdetail =
          this.tckOrderdetailList[this.checkedTCkOrderdetail[i] - 1];

        if (tckOrderdetail.isNewRecord) {
          checkResult = this.checkDetails(tckOrderdetail);
          if (!checkResult) {
            break;
          }
        }
        if (tckOrderdetail.confirmStatus == "2") {
          checkResult = false;
          this.$modal.msgError(
            "物料【" + tckOrderdetail.goodsName + "】已出库完成"
          );
          break;
        }
        commitTCkOrderdetailList.push(tckOrderdetail);
      }

      if (!checkResult) return;
      // console.log(commitTCkOrderdetailList);
      var form = {
        id: this.id,
        orderId: this.orderId,
        storageId: this.storageId,
        ckType: this.ckType,
        tckOrderdetailList: commitTCkOrderdetailList,
      };

      var that = this;
      this.$modal.confirm("确认生成出库任务吗？").then(function () {
        confirmOut(form).then((response) => {
          // this.$modal.msgSuccess("");
          if (response.code != 200) {
            that.$modal.msgError("发生系统错误，物料出库失败");
            return;
          }
          that.$modal.msgSuccess("出库任务创建成功！");

          that.getCkOrderDetailsById();
        });
      });
    },
    checkDetails(tckOrderdetail) {
      let checkResult = true;
      if (tckOrderdetail.goodsId == "") {
        checkResult = false;
        this.$modal.msgError("物料编码不能为空");
        return false;
      }

      if (tckOrderdetail.goodsName == "") {
        checkResult = false;
        this.$modal.msgError("物料名称不能为空");
        return false;
      }

      if (tckOrderdetail.shelvesNum == 0) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的需求数量必须大于0"
        );
        return false;
      }

      if (!Number.isInteger(tckOrderdetail.shelvesNum)) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的需求数量必须为正整数"
        );
        return false;
      }
      /*if (tckOrderdetail.goodsNum == 0) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的出库数量必须大于0"
        );
        return false;
      }*/
      if (tckOrderdetail.goodsNum > tckOrderdetail.shelvesNum) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的出库数量不能大于需求数量"
        );
        return false;
      }
      if (tckOrderdetail.goodsNum > tckOrderdetail.stockNum) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的出库数量不能大于库存数量"
        );
        return false;
      }
      /*if (tckOrderdetail.stockNum < tckOrderdetail.shelvesNum) {
        checkResult = false;
        this.$modal.msgError(
          "物料【" + tckOrderdetail.goodsName + "】的需求数量不能大于库存数量"
        );
        return false;
      }*/
      return true;
    },
    /** 查询用户展示字段定义管理列表 */
    getHideColumn() {
      var queryHideColumnParams = {
        pageNum: 1,
        pageSize: 100,
        businessCode: this.businessCodeTrk,
        tableNo: this.tableNo,
      };
      listCOLUMN(queryHideColumnParams).then((response) => {
        if (response.rows.length > 0) {
          var row = response.rows[0];
          var columnHide = row.columnHide.split(",");
          if (columnHide.length > 0) {
            for (let item in this.columns) {
              if (columnHide.indexOf(this.columns[item].columnName) > -1) {
                this.columns[item].visible = false;
              }
            }
          }
        }
        this.rightToolbarShow = true;
      });
    },
    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;
        var subSearchPanelHeight = this.$refs.subSearchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight - subSearchPanelHeight - 7;

        var mainHeight = tablePanelHeight / 3;
        this.mainTableDivHeight = mainHeight + "px";
        this.mainTableHeight = mainHeight - 25 + "px";
        this.subTableDivHeight = tablePanelHeight - mainHeight + "px";
        this.subTableHeight = tablePanelHeight - mainHeight - 25 - 33 + "px";
      });
    },
    /** 查询出库列表 */
    getList() {
      this.loading = true;
      listCkOrders(this.queryParams).then((response) => {
        // 按照 createTime 字段倒序排列
        response.rows.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        this.ckOrdersList = response.rows;
        this.total = response.total;
        this.columns = []
        this.columns = response.columns;
        this.loading = false;
        this.generateFilters();
      });
    },
    generateFilters() {
      // this.columns.forEach(column => {
      //   const uniqueValues = [...new Set(this.ckOrdersList.map(item => item[column.columnName]))];
      //   column.filters = uniqueValues.map(value => ({text: value, value}));
      //   column.filterMethod = (value, row) => row[column.columnName] === value;
      // });
      this.columns.forEach(column => {
        let uniqueValues;
        if (column.columnName === 'status') {
          uniqueValues = [...new Set(this.ckOrdersList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({
            text: this.dict.type.common_status.find(status => status.value === value)?.label || value,
            value
          }));
          column.filterMethod = (value, row) => row[column.columnName] === value;
          column.formatter = (row, column, cellValue, index) => {
            return this.dict.type.common_status.find(status => status.value === cellValue)?.label || cellValue;
          };
        }
         else if (column.columnName === 'isAudit') {
          uniqueValues = [...new Set(this.ckOrdersList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({
            text: this.dict.type.is_audit.find(isAudit => isAudit.value === value)?.label || value,
            value
          }));
          column.filterMethod = (value, row) => row[column.columnName] === value;
          column.formatter = (row, column, cellValue, index) => {
            return this.dict.type.is_audit.find(isAudit => isAudit.value === cellValue)?.label || cellValue;
          };
        }
        else {
          uniqueValues = [...new Set(this.ckOrdersList.map(item => item[column.columnName]))];
          column.filters = uniqueValues.map(value => ({text: value, value}));
          column.filterMethod = (value, row) => row[column.columnName] === value;
        }
      });
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        storageId: null,
        storageAreaId: null,
        ckType: null,
        deliveryMethod: null,
        remark: null,
        status: null,
        createBy: null,
        auditMan: null,
        auditDate: null,
        orderSource: null,
        outStand: null,
        orderType: null,
        confirmStatus: null,
        recordPerson: null,
        applicant: null,
        recordDate: null,
        productId: null,
        stationId: null,
        taskId: null,
        orderDate: null,
        createTime: null,
        updateTime: null,
        updateBy: null,
        levelType: null,
      };

      this.tckOrderdetailList = [];
      this.resetForm("form");
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      const uniqueGoodsIds = new Set(data.map(row => row.goodsId));

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
        } else if (column.property === 'shelvesNum') {
          const total = data.reduce((acc, row) => acc + (typeof row.shelvesNum === 'number' ? row.shelvesNum : 0), 0);
          sums[index] = total.toFixed(2);
        } else if (column.property === 'goodsId') {
          sums[index] = uniqueGoodsIds.size;
        } else if (column.property === 'price') {
          const total = data.reduce((acc, row) => acc + (typeof row.shelvesNum === 'price' ? row.price : 0), 0);
          sums[index] = total.toFixed(2);
        }
      });

      console.log("看看合计", sums);
      return sums;
    },

    getCkOrderDetailsById() {
      getCkOrders(this.id).then((response) => {
        this.tckOrderdetailList = [];
        if (response.data.tckOrderdetailList) {
          this.tckOrderdetailList = response.data.tckOrderdetailList;
          for (let i = 0; i < this.tckOrderdetailList.length; i++) {
            let obj = this.tckOrderdetailList[i];
            this.$set(obj, "isNewRecord", false);
            this.$set(obj, "editFlg", false);
            this.$set(obj, "addFlg", false);

            /*obj.goodsNum = Number(obj.shelvesNum) - Number(obj.pickNum);*/
          }
        }
        //   let _this = this;
        //   this.tckOrderdetailList.forEach((element) => {
        //     _this.$set(element, "isNewRecord", false);
        //     _this.$set(element, "editFlag", false);
        //     _this.$set(element, "addFlag", false);
        //   });

        // console.log(this.tckOrderdetailList);
      });
    },
    // 增加主表行双击事件,查询子表数据
    handleMainAuditTableClick(row) {
      /*row.element.style.backgroundColor = 'yellow'; // 假设row对象有element属性指向DOM元素*/
      console.log("1234")
      this.deliveryId = row.deliveryId;
      this.id = row.id;
      this.ckType = row.ckType;
      this.ckTypeEnabled = true;
      this.storageId = row.storageId;
      this.isAudit = row.isAudit == "1" ? true : false;
      getCkOrders(this.id).then((response) => {
        this.tckOrderdetailList = [];
        console.log(response);
        if (response.data.tckOrderdetailList) {
          this.tckOrderdetailList = response.data.tckOrderdetailList;
          for (let i = 0; i < this.tckOrderdetailList.length; i++) {
            let obj = this.tckOrderdetailList[i];
            this.$set(obj, "isNewRecord", false);
            this.$set(obj, "editFlg", false);
            this.$set(obj, "addFlg", false);
            if (obj.levelType == 1) {
              if (this.auditForm.person3 == '') {
                this.isFirst = true; //是一级库并且第三审批人为空
                // this.$modal.msgError("一级库必须有第三审批人！");
                // return;
              }
            }

            obj.goodsNum = Number(obj.shelvesNum) - Number(obj.pickNum);
          }
        }
        if (this.tckOrderdetailList.length == 0) {
          this.$modal.msgError("该通知单无明细，不能提交审核！");
          return;
        }
        this.auditOpen = false;
        row.isAudit = "2";
        row.auditPerson1 = this.auditForm.person1;
        row.auditPerson2 = this.auditForm.person2;
        row.auditPerson3 = this.auditForm.person3;
        row.why = this.auditForm.why
        this.$modal
          .confirm('确认要提交审核id为"' + row.id + '"数据项？')
          .then(function () {
            return changeStatus(row.id, "", row.isAudit, row.auditPerson1, row.auditPerson2, row.auditPerson3, row.why);
          })
          .then(() => {
            this.$modal.msgSuccess("提交审核成功");
          })
          .catch(function () {
            row.status = "0";
          });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleSubQuery() {
      this.querySubParams.pageNum = 1;
      this.getSubList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetSubQuery() {
      this.resetForm("querySubForm");
      this.handleSubQuery();
    },
    // 双击
    handleMainTableClick(row) {
      this.selectedRowId = row.id;
      this.deliveryId = row.deliveryId;
      this.id = row.id;
      this.ckType = row.ckType;
      this.ckTypeEnabled = true;
      this.storageId = row.storageId;
      this.isAudit = row.isAudit == "1" ? true : false;

      // 清空selectedRows或者只保留当前行
      if (this.selectedRows.some(item => item.id === row.id)) {
        // 如果当前行已经被选中，则清空selectedRows
        this.selectedRows = [];
      } else {
        // 否则，清空selectedRows并添加当前行
        this.selectedRows = [row];
      }

      // 使用 toggleRowSelection 来切换选中状态
      this.$refs.providerTableRef.clearSelection(); // 清除所有选中状态
      if (this.selectedRows.length > 0) {
        this.$refs.providerTableRef.toggleRowSelection(row, true); // 选中当前行
      }

      getCkOrders(this.id).then((response) => {
        this.tckOrderdetailList = [];
        if (response.data.tckOrderdetailList.length > 0) {
          this.tckOrderdetailList = response.data.tckOrderdetailList;
          this.printList = response.data.tckOrderdetailList;
          for (let i = 0; i < this.tckOrderdetailList.length; i++) {
            let obj = this.tckOrderdetailList[i];
            this.$set(obj, "isNewRecord", false);
            this.$set(obj, "editFlg", false);
            this.$set(obj, "addFlg", false);
          }
        }
        console.log(this.tckOrderdetailList, "双击");
      });
    },
    getRowClassName({row, rowIndex}) {
      console.log(rowIndex, this.selectedRowId)
      return row.id === this.selectedRowId ? 'selected-row' : '';
    },
    rowStyle({row, rowIndex}) {
      if (this.selectedRowId == row.id) {
        return {backgroundColor: '#019fe8'}; // 返回被点击行的样式
      }
      return {}; // 返回其他行的默认样式
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.datas = selection.map((item) => item);
      this.agv = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**
     * 审核出库单，审核后，才可以出库
     */
    handleAudit(row) {
      const ids = row.id || this.ids;
      let isAudit = false;
      for (var i = 0; i < ids.length; i++) {
        for (var j = 0; j < this.ckOrdersList.length; j++) {
          let obj = this.ckOrdersList[j];
          if (ids[i] == obj.id && obj.isAudit == "1") {
            isAudit = true;
            break;
          }
        }
        if (isAudit) {
          break;
        }
      }
      if (isAudit) {
        this.$modal.msgError("请选择未审核的通知单进行审核，请确认！");
        return;
      }
      this.$modal
        .confirm('是否确认审核出库编号为"' + ids + '"的数据项？')
        .then(function () {
          return auditCkOrders(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("审核成功");
        })
        .catch(() => {
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$forceUpdate();
      this.reset();
      this.open = true;
      this.dict.type.outbound_type.forEach(dict => {
        console.log(typeof dict.value, '字典输出'); // 输出每个选项的类型
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCkOrders(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出库";
      });
    },
    confirmAudit() {
      // Check if at least one auditor is selected
      if (!this.auditForm.person1 && !this.auditForm.person2 && (!this.showThird || !this.auditForm.person3)) {
        this.$message.error('请至少选择一位审核人');
        return;
      }
      if (!this.auditForm.person3 && !this.auditForm.why) {
        this.$message.error('请选择第三审核人或写明原因');
        return;
      }

      // Close the dialog and handle the audit
      this.handleMainAuditTableClick(this.auditRow);

    },
    cancelAudit() {
      this.auditForm.person1 = "";
      this.auditForm.person2 = ""
      this.auditForm.person3 = "";
      this.isFirst = false;
      this.auditOpen = false;
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.orderId == "") {
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.ckType = this.ckType
          // this.form.tckOrderdetailList = this.tckOrderdetailList;
          if (this.form.id != null) {
            updateCkOrders(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCkOrders(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除出库编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCkOrders(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },


    //明细数据选择的仓库
    mxStash(value) {
      this.stash = value
      console.log("Selected Storage ID:", value);
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"id为"' + row.id + '"数据项？')
        .then(function () {
          return changeStatus(row.id, row.status, "");
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认启用出库编号为"' + ids + '"的数据项？')
        .then(function () {
          return enabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("启用成功");
        })
        .catch(() => {
        });
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      debugger
      for (const e of this.datas) {
        if (e.isAudit !== '0' && e.isAudit !== '3') {
          this.$modal.msgError("单据已经是审核状态");
          return; // 这将退出整个函数
        }
        this.auditRow = e;
      }
      this.$modal
        .confirm('是否确认禁用出库编号为"' + ids + '"的数据项？')
        .then(function () {
          return disabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("禁用成功");
        })
        .catch(() => {
        });
    },

    /** 出库物料明细序号 */
    rowTCkOrderdetailIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
      if (row.isNewRecord) {
        this.disableUpdate = false;
      } else {
        if (row.goodsNum == 0 || this.isAudit != "0") {
          this.disableUpdate = true;
          return "success-row";
        }
        this.disableUpdate = false;
      }

      return "";
    },
    selectable(row, index) {
      // 这里可以根据具体业务逻辑判断，returnfalse就是不可选择，row为表格行数据
      if (row.goodsNum == 0 && !row.isNewRecord) {
        return false;
      } else {
        return true;
      }
    },

    //明细确认
    handleSaveTCkOrderdetail() {
      //保存数据
      debugger
      if (this.ids.length == 0) {
        this.$modal.msgError("请先选择要保存的通知单！");
        return;
      }


      for (let i = 0; i < this.agv.length; i++) {
        const c = this.agv[i];
        console.log("当前项", c);
      }

      let arraysDetails = [];
      const tckOrderdetailList = this.tckOrderdetailList;
      const checkedTCkOrderdetail = this.checkedTCkOrderdetail;
      let checkResult = false;
      for (let i = 0; i < checkedTCkOrderdetail.length; i++) {
        let obj = tckOrderdetailList[checkedTCkOrderdetail[i] - 1];
        let orderIdString = this.ids.slice("");
        obj.orderId = orderIdString[0];
        checkResult = this.checkDetails(obj);
        var callNum = 0;
        if (obj.callShelvesNum) {
          callNum = obj.callShelvesNum
        }
        if (obj.shelvesNum > obj.stockNum) {
          this.$modal.msgError("需求数量不能大于库存数量！");
          return;
        }
        if (obj.shelvesNum > (obj.stockNum - callNum)) {
          this.$modal.msgError("注意库存数量与已呼叫数量之差是否大于等于需求数量！");
          return;
        }
        arraysDetails.push(obj);
      }
      if (!checkResult) {
        return;
      }
      if (arraysDetails.length == 0) {
        this.$modal.msgError("请先选择要保存的通知单！");
        return;
      }
      console.log(arraysDetails, "123");
      this.updateSupport = true;
      updateTckOrderDetails(arraysDetails).then((response) => {
        //console.log(response.data);
        if (response.code == 200) {
          this.$modal.msgSuccess("保存明细成功！");
          this.getList();
        } else {
          this.$modal.msgError("保存明细失败！");
        }
        this.updateSupport = false;
      });
    },
    /** 出库物料明细添加按钮操作 */
    handleAddTCkOrderdetail() {
      if (this.deliveryId == "") {
        this.$modal.msgError("请先双击要添加的明细单");
        return;
      }
      // if (this.storageId == "") {
      //   this.$modal.msgError("请先选择仓库");
      //   return;
      // }
      let obj = {};
      obj.businessId = "";
      obj.goodsId = "";
      obj.goodsName = "";
      obj.storageId = "";
      obj.ctl = "";
      obj.locationId = "";
      obj.specification = "";
      obj.unit = "";
      obj.shelvesNum = "";
      obj.goodsNum = "";
      obj.callShelvesNum = "";
      obj.remark = "";
      obj.price = "";
      obj.totalMoney = '';
      obj.goodsTypeId = "";
      obj.providerId = "";
      obj.recoil = "";
      obj.storageAreaId = "";
      obj.pickNum = "0";
      obj.trNum = "0";
      obj.status = "";
      obj.confirmStatus = "";
      obj.stockNum = "";
      obj.taskId = "";
      obj.addFlg = true;
      obj.editFlg = true;
      obj.isNewRecord = true;
      this.tckOrderdetailList.push(obj);
      console.log(obj, "表格数据")
      console.log(this.stash)
    },
    /** 出库物料明细删除按钮操作 */
    handleDeleteTCkOrderdetail() {
      if (this.checkedTCkOrderdetail.length == 0) {
        this.$modal.msgError("请先选择要删除的出库物料明细数据");
      } else {
        const tckOrderdetailList = this.tckOrderdetailList;
        const checkedTCkOrderdetail = this.checkedTCkOrderdetail;
        var arrayList = [];
        arrayList = tckOrderdetailList.filter(function (item) {
          return (
            checkedTCkOrderdetail.indexOf(item.index) >= 0 &&
            item.id != undefined
          );
        });
        //删除

        if (arrayList.length > 0) {
          var idList = arrayList.map((item) => {
            return item.id;
          });
          this.$modal
            .confirm('是否确认删除出库明细为"' + idList + '"的数据项？')
            .then(function () {
              return delCkOrderDetails(idList);
            })
            .then(() => {
              // this.getList();
              this.$modal.msgSuccess("删除成功");
            })
            .catch(() => {
            });
        }

        this.tckOrderdetailList = tckOrderdetailList.filter(function (item) {
          return checkedTCkOrderdetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleTCkOrderdetailSelectionChange(selection) {
      this.checkedTCkOrderdetail = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/ckOrders/export",
        {
          ...this.queryParams,
        },
        `ckOrders_${new Date().getTime()}.xlsx`
      );
    },
    // 数据导入按钮操作
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "二级出库通知单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/ckOrders/importTemplate",
        {},
        `出库_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    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(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // sendNotice() {
    //   const tmpId = this.ids;
    //   if (tmpId.length == 0) {
    //     this.$modal.msgError("请选择出库通知单");
    //     return;
    //   }

    //   var form = {
    //     id: tmpId[0],
    //   };

    //   var that = this;
    //   this.$modal.confirm("确认是否发送出库通知单录入完成消息到手持设备？").then(function () {
    //     sendOrderNotice(form).then((response) => {
    //       if (response.code != 200) {
    //         that.$modal.msgError("发生系统错误，通知单消息发送失败");
    //       }
    //       if (response.data.error != "") {
    //         that.$modal.msgError(response.data.error);
    //         return;
    //       } else {
    //         that.$modal.msgSuccess(response.data.success);
    //       }
    //     });
    //   });
    // },

    //添加审核人
    /** 选择审核人 */
    selectAuditPerson() {
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一个单据提交审核");
        return;
      }
      for (const e of this.datas) {
        if (e.isAudit !== '0' && e.isAudit !== '3') {
          this.$modal.msgError("单据已经是审核状态");
          return; // 这将退出整个函数
        }
        this.auditRow = e;
      }
      this.resetAuditForm();
      this.auditOpen = true;
    },
    resetAuditForm() {
      this.auditForm.person1 = '';
      this.auditForm.person2 = '';
      this.auditForm.person3 = '';
      this.isFirst = false;
    },
    //打印
    println() {
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一个明细");
        return;
      }
      console.log(this.datas,"this.datas")
      this.datas.forEach((c) => {
        if (c.isAudit == 1) {
          this.handleMainTableClick(c);
          this.data = {
            c: c,
            tckOrderdetailList: this.printList,
          };

          console.log("传递到子页面的数据：", this.data);
          this.$nextTick(() => {
            if (this.$refs.ticket) {
              this.$refs.ticket.printClick();
            } else {
              this.$modal.msgError("未找到子页面引用");
            }
          });
        } else {
          this.$modal.msgError("未审核不能打印");
        }
      });
    },
    /** 查询出库通知单明细列表 */
    getSubList() {
      if (this.id == "") {
        this.$modal.msgError("请选择要查询的通知单");
        return;
      }
      this.querySubParams.orderId = this.id;
      if (this.querySubParams.goodsId !== "" && this.querySubParams.goodsId != null) {
        this.querySubParams.goodsId = this.querySubParams.goodsId.replace(/\s+/g, "").toUpperCase();
      }
      console.log(this.querySubParams)
      listOrderdetail(this.querySubParams).then((response) => {
        this.tckOrderdetailList = response.rows;
        this.subTotal = response.total;
        if (this.subColumns.length === 0) this.subColumns = response.columns;
      });
    },
    /*sendIwms() {
      const tmpId = this.ids;
      if (tmpId.length == 0) {
        this.$modal.msgError("请选择出库通知单");
        return;
      }
      if (this.ids.length > 1) {
        this.$modal.msgError("只能选择一个单据");
        return;
      }
      this.datas.forEach(c => {
        /!*if (c.isAudit == 0) {
          this.$modal.msgError("数据状态为未审核，请检查");
          return;
        }*!/
        var form = {
          id: tmpId[0],
        };

        var that = this;
        this.$modal.confirm("确认是否发送出库通知单到iwms？").then(function () {
          sendiwms(form).then((response) => {
            if (response.code != 200) {
              that.$modal.msgError("发生系统错误，通知单消息发送失败");
            }
            if (response.data.error != "") {
              that.$modal.msgError(response.data.error);
              return;
            } else {
              that.$modal.msgSuccess(response.data.success);
            }
          });
        });
      });
    },*/


    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}

::v-deep .el-table .warning-row {
  background: #31a354;
}

::v-deep .el-table .success-row {
  background-color: #e1d1d1;
}

::v-deep .el-table .selected-row {
  background-color: #019fe8 !important;
}

</style>



