<template>
  <div :class="kind ? 'orderPage' : 'orderPageS'">
    <el-tabs
      v-loading="editLoading"
      element-loading-text="正在加载中..."
      type="border-card"
      class="order-table"
      @tab-click="tabClick"
    >
      <template v-for="item in numTab" :key="item.table">
        <el-tab-pane :label="item.label" :name="item.name">
          <el-form
            :label-position="labelPosition"
            label-width="100px"
            :model="StockInfo"
            v-if="kind"
          >
            <div class="leftInfo">
              <el-form-item label="配送司机">
                <el-select
                  v-model="StockInfo.Sj"
                  placeholder="请选择司机信息"
                  multiple
                  @change="SJchangeSelect"
                >
                  <el-option-group
                    v-for="group in StockInfo.DriverInformation"
                    :key="group.id"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-option-group>
                </el-select>
              </el-form-item>

              <el-form-item label="配送车辆">
                <el-select
                  v-model="StockInfo.Cl"
                  placeholder="请选择配送车辆"
                  multiple
                  @change="CLchangeSelect"
                >
                  <el-option-group
                    v-for="group in StockInfo.VehicleInformation"
                    :key="group.id"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.id"
                      :label="item.vehicleNub"
                      :value="item.id"
                    />
                  </el-option-group>
                </el-select>
              </el-form-item>
            </div>
            <!-- 选择好的司机信息展示 -->
            <div class="Information">
              <div class="infoCls">
                <div class="Infos">
                  <span> 主司机展示</span>
                  <el-input v-model="DataSubmit.masterDriverName" disabled placeholder="暂未选择" />
                </div>
                <div>
                  <span> 主车辆展示</span>
                  <el-input v-model="DataSubmit.masterVehicleNub" disabled placeholder="暂未选择" />
                </div>
              </div>
            </div>
            <el-button style="margin-left: auto" type="danger" round @click="DriverConfiguration"
              >查看司机配置</el-button
            >
          </el-form>
          <!-- 外协开始 -->
          <el-form :label-position="labelPosition" label-width="100px" :model="StockInfo" v-else>
            <div class="leftInfo wxInfo">
              <el-form-item label="外协来源">
                <el-select
                  v-model="DataSubmit.tripartite.distributionCompany"
                  clearable
                  placeholder="请选择外协来源"
                  @change="Outsourcing"
                >
                  <el-option
                    v-for="item in StockInfo.OutsourcingSources"
                    :key="item.id"
                    :label="item.dictValue"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="司机名称">
                <el-input
                  v-model="DataSubmit.tripartite.driverName"
                  placeholder="请输入司机名称"
                  clearable
                />
              </el-form-item>

              <el-form-item label="司机电话">
                <el-input
                  v-model="DataSubmit.tripartite.driverPhone"
                  placeholder="请输入司机电话"
                  clearable
                />
              </el-form-item>

              <el-form-item label="车辆车牌">
                <el-input
                  v-model="DataSubmit.tripartite.vehicleNum"
                  placeholder="请输入车辆车牌"
                  clearable
                />
              </el-form-item>

              <el-form-item label="配送费用">
                <el-input
                  v-model="DataSubmit.tripartite.deliveryFee"
                  placeholder="请输入配送费用"
                  clearable
                />
              </el-form-item>
            </div>
          </el-form>
          <!-- 外协结束 -->
          <!-- 备货选择 -->
          <el-divider content-position="left">备货区域</el-divider>
          <el-form :label-position="labelPosition" label-width="100px" :model="StockInfo">
            <div class="leftInfo StockUParea">
              <!-- 备货人员选择 -->
              <el-form-item label="备货人员">
                <el-select
                  v-model="DataSubmit.stockup.forkliftName"
                  clearable
                  placeholder="请选择备货人员"
                  @change="StockPersonnel"
                >
                  <el-option
                    v-for="item in StockInfo.StockPersonnel"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <!-- 装车班组选择 -->
              <el-form-item label="装车班组">
                <el-select
                  v-model="DataSubmit.stockup.loaderId"
                  clearable
                  placeholder="请选择装车班组"
                  @change="Loading"
                >
                  <el-option
                    v-for="item in StockInfo.LoadingTeam"
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <!-- 卸车班组选择 -->
              <el-form-item label="卸车班组">
                <el-select
                  v-model="DataSubmit.stockup.unloaderId"
                  clearable
                  placeholder="请选择卸车班组"
                  @change="unload"
                >
                  <el-option
                    v-for="item in StockInfo.UnloadingTeam"
                    :key="item.id"
                    :label="item.groupName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 配送类型  -->

              <el-form-item label="配送类型">
                <el-radio-group v-model="DataSubmit.reservation.deliveryType" class="ml-4">
                  <el-radio label="1" size="large">商配</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- 备货区域  -->
              <el-form-item label="备货区域">
                <el-select
                  v-model="DataSubmit.stockup.goodsAreaId"
                  clearable
                  placeholder="请选择备货区域"
                  @change="StockUpSera"
                >
                  <el-option
                    v-for="item in StockInfo.StockUpArea"
                    :key="item.id"
                    :label="item.headline"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <!-- 备货时间  -->
              <div class="time">
                <el-form-item label="备货时间">
                  <el-date-picker
                    v-model="DataSubmit.stockup.stockupDate"
                    type="datetime"
                    placeholder="请选择备货时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </div>

              <!-- 出库时间 -->
              <div class="time">
                <el-form-item label="出库时间">
                  <el-date-picker
                    v-model="DataSubmit.stockup.outboundDate"
                    type="datetime"
                    placeholder="请选择出库时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </div>
              <!-- 配送日期  -->
              <div class="time">
                <el-form-item label="配送日期">
                  <el-date-picker
                    v-model="DataSubmit.taskTime"
                    type="date"
                    placeholder="请选择配送时间"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                  />
                </el-form-item>
              </div>

              <!-- 备注  -->
              <div class="notes">
                <el-form-item label="备注">
                  <el-input
                    v-model="DataSubmit.remarks"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="请输入备注内容"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form>
          <el-tabs type="border-card">
            <el-tab-pane label="订单">
              <div class="el-content-el">
                <!-- 顶部开始 -->
                <div class="el-Cart-button">
                  <!-- 表格顶部左侧按钮 -->
                  <div class="el-Cart-button-left">
                    <el-button type="primary" @click="AddInfo"
                      ><el-icon><Plus /></el-icon>新 增</el-button
                    >
                    <div class="el_multifunctional">
                      <el-input
                        v-model="multifunctional"
                        placeholder="请输入要搜索的值,多条件用英文逗号拼接"
                        clearable
                        @clear="soclear"
                      />
                      <el-button type="primary" @click="SearchFu"
                        ><el-icon><Plus /></el-icon>搜索</el-button
                      >
                    </div>
                  </div>
                </div>
                <!-- 顶部结束 -->
                <div class="el-Cart">
                  <tablecmt
                    class="columnList"
                    style="height: 60vh"
                    ref="newColumnListNode"
                    :columnList="menuData.slice(1)"
                    :tableData="dataInfo"
                    :loading="loading"
                  >
                    <template #default="slotProps">
                      <el-text
                        v-if="slotProps.scope.row.isZero != '1'"
                        :link="ElButtonS[0].link"
                        :class="ElButtonS[0].class"
                        :auto-insert-space="ElButtonS[0].space"
                        :size="ElButtonS[0].size"
                        :icon="ElButtonS[0].icon"
                        @click="ViewEvent(slotProps.scope.row)"
                        >查看包件</el-text
                      >
                      <!-- <el-text
                        v-if="slotProps.scope.row.isZero == '1'"
                        :link="ElButtonS[1].link"
                        :class="ElButtonS[1].class"
                        :auto-insert-space="ElButtonS[1].space"
                        :size="ElButtonS[1].size"
                        :icon="ElButtonS[1].icon"
                        @click="Entering(slotProps.scope.row)"
                        >在库录入</el-text
                      > -->
                      <el-text
                        v-if="slotProps.scope.row.isZero == '1'"
                        :link="ElButtonS[2].link"
                        :class="ElButtonS[2].class"
                        :auto-insert-space="ElButtonS[2].space"
                        :size="ElButtonS[2].size"
                        :icon="ElButtonS[2].icon"
                        @click="QuantityEntry(slotProps.scope.row)"
                        >数量录入</el-text
                      >

                      <el-text
                        :link="ElButtonS[4].link"
                        :class="ElButtonS[4].class"
                        :auto-insert-space="ElButtonS[4].space"
                        :size="ElButtonS[4].size"
                        :icon="ElButtonS[4].icon"
                        @click="DeleteEvent(slotProps.scope.row)"
                        >删除</el-text
                      >
                      <!-- <div :class="ElBtnClass">
                      </div> -->
                    </template>
                  </tablecmt>

                  <div class="el-Cart-button-btn">
                    <div class="el_tool">
                      已选择:{{ dataInfo.length }}条

                      <div>
                        <span>合计:</span>
                        <span
                          >订单总件数:
                          <span style="color: #67c23a">{{ Totalnumberoforders }} </span>
                        </span>
                        <span style="margin: 0 4px"></span>
                        <span
                          >在库总件数:
                          <span style="color: #67c23a"> {{ Totalnumberofitemsinstock }}</span></span
                        >
                      </div>
                    </div>
                    <el-button type="primary" @click="SubmitCommercial"
                      ><el-icon><Select /></el-icon>提交(商配订单)</el-button
                    >
                  </div>
                </div>

                <!-- 右侧功能列表弹窗 -->
                <div class="el-menu-load">
                  <el-drawer v-model="menu" direction="rtl">
                    <template #header>
                      <h4>菜单功能列表</h4>
                    </template>
                    <!-- 默认插入到侧边栏内容 -->
                    <!-- 表格功能列表  -->
                    <template #default>
                      <div v-if="!Btn">
                        <el-tabs type="border-card">
                          <el-tab-pane label="表格功能">
                            <el-table :data="menuData" border>
                              <el-table-column
                                v-for="column in MenuTop"
                                :key="column.prop"
                                :prop="column.prop"
                                :label="column.label"
                                :width="column.width"
                              >
                                <!--
                  / 
                  MenuTop:       0:菜单选项
                  true-label:    1.选中时候的值
                  false-label:   2.没有选中时候的值
                  @change:       3.当绑定时候的值发生变化的时候触发
                  label:         4.选中状态的值

                  /
                -->
                                <!-- 标题 -->
                                <template #default="scope">
                                  <template v-if="column.prop == 'label'">
                                    <el-text class="mx-1">{{ scope.row[column.prop] }}</el-text>
                                  </template>
                                  <!-- 隐藏复选框 -->
                                  <template v-else-if="column.label == '隐藏'">
                                    <el-checkbox-group v-model="checkList">
                                      <el-checkbox
                                        :key="scope.row['label']"
                                        :label="scope.row['label']"
                                        @change="CheckBox(scope.row, 1)"
                                      >
                                        <!-- 用于隐藏文字 -->
                                        <template #default="scope">
                                          <!-- {{ scope }} -->
                                        </template>
                                      </el-checkbox>
                                    </el-checkbox-group>
                                  </template>

                                  <template v-else-if="column.label == '冻结'">
                                    <el-checkbox-group v-model="flexList">
                                      <el-checkbox
                                        :key="scope.row['label']"
                                        :label="scope.row['label']"
                                        @change="CheckBox(scope.row, 2)"
                                      >
                                        <!-- 用于隐藏文字 -->
                                        <template #default="scope">
                                          <!-- {{ scope }} -->
                                        </template>
                                      </el-checkbox>
                                    </el-checkbox-group>
                                  </template>
                                </template>
                              </el-table-column>
                            </el-table>
                          </el-tab-pane>
                          <el-tab-pane label="按钮功能">
                            <!-- <div class="el-title-btn">
                  <span> 表格操作按钮风格选择 </span>
                </div> -->
                            <el-radio-group v-model="BtnRadio" @change="btnClass">
                              <el-radio label="1" size="default" border>链接样式风格</el-radio>
                              <el-radio label="2" size="default" border>按钮样式风格</el-radio>
                            </el-radio-group>
                          </el-tab-pane>
                          <el-tab-pane label="待添加"></el-tab-pane>
                          <el-tab-pane label="待添加"></el-tab-pane>
                        </el-tabs>
                      </div>
                      <!-- 按钮功能结束-->
                    </template>
                  </el-drawer>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </template>
    </el-tabs>

    <!-- 弹窗组件 -->
    <el-dialog v-model="AddLalog" width="80%" :title="wrapLoading ? '包件信息' : '在库订单信息'">
      <!-- 表格列开始 -->
      <!-- data 订单信息  wrapData包件信息 -->
      <div v-if="!wrapLoading">
        <div class="SoInput" v-if="searchSo" ref="SoHeight">
          <el-form label-width="100px" :model="parameter">
            <el-form-item label="商场名称:">
              <el-input v-model="parameter.mallName" clearable placeholder="请输入商场名称" />
            </el-form-item>
            <el-form-item label="货物名称:">
              <el-input v-model="parameter.descriptionGoods" placeholder="请输入货物名称" />
            </el-form-item>
            <el-form-item label="运单号:">
              <el-input v-model="parameter.waybillNumber" clearable placeholder="请输入运单号" />
            </el-form-item>
            <el-form-item label="订单自编号:">
              <el-input v-model="parameter.orderCode" clearable placeholder="请输入订单自编号" />
            </el-form-item>
            <el-form-item label="服务号:">
              <el-input v-model="parameter.serviceNumber" clearable placeholder="请输入服务号" />
            </el-form-item>

            <el-form-item label="运单收货单位:">
              <el-input
                v-model="parameter.consigneeUnit"
                clearable
                placeholder="请输入运单收货人"
              />
            </el-form-item>

            <el-form-item label="运单收货人:">
              <el-input
                v-model="parameter.consigneePerson"
                clearable
                placeholder="请输入运单收货人"
              />
            </el-form-item>

            <el-form-item label="顾客地址:">
              <el-input
                v-model="parameter.customerAddress"
                clearable
                placeholder="请输入顾客地址"
              />
            </el-form-item>
            <el-form-item> </el-form-item>
          </el-form>
          <!-- <div class="SoBtn">
                        搜索菜单预留按钮 
                      </div> -->
        </div>
      </div>
      <!-- 包件搜索 -->
      <div v-else class="el_package">
        <el-form :model="PackageFrom">
          <el-form-item label="运单号:">
            <el-input v-model="PackageFrom.waybillNumber" clearable placeholder="请输入运单号" />
          </el-form-item>
          <el-form-item label="包条码:">
            <el-input v-model="PackageFrom.orderPackageCode" placeholder="请输入包条码" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 顶部开始 -->
      <div class="flex-c-sb">
        <!-- 表格顶部左侧按钮 -->
        <div>
          <el-button type="primary" @click="SoInput"
            ><el-icon><Search /></el-icon>搜索</el-button
          >
          <el-button class="SoEmpty" type="primary" @click="SoEmpty">
            <el-icon><Delete /></el-icon> 清空
          </el-button>
        </div>
        <!-- 表格顶部右侧按钮 -->
        <div>
          <!-- 刷新按钮 -->
          <el-button @click="refresh" icon="Refresh" circle></el-button>
          <el-button @click="search" icon="Search" circle></el-button>
        </div>
      </div>
      <!-- 顶部结束 -->
      <tablecmt
        class="columnList mt10"
        style="height: 60vh"
        ref="columnListNode"
        :columnList="wrapLoading ? wrap : newMenuData"
        :tableData="wrapLoading ? wrapData : data"
        :loading="loading"
        @inputTxt="inputsc"
        @selection="TCselectAll"
        :isselectfun="ProhibitSelection"
        :searchInput="multifunctional"
      >
        <template #default="slotProps"> </template>
      </tablecmt>
      <!-- 表格翻页功能 -->
      <div class="flex-c-sb">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="pageList"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="PageSizeChange"
          @current-change="SizeChange"
          v-if="!wrapLoading"
        />
        <!-- 弹窗底部提交按钮 -->
        <div></div>

        <el-button type="danger" @click="submit">
          <el-icon><Select /></el-icon>
          确认提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 弹窗结束 -->

    <!-- 弹窗组件 -->
    <div class="addlalog addlalogS">
      <!-- <el-dialog v-model="SjTc" title="司机信息配置"> -->
      <el-dialog v-model="comprehensive" :title="SjTc ? '司机配置' : '零担品类信息'">
        <!-- 司机信息弹窗  -->
        <el-table v-if="SjTc" :data="DvInfoData" border style="width: 100%">
          <el-table-column prop="driverName" label="司机信息" />
          <el-table-column prop="vehicleNub" label="车辆信息" />
          <el-table-column label="操作">
            <template #default="scope">
              <span @click="moveUpVehictle(scope.row)" class="move">上移</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- EnteringLibrary在库录入 -->
        <div Class="iszer" v-if="EnteringLibrary">
          <span style="font-weight: bold; display: block; padding-bottom: 10px"
            >在库总数:{{ dataInfo[dataId].handQuantity }}</span
          >
          <el-table :data="isZeroTable" border style="width: 100%">
            <el-table-column fixed prop="firsts" label="名称" />
            <!-- <el-table-column prop="quantity" label="数量" /> -->
            <!-- <el-table-column prop="handQuantity" label="在库数量" /> -->
            <el-table-column prop="deliveryQuantity" label="冻结数量" />
            <el-table-column prop="outboundQuantity" label="出库数量" />
            <!-- <el-table-column label="可用数量">
              <template #default="props"> 
                <span>
                  {{
                    props.row.handQuantity - props.row.deliveryQuantity - props.row.outboundQuantity
                  }}</span
                >
              </template>
            </el-table-column> -->
            <!-- 在库=冻结-出库 -->

            <el-table-column fixed="right" label="数量操作">
              <template #default="scope">
                <el-input-number
                  v-if="!QuantityEntryStatus"
                  size="small"
                  v-model="scope.row.number"
                  @change="isZeroNumber(scope.row)"
                />
                <el-input-number
                  v-else
                  size="small"
                  :max="MaxSUM"
                  :min="0"
                  v-model="scope.row.reservationNum"
                  @change="isZeroNumber(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div class="isZel-btn">
            <el-button v-if="!QuantityEntryStatus" color="#172e60" type="success" @click="ModifyLCL"
              >修改(零担订单)</el-button
            >
            <el-button color="#172e60" type="success" @click="SubmitLoad">提交(零担订单)</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  $_selectStockArticleInfoList,
  $_getPackageListByStockArticleId,
  getZeroOrderDetail,
} from '@/api/distribution/distributionStockArticle'; //API
import { getVehicleList } from '@/api/basicdata/basicdataVehicle'; //车辆信息
import { useStore } from 'vuex';
import { getDriverList } from '@/api/basicdata/basicdataDriverArtery'; //司机信息
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus';
import {
  deliveryBusinessTask,
  $_getDeliveryZeroOrderDetail,
} from '@/api/distribution/distributionReservation'; //提交API
import { getListUser } from '@/api/distribution/distributionStockup'; //备货人员查询
import { $_stockUpInfo } from '@/api/basicdata/basicdataGoodsArea'; //备货区域
import { getListTeamInfo } from '@/api/basicdata/basicdataTeamGroup'; //装卸班组
import {
  getDeliveryList,
  $_getPackageListByDeliveryIdAndOrderId,
  updateDeliveryList,
  $_judgmentOrderRemove,
} from '@/api/distribution/distributionDeliveryList'; //数据回显
import { getDictionaryBiz } from '@/api/system/dict'; //外协来源
import type { FormProps } from 'element-plus';
import { updateEntryNum, entryNum } from '@/api/distribution/distributionParcelNumber';
import { deepClone } from '@/utils/util.js';
const route = useRoute();
const router = useRouter();
// 获取vuex仓库
const $store = useStore();
console.log($store, '仓库');

// 选项卡
const numTab = ref([
  {
    label: '自主配送',
    name: '0',
  },
  {
    label: '外协',
    name: '1',
  },
]);
const num = ref(null); //计步器
const Totalnumberoforders = ref(0); //订单总件数
const Totalnumberofitemsinstock = ref(0); //在库件数
const kind = ref(true); //标签切换
const currentPage = ref(1); // 默认页码
const pageSize = ref(20); // 默认每一页几条
const pageList = ref([5, 10, 50, 100, 200]); // 选择每页显示多少条
const background = ref(true); // 是否开启背景颜色
const disabled = ref(false); // 是否禁止使用页码功能
const data = ref([]); // 表格数据
const PackageFrom = ref({}); //包件搜索
const wrapData = ref([]); //包件表格信息
const wrapLoading = ref(false); //包件表格弹窗
const dataInfo = ref([]); //表格展示信息
const dataInfoTemp = ref([]); //表格展示公共值
const dataTmp = ref([]); //暂存数据
const TabHeight = ref(230); //动态获取表格高度
const TCTabHeight = ref(600); //动态获取弹窗表格高度
const AddLalog = ref(false); //提交弹窗
const AddForm = ref({}); //表单所有信息
const AddData = ref({}); //获取数据列表
const tableRef = ref(null); // 用于引用 table 实例
const menu = ref(false); //功能菜单列表
const total = ref(0); //页码总数
const checkList = ref<(string | number)[]>([]); //隐藏
const flexList = ref<(string | number)[]>([]); //冻结
const loading = ref(false); //刷新功能
const BG = ref(false); //表格功能列表
const BtnRadio = ref('1'); //按钮样式风格切换
const Packageow = ref(); //查看包间报错当前数据
const ElBtnClass = ref('el-Btn-link'); //按钮样式风格类名
const searchSo = ref(false); //搜索弹窗
const SoHeight = ref(); //搜索栏高度动态
const SjInfo = ref([]); //选中的司机 用来匹配车辆
const ClInfo = ref([]); //选中的车辆 用来匹配司机
const deptId = ref(); //备货区关键参数
const driver = ref(); //司机 页面初始化获取的信息
const vehicle = ref(); //车辆页面初始化获取的信息
const DriverTemporaryStorage = ref([]); //司机暂存
const VehicleTemporaryStorage = ref([]); //车辆暂存
const DvInfoData = ref([]); //合并司机和车辆信息
const SjTc = ref(false); //司机信息弹窗
const editLoading = ref(false); //编辑弹窗
const state = ref(false); //提交信息状态
const tableRefs = ref(null); //包件实例
const multifunctional = ref(''); //编辑订单搜索
const dataId = ref(null); //包件对应ID,用于存储包件下面的ID
const wrapDataInfo = ref([]); //订单包件回显
const RouteId = ref(); //编辑页面的ID参数
const labelPosition = ref<FormProps['labelPosition']>('right');
const SoInfoData = ref(); //搜索框
const parameter = ref({}); //搜索框参数
const wrapTemp = ref([]); //包件选中项暂存
const EnteringLibrary = ref(false); //在库录入按钮
const QuantityEntryS = ref(false); //数量录入按钮
const isZeroTable = ref([]); //零担表格
const comprehensive = ref(false); //司机,零担弹窗
const QuantityEntryStatus = ref(false); //零担数量录入状态
const TCzj = ref(); //弹窗组件实例
const soInpuState = ref(false); //搜索框状态表示当前没有搜索
const statisticsList = ref([]); //需要统计的字段
const inputValue = ref('number'); //零担输入的值
const dataInfoID = ref(); //点击删除保存当前ID
/** 编辑时, 初始化司机信息 */
const chooseDriverIds = ref([]);
/** 编辑时, 初始化车辆信息 */
const chooseCarIds = ref([]);

// 司机选择信息
// 车辆选项
// 备货人员
// radio1 配送类型
const StockInfo = ref({
  createDate: new Date(), //默认日期
  radio: 1,
  //司机信息
  DriverInformation: [
    {
      label: '当前车辆司机',
      options: [],
    },
    {
      label: '全部司机信息',
      options: [],
    },
  ],

  //车辆信息
  VehicleInformation: [
    {
      label: '当前司机车辆',
      options: [],
    },
    {
      label: '全部车辆信息',
      options: [],
    },
  ],
  OutsourcingSources: [], //外协来源
  // 装车班组
  LoadingTeam: [],
  // 卸车班组
  UnloadingTeam: [],
  //   备货人员信息
  StockPersonnel: [],
  //   备货区域
  StockUpArea: [],
  TemporaryDriver: [], //临时存放司机信息
  TemporaryVehicles: [], //临时存放车辆信息
});

const selectable = (row, index) => {
  // row.orderPackageReservationStatusName == '已预约' ||
  if (row.checked) {
    return false; //禁用状态
  } else {
    return true; //非禁用状态
  }
};
// 提交的表单
const DataSubmit = ref({
  allocationInfo: [
    {
      driverId: null, //司机ID
      driverName: null, //司机名称
      driverPhone: null, // 司机电话
      vehicleId: null, //车辆ID
      vehicleNub: null, //车牌号
    },
  ],
  masterDriverName: null, //主司机
  masterVehicleNub: null, //主车辆
  remarks: null, //备注
  reservation: {
    deliveryType: '1', //配送类型  固定商配
    deliveryWay: null, //配送方式 （无用）TGG说的
    otherFee: 0, //其他费用 （无用）
    serveType: null, //服务类型  （无用）
  },

  stockArticle: [], //订单列表
  stockup: {
    forkliftId: null, //叉车ID
    forkliftName: null, //备货人员
    goodsAreaId: null, //备货区ID
    goodsAreaName: null, //备货区域
    outboundDate: null, //出库时间
    stockupDate: null, //备货时间
    loaderId: null, //装车班组ID
    loaderName: null, //装车班组
    unloaderName: null, // 卸车班组
    unloaderId: null, //卸车班组ID
  },
  taskTime: null, //配送日期remarks

  //   外协参数
  tripartite: {
    driverName: null, //司机名称
    driverPhone: null, //司机电话
    vehicleNum: null, //司机车牌号
    deliveryFee: null, //配送费用
    distributionCompanyId: '1', //默认
    distributionCompany: null, //外协来源
  },
});

// 列表组件实例 -- 新增
const columnListNode = ref();

// 按钮样式风格切换
const btnClass = type => {
  // 切换链接样式风格
  if (type == 1) {
    ElBtnClass.value = 'el-Btn-link';
  }
  // 切换按钮样式风格
  if (type == 2) {
    ElBtnClass.value = 'el-Btn-btn';
  }
};
//页面初始化请求需要的数据
async function Info() {
  // 车辆信息
  getVehicleList().then(res => {
    console.log(res, '车辆信息');
    StockInfo.value.VehicleInformation[1].options = res.data.data;
    vehicle.value = res.data.data; //存一份初始化信息 用于清空选择使用
    console.log(StockInfo.value.VehicleInformation, 'StockInfo.VehicleInformation');
  });
  //   司机信息
  getDriverList().then(res => {
    console.log(res, '司机信息');
    // StockInfo.value.DriverInformation = res.data.data;
    StockInfo.value.DriverInformation[1].options = res.data.data;
    driver.value = res.data.data; //存一份初始化信息 用于清空选择使用
    console.log(StockInfo.value.DriverInformation, '全部司机信息');
  });
  //   备货人员信息
  await getListUser().then(res => {
    let data = []; //备货人员信息临时保存
    console.log(res, '备货人员');
    console.log(res.data.data);
    console.log(res.data.data[0].deptId, '关键参数');
    deptId.value = res.data.data[0].deptId; //目前取第一个，TGG说参数都是一样
    // 确保请求到的内容有数据,防止报错
    if (res.data.data.length > 0) {
      res.data.data.forEach(item => {
        console.log(item.realName);
        data.push({ realName: item.realName, id: item.id });
      });
    }
    console.log(data, '备货人员');
    StockInfo.value.StockPersonnel = data;
  });
  //   备货区域
  $_stockUpInfo({
    params: deptId.value,
  }).then(res => {
    console.log(res, '备货区域');
    StockInfo.value.StockUpArea = res.data.data;
    console.log(StockInfo.value.StockUpArea, ' StockInfo.value.StockUpArea');
  });
  //   装卸班组
  getListTeamInfo(deptId.value).then(res => {
    console.log(res.data.data, '装卸班组');
    StockInfo.value.UnloadingTeam = res.data.data; //卸车
    StockInfo.value.LoadingTeam = res.data.data; //装车
  });
  //   外协来源-数据字典数据获取
  getDictionaryBiz('tripartite_source').then(res => {
    StockInfo.value.OutsourcingSources = res.data.data;
    console.log(StockInfo.value.OutsourcingSources, '外协来源');
  });
}
// 导航标签切换
const tabClick = val => {
  let label = val.props.label;
  if (label == '自主配送') {
    kind.value = true;
  } else {
    kind.value = false;
  }
  console.log(kind.value);
};
Info(); //页面初始化获取车辆和司机信息
// 过滤出来的当前司机车辆
// arr1 传入需要匹配的
// arr2进行匹配的
function CurrentVehicle(arr1, arr2) {
  const matchedArray = [];
  arr1.forEach(id => {
    const matchedItem = arr2.find(item => item.id === id);
    if (matchedItem) {
      matchedArray.push(matchedItem);
    }
  });
  return matchedArray;
}

const handleSizeChange = () => {
  console.log(1);
};
// 根据ID匹配函数
function findObjectById(id, array) {
  return array.find(item => item.id === id);
}
// 按钮配置
const ElButtonS = ref([
  // 1.class   按钮样式名(用于切换按钮样式)
  // 2.space   是否开启按钮文子直接间距(true开启 ,false关闭)
  // 3.size    按钮尺寸默认小尺寸('large'| 'default'| 'small')
  // 4.icon    按钮图标
  // 5.table   按钮名称

  {
    class: 'el-btn-view',
    space: true,
    size: 'small',
    icon: 'el-icon-view',
    table: '查看',
  },
  {
    class: 'el-btn-view Zola-View',
    space: true,
    size: 'small',
    icon: 'EditPen',
    table: '在库录入',
  },
  {
    class: 'el-btn-view',
    space: true,
    size: 'small',
    icon: 'DataLine',
    table: '数量录入',
  },
  {
    class: 'el-btn-success',
    space: true,
    size: 'small',
    icon: 'Edit',
    table: '编辑',
  },
  {
    class: 'el-btn-danger',
    space: true,
    size: 'small',
    icon: 'el-icon-delete',
    table: '删除',
  },
]);
// 菜单配置
const MenuTop = ref([
  {
    prop: 'label',
    label: '列名',
    width: '',
  },
  {
    prop: '',
    label: '隐藏',
  },
  {
    prop: '',
    label: '冻结',
  },
  {
    prop: '',
    label: '排序',
  },
]);
// 菜单功能配置项
const menuData = ref([
  {
    prop: '',
    label: '复选框',
    type: 0,
    values: '',
    width: 55,
    checkarr: [],
    fixed: true,
    sortable: false,
    head: false,
  },
  {
    prop: '',
    label: '序号',
    type: 12,
    values: '',
    width: 55,
    checkarr: [],
    fixed: true,
    sortable: false,
    head: false,
  },
  {
    prop: 'serviceNumber',
    label: '服务号',
    type: 2,
    values: '',
    width: '160',
    checkarr: [],
    fixed: true,
    sortable: true,
    head: false,
  },
  {
    prop: 'waybillNumber',
    label: '运单号',
    type: 2,
    values: '',
    width: '160',
    checkarr: [],
    fixed: true,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderCode',
    label: '订单自编号',
    type: 2,
    values: '',
    width: '160',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },

  {
    prop: 'consigneeUnit',
    label: '运单收货单位',
    type: 2,
    values: '',
    width: '180',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'totalNumber',
    label: '订单总件数',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
    statistics: true, //开启统计
    isshowSummary: true,
  },
  {
    prop: 'handQuantity',
    label: '在库件数',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
    statistics: true, //开启统计
    isshowSummary: true,
  },
  {
    prop: 'consigneePerson',
    label: '运单收货人',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'consigneeMobile',
    label: '运单收货人电话',
    type: 1,
    values: '',
    width: '150',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  // {
  //   prop: 'mallId',
  //   label: '商场编号',
  //   type: 2,
  //   values: '',
  //   width: '260',
  //   checkarr: [],
  //   fixed: false,
  //   sortable: true,
  //   head: false,
  // },
  {
    prop: 'mallCode',
    label: '商场编号',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'storeCode',
    label: '经销商编码',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'storeName',
    label: '门店名称',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'storeId',
    label: '门店编号',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderStatusName',
    label: '订单状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'freezeStatusName',
    label: '冻结状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'reservationStatusName',
    label: '预约状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'descriptionGoods',
    label: '货物名称',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'warehouse',
    label: '仓库',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'warehouseEntryTime',
    label: '入库时间',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'storeTime',
    label: '在库时间',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },

  {
    prop: 'completeSetName',
    label: '是否齐套',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'brand',
    label: '品牌',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'typeServerName',
    label: '服务类型',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },

  {
    prop: 'mallName',
    label: '商场名称',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'customerName',
    label: '顾客名字',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'customerTelephone',
    label: '顾客电话',
    type: 2,
    values: '',
    width: '160',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'customerAddress',
    label: '顾客地址',
    type: 2,
    values: '',
    width: '200',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'allocation',
    label: '库位信息',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'trays',
    label: '托盘信息',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: '',
    label: '操作',
    type: 6,
    values: '',
    width: '250',
    checkarr: [],
    fixed: 'right',
    sortable: true,
    head: false,
  },
]);
// 新增订单列表
const newMenuData = deepClone(menuData.value.slice(0, menuData.value.length - 1));
// 包件信息
const wrap = ref([
  {
    prop: '',
    label: '复选框',
    type: 0,
    values: '',
    width: 55,
    checkarr: [],
    fixed: true,
    sortable: false,
    head: false,
  },
  {
    prop: '',
    label: '序号',
    type: 12,
    values: '',
    width: 55,
    checkarr: [],
    fixed: true,
    sortable: false,
    head: false,
  },
  {
    prop: 'waybillNumber',
    label: '运单号',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageCode',
    label: '包条码',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageStockupStatusName',
    label: '备货状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageStatusName',
    label: '签收状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageGroundingStatusName',
    label: '上架状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageLoadingStatusName',
    label: '装车状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageReservationStatusName',
    label: '预约状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'orderPackageFreezeStatusName',
    label: '冻结状态',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'goodsAllocation',
    label: '货位信息',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'pallet',
    label: '所在托盘',
    type: 1,
    values: '',
    width: '260',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'warehouse',
    label: '仓库',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },

  {
    prop: 'firsts',
    label: '一级品',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'second',
    label: '二级品',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'thirdProduct',
    label: '三级品',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
  {
    prop: 'materialName',
    label: '物料',
    type: 2,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },

  {
    prop: 'quantity',
    label: '数量',
    type: 1,
    values: '',
    width: '130',
    checkarr: [],
    fixed: false,
    sortable: true,
    isshowSummary: true,
    head: false,
  },
  {
    prop: 'trainNumber',
    label: '客户车次号',
    type: 1,
    values: '',
    width: '260',
    checkarr: [],
    fixed: false,
    sortable: true,
    head: false,
  },
]);
// 获取表格数据
function onLoad() {
  loading.value = true; //开启加载效果
}

statisticsList.value = menuData.value.filter(item => item.statistics); //筛选出要统计的
console.log(statisticsList.value, '需要统计的字段');

const TabHeig = () => {
  TabHeight.value = TabHeight.value.offsetHeight; //表格高度
  console.log(TabHeight.value.offsetHeight, 'TabHeight.value.offsetHeight');
};
// 动态获取DOM高度给表单防止页面出现滚动条
// 页面初始化完成数据回填
onMounted(() => {
  console.log(route.query.id, '路由参数ASDASDASDAS');
  if (route.query.id) {
    RouteId.value = route.query.id;
    // wrapLoading.value = true; //表示这是编辑状态
    editLoading.value = true; //开启加载
    getDeliveryList(route.query.id).then(res => {
      //司机配置
      if (res.data.data.kind == 2) {
        DataSubmit.value.tripartite.distributionCompany = res.data.data.distributionCompany; //外协来源
        DataSubmit.value.tripartite.driverName = res.data.data.deliveryTripartiteVO.driverName; //司机名称
        DataSubmit.value.tripartite.vehicleNum = res.data.data.deliveryTripartiteVO.vehicleNum; //司机车牌
        DataSubmit.value.tripartite.deliveryFee = res.data.data.deliveryTripartiteVO.deliveryFee; //配送费用
        DataSubmit.value.tripartite.driverPhone = res.data.data.deliveryTripartiteVO.driverPhone; //司机电话
        numTab.value[0].name = '1'; //切换外协选项卡
        numTab.value[1].name = '0';
        kind.value = false;
        console.log(numTab.value, '选项卡');
      } else {
        numTab.value[0].name = '0'; //切换外协选项卡
        numTab.value[1].name = '1';
        kind.value = true;
        res.data.data.deliverySelfVO.forEach(item => {
          console.log(item, '司机配置信息');
          DriverTemporaryStorage.value.push({
            driverId: item.driverId, //司机ID
            driverName: item.driverName, //司机姓名
            driverPhone: item.driverPhone, //司机电话
          });
          chooseDriverIds.value.push(item.driverId);

          VehicleTemporaryStorage.value.push({
            vehicleId: item.vehicleId, //车辆ID
            vehicleNub: item.vehicleNub, //车牌号
          });
          chooseCarIds.value.push(item.vehicleId);
          // 配送司机
          StockInfo.value.Sj.push(item.driverId);
          // 配送车辆
          StockInfo.value.Cl.push(item.vehicleId);
          if (item.isMaster == 2) {
            DataSubmit.value.masterDriverName = item.driverName; //主司机名称
            DataSubmit.value.masterVehicleNub = item.vehicleNub; //司机车牌号
          }
        });
      }
      wrapDataInfo.value = res.data.data.stockArticleList; // 订单包件
      dataInfo.value = res.data.data.stockArticleList; //订单列表
      // dataInfoTemp.value=dataInfo.value;//把获取到的值传递给公共组件
      DataSubmit.value.stockup.loaderId = res.data.data.loadingTeamId; //装车班组ID
      DataSubmit.value.stockup.loaderName = res.data.data.loadingTeamName; //装车班组名称
      DataSubmit.value.stockup.unloaderId = res.data.data.unloadingTeamId; //卸车班组ID
      DataSubmit.value.stockup.unloaderName = res.data.data.unloadingTeamName; //卸车班组名称
      DataSubmit.value.remarks = res.data.data.remarks; //备注信息
      DataSubmit.value.stockup.forkliftName = res.data.data.stockupInfo.forkliftName; //备货人员名称
      DataSubmit.value.stockup.forkliftId = res.data.data.stockupInfo.forkliftId; //备货人员ID
      DataSubmit.value.stockup.goodsAreaId = res.data.data.stockupInfo.goodsAreaId; //备货区域ID
      DataSubmit.value.stockup.goodsAreaName = res.data.data.stockupInfo.stockupArea; //备货区域名称
      DataSubmit.value.stockup.outboundDate = res.data.data.stockupInfo.outboundDate; //出库时间
      DataSubmit.value.stockup.stockupDate = res.data.data.stockupInfo.stockupDate; //备货时间
      DataSubmit.value.taskTime = res.data.data.taskTime; //配送日期
      editLoading.value = false; //所有信息获取完成关闭弹窗
      tooSUM();
    });
  }
});

// 订单新增选中
async function OrderSelection(id, DataParameter) {
  try {
    loading.value = true; //开启加载效果

    loading.value = true; //开启加载效果
    const res = await $_selectStockArticleInfoList({
      typeService: StockInfo.value.radio, //类型商配（固定）
      genre: 1, //固定参数
      current: currentPage.value, //页码
      size: pageSize.value, //每一页条数
      ...DataParameter, //搜索参数
      ...PackageFrom.value, //订单搜索参数
      ...parameter.value, //包件搜索
    });

    const { code, data: resData } = res.data;

    if (code !== 200) return;

    console.log('columnListNode.value :>> ', columnListNode.value);

    data.value = resData.records;
    // 根据选择的已经有的去匹配已经选择的数据勾选

    console.log(data.records, '在库订单信息');
    total.value = resData.total; //总页数

    await nextTick();
    // 浅拷贝数据
    const selectArr = [...dataInfo.value];

    selectArr.forEach((value, index) => {
      const _item = resData.records.find(item => item.id === value.id);
      // 没有则跳出本次循环
      if (!_item) return;
      // 找到则替换数据
      selectArr.splice(index, 1, _item);
    });
    // console.log('selectArr :>> ', selectArr);
    console.log('columnListNode.value :>> ', columnListNode.value);
    columnListNode.value.handleCheckSelect(selectArr);
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    loading.value = false; // 关闭加载
  }
}

// 点击新增获在库订单信息
function dataTabInfo() {
  // 根据当前是自配还是外协来选择订单里面选中状态
  if (kind.value) {
    OrderSelection(0);
  } else {
    OrderSelection(1);
  }
}
// 点击新增获取在库订单信息
const AddInfo = () => {
  // PackageFrom.value = {}; //重置搜索框参数
  // parameter.value = {}; //重置搜索框参数
  currentPage.value = 1; //重置搜索页码
  // if (soInpuState.value) {
  //   ElMessage({
  //     showClose: true,
  //     message: '请先重置搜索框值',
  //     type: 'warning',
  //   });
  //   return;
  // }
  dataTmp.value = [];
  console.log('提交前的参数', dataInfo.value);
  console.log('提交前前临时存储', dataTmp.value);
  AddLalog.value = true; //展开表单弹窗
  wrapLoading.value = false; //关闭包件弹窗信息
  dataTabInfo(); //请求数据
};
// 每页多少条触发
const PageSizeChange = val => {
  pageSize.value = val;
  dataTabInfo();
};
// 页码翻页触发
const SizeChange = val => {
  currentPage.value = val;
  dataTabInfo();
};

// 菜单触发功能
// Type ===1  隐藏列
// Type ===2  冻结列
const CheckBox = (scope, type: number) => {
  console.log(scope, 'scope');
  if (type === 1) {
    scope.head = !scope.head;
  }
  if (type === 2) {
    scope.fixed = !scope.fixed;
  }
};
// 表格全选功能触发
const selectAll = val => {
  console.log(val);
};
// 弹窗全选
const TCselectAll = val => {
  dataTmp.value = val;
  console.log(dataTmp.value, '勾选中的数据');
};

/** 表格表头输入框搜索 */
const inputsc = (value, row) => {
  if (!wrapLoading.value) {
    parameter.value[row.prop] = value;
    if (!value) delete parameter.value[row.prop];

    // 订单搜索
    if (kind.value) {
      OrderSelection(0, parameter.value);
    } else {
      OrderSelection(1, parameter.value);
    }
  } else {
    PackageFrom.value[row.prop] = value;
    if (!value) delete PackageFrom.value[row.prop];

    // 包件搜索
    PackageFn();
  }
};

// 弹窗表格单个选中触发事件
const selectChange = (selection, row) => {
  //   把选择的数据放到临时存储里面
  //   编辑状态
  if (RouteId.value) {
    console.log(dataTmp, '当前选中的包件信息');
    //   wrapLoading为真表示此时弹窗内容是包件信息
    if (wrapLoading.value) {
      let packageListInfo = []; //定义参数名保存选中的订单
      //   packageListInfo = dataTmp.value;//把临时存储的值赋值给需要提交的字段
      dataTmp.value = selection; //当前选中的值给临时存储起来
      //   dataTmp.value = dataInfo.value;
      console.log(dataInfo.value, '包件信息选中');
      console.log(dataId.value, '当前选中的订单ID下标');
      console.log(dataInfo.value[dataId.value], '当前操作的订单');
    } else {
      console.log('当前为在库订单信息');
      //   dataTmp.value = selection; //选中信息暂存起来
      selection.forEach(item => {
        item.checked = true; //表示当前已经被选中了
        dataTmp.value.push(item);
      });
    }
  } else {
    // 新增状态
    if (wrapLoading.value) {
      wrapTemp.value = selection;
      // 包件
    } else {
      selection.forEach(item => {
        item.checked = true; //表示当前已经被选中了
        dataTmp.value.push(item);
      });
    }
  }
};
function tooSUM() {
  Totalnumberoforders.value = 0;
  Totalnumberofitemsinstock.value = 0;
  dataInfo.value.forEach(item => {
    (Totalnumberoforders.value += item.totalNumber),
      (Totalnumberofitemsinstock.value += item.handQuantity);
  });
}
// 弹窗确认表单信息展示
const submit = () => {
  console.log('dataTmp.value :>> ', dataTmp.value);

  // 当前为编辑状态
  if (RouteId.value) {
    if (!dataTmp.value.length) {
      ElMessageBox.confirm('当前没有勾选包件，是否移除当前订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log(dataInfo.value, '当前所有订单');
          console.log(dataId.value, '删除订单');
          dataInfo.value.splice(dataId.value, 1);

          ElMessage({
            type: 'success',
            message: '移除成功',
          });
          AddLalog.value = false; //关闭弹窗
        })
        .catch(() => {});
      return;
    }
    if (!wrapLoading.value) {
      dataInfo.value = dataTmp.value;

      console.log(dataInfo.value, '要展示的值');
      console.log('触发1');
    } else {
      // 编辑的时候需要带上这个参数存放订单下面的包件信息
      let packageListInfo = [];
      console.log('触发2');
      dataInfo.value[dataId.value].packageListInfo = dataTmp.value; //把存在的值给当前订单下面
      // dataInfo.value[dataId.value].packageListInfo = wrapData.value;
      wrapTemp.value[dataId.value] = dataTmp.value;
      console.log('wrapTemp.value[dataId.value] :>> ', wrapTemp.value[dataId.value]);
      console.log(wrapTemp.value, '包件订单被缓存');
      console.log(dataInfo.value[dataId.value].packageListInfo, '被添加到当前订单下面');
      console.log(dataInfo.value, '所有订单信息');
    }
  } else {
    if (!dataTmp.value.length) {
      ElMessageBox.confirm('当前没有勾选包件，是否移除当前订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log(dataInfo.value, '当前所有订单');
          console.log(dataId.value, '删除订单');
          dataInfo.value.splice(dataId.value, 1);

          ElMessage({
            type: 'success',
            message: '移除成功',
          });
          AddLalog.value = false; //关闭弹窗
        })
        .catch(() => {});
      return;
    }
    // 新增订单
    //选中好的订单提交到要展示的表格
    if (wrapLoading.value) {
      console.log(dataInfo.value, '订单');
      console.log(dataId.value, '当前下标');
      console.log(dataInfo.value[dataId.value], '当前下班的订单');
      console.log(dataTmp.value, '勾选的数据');
      dataInfo.value[dataId.value].packageListInfo = dataTmp.value; //把存在的值给当前订单下面。。修改过
      console.log(wrapTemp.value, '包件订单被缓存222');
      console.log(dataInfo.value, '处理好的订单');
      // 包件弹窗
    } else {
      dataInfo.value = dataTmp.value;
    }

    console.log('提交后的参数', dataInfo.value);
    console.log('提交后的临时存储', dataTmp.value);
  }

  // 展示的信息
  dataInfo.value = removeDuplicates(dataInfo.value);
  // 计算总数
  tooSUM();
  // 临时存储
  dataTmp.value = removeDuplicates(dataTmp.value);
  AddLalog.value = false; //关闭弹窗
};

// 订单数据去重
function removeDuplicates(arr) {
  const ids = arr.map(obj => obj.id);
  return arr.filter((item, index) => ids.indexOf(item.id) === index);
}
const soclear = () => {
  SearchFu();
};

function scrollToElementWithinTableRow(partialIdString) {
  // 首先清空之前所有元素的颜色样式
  const tableRows = document.querySelectorAll('tr');
  tableRows.forEach(function (row) {
    const cells = row.querySelectorAll('[id]');
    cells.forEach(function (cell) {
      cell.style.backgroundColor = ''; // 移除背景颜色
      cell.style.color = ''; // 移除文字颜色
    });
  });

  // 将输入的逗号分隔的字符串拆分成数组
  const partialIds = partialIdString.split(',').map(id => id.trim());

  // 通过遍历每一行来检查是否每一个partialId都存在
  for (let row of tableRows) {
    // 检查这一行是否包含所有的partialIds
    if (partialIds.every(partialId => row.querySelector(`[id*="${partialId}"]`))) {
      // 如果匹配，设置背景颜色和文字颜色
      const cells = row.querySelectorAll('[id]');
      cells.forEach(function (cell) {
        cell.style.backgroundColor = '#ff0000'; // 设置背景颜色为红色
        cell.style.color = '#fff'; // 设置文字颜色为白色
      });

      // 将这一行滚动到视野区域
      row.scrollIntoView();
      break; // 匹配到了就跳出循环
    }
  }
}
// 编辑多功能搜索
const SearchFu = () => {
  console.log(multifunctional.value, '搜索的参数值');

  if (multifunctional.value) {
    scrollToElementWithinTableRow(multifunctional.value);
  } else {
    document.querySelectorAll('[id]').forEach(function (el) {
      el.style.backgroundColor = ''; // 移除背景颜色
      el.style.color = ''; // 移除文字颜色
    });
  }

  return;

  // console.log(dataInfo.value, '搜索结果');
};

// 删除触发事件
const DeleteEvent = val => {
  if (route.query.id) {
    // 判断是否为编辑
    let data = {
      deliveryId: route.query.id,
      orderId: val.id,
    };
    console.log(data, '删除处理值');
    $_judgmentOrderRemove(data).then(res => {
      console.log(res, '删除返回值');
      if (res.data.code == 200) {
        if (!res.data.data) {
          ElMessage({
            message: '不能移除当前订单,存在装车数据,联系司机滞留',
            type: 'warning',
          });
          return;
        }
        dataInfoID.value = val; //存储一份临时数据
        if (dataInfoTemp.value.length) {
          //删除拷贝的数据里面如果执行这个表示当前已经是搜索过了，在执行搜索里面的值
          const index = dataInfoTemp.value.findIndex(item => item.id === val.id);
          if (index !== -1) {
            dataInfoTemp.value.splice(index, 1);
          }
        }
        console.log(dataInfoID.value, '当前删除的数据');
        // 接收点击删除当前行数据
        const index = dataInfo.value.findIndex(item => item.id === val.id);
        if (index !== -1) {
          dataInfo.value.splice(index, 1);
          ElMessage({
            message: '移除成功',
            type: 'success',
          });
        }
      }
    });
  } else {
    dataInfoID.value = val; //存储一份临时数据
    if (dataInfoTemp.value.length) {
      //删除拷贝的数据里面如果执行这个表示当前已经是搜索过了，在执行搜索里面的值
      const index = dataInfoTemp.value.findIndex(item => item.id === val.id);
      if (index !== -1) {
        dataInfoTemp.value.splice(index, 1);
      }
    }

    console.log(dataInfoID.value, '当前删除的数据');
    // 接收点击删除当前行数据
    const index = dataInfo.value.findIndex(item => item.id === val.id);
    if (index !== -1) {
      dataInfo.value.splice(index, 1);
      ElMessage({
        message: '移除成功',
        type: 'success',
      });
    }
  }
  tooSUM();
};
// 编辑触发事件
const EditEvent = val => {
  // 接收点击编辑当前行数据
  console.log('触发了编辑事件', val);
};
const MaxSUM = computed(() => {
  let sum = 0;
  isZeroTable.value.forEach(item => {
    sum += item.deliveryQuantity;
  });
  let max = dataInfo.value[dataId.value].handQuantity - sum;
  console.log(dataInfo.value, ' dataInfo.value[');

  return max;
});
const toggleSelection = options => {
  const { val = true, data, dataInfo = wrapData.value, index = 0 } = options;
  const setIn = setTimeout(() => {
    if (val) {
      dataInfo.forEach((row, i) => {
        tableRefs.value[index].toggleRowSelection(dataInfo[i], true);
      });
    } else {
      dataInfo.forEach((row, i) => {
        if (row.id == data[i]) {
          tableRefs.value[index].toggleRowSelection(dataInfo[i], true);
        }
      });
    }
    clearTimeout(setIn);
  }, 0);
};
function ProhibitSelection(val, index) {
  if (wrapLoading.value) {
    if (val.orderPackageLoadingStatus == 20 || val.orderPackageStockupStatus == 70) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
}
// 查看包件返回包件对应下标.
const findIndexById = id => {
  for (let i = 0; i < dataInfo.value.length; i++) {
    if (dataInfo.value[i].id == id) {
      return i;
    }
  }
  return -1; //返回-1表示没用查询到
};

// 查看包间函数
const PackageFn = async () => {
  loading.value = true; //关闭加载效果

  try {
    //接收点击查看当前行数据;
    //   编辑信息弹窗状态
    if (RouteId.value) {
      console.log(wrapLoading.value, '当前为编辑状态');
      const res = await $_getPackageListByDeliveryIdAndOrderId({
        ...PackageFrom.value, //搜索参数
        current: 1,
        size: 100,
        deliveryId: RouteId.value,
        id: Packageow.value.id,
      });

      const { code, data: resData } = res.data;

      if (code !== 200) return;

      console.log(res, '订单包件信息');
      wrapData.value = res.data.data.data.packageList;
      let IdTmp = []; //订单ID暂存
      dataInfo.value[dataId.value].packageListInfo = wrapTemp.value[dataId.value];

      await nextTick();
      const _arr = [];
      const _ids = res.data.data.data.packageListIds
        ? res.data.data.data.packageListIds.split(',')
        : [];

      for (const iterator of res.data.data.data.packageList) {
        if (_ids.includes(iterator.id)) _arr.push(iterator);
      }

      columnListNode.value.handleCheckSelect(_arr);

      //查看当前订单下面包件是缓存值,如果有就读取缓存值,否则就是第一次加载,使用API返回值
      // if (dataInfo.value[dataId.value].packageListInfo) {
      //   dataInfo.value[dataId.value].packageListInfo.forEach(item => {
      //     IdTmp.push(item.id);
      //   });
      // }
      // toggleSelection({
      //   val: false,
      //   data: IdTmp.length ? IdTmp : res.data.data.data.packageListIds.split(','),
      //   index: kind.value ? 0 : 1,
      // }); //编辑的时候选中已有的数据

      // AddLalog.value = false; //关闭弹窗
      console.log(wrapData.value, '包件表格信息');
      console.log(res);
      console.log('执行了2');
    } else {
      // 运单号
      // 包条码
      const res = await $_getPackageListByStockArticleId({
        ...PackageFrom.value, //搜索参数
        id: Packageow.value.id,
        current: 1,
        size: 100,
      });

      const { code, data: resData } = res.data;

      console.log('res :>> ', res);

      if (code !== 200) return;

      wrapData.value = resData.records;
      console.log(res, '订单包件');

      await nextTick();
      columnListNode.value.handleCheckSelect(wrapData.value);
      console.log(tableRefs, 'tableRefs');
      console.log(resData.records, '查看下面的包件');
      // 新增 查看订单流程

      console.log('当前为新增状态');
      console.log(Packageow.value, Packageow.value.id, '查看包件事件');
      //临时存储下标用于查询包件对应的下标
      console.log(dataId.value, 'dataId.value下标');
      console.log(wrapDataInfo.value[dataId.value], '当前订单下面的包件信息');
      console.log(wrapDataInfo, '订单');
    }
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    loading.value = false; //关闭加载效果

    editLoading.value = false; //关闭加载效果
  }
};

// 查看包件事件
function ViewEvent(val, index) {
  console.log(index, '下标');
  wrapData.value = [];
  loading.value = true; //开启加载效果
  PackageFrom.value = {}; //清空订单搜索参数
  parameter.value = {}; //清空包件搜索
  Packageow.value = val;
  console.log(index, '查看包件事件INDEX');
  wrapLoading.value = true; //查看包件弹窗
  AddLalog.value = true; //开启弹窗
  editLoading.value = true; //开启加载效果
  dataId.value = findIndexById(val.id);
  console.log(val.id);

  //接收点击查看当前行数据;
  //   编辑信息弹窗状态
  PackageFn();
  return;
}
// 输入框值切换

// 在库录入
const Entering = val => {
  dataId.value = findIndexById(val.id); //记录当前点击的订单
  comprehensive.value = true; //开启弹窗
  EnteringLibrary.value = true; //显示零担
  QuantityEntryStatus.value = false; //关闭零担录入
  SjTc.value = false; //关闭司机弹窗
  console.log('在库录入', val);

  getZeroOrderDetail(val.id).then(res => {
    console.log(res, '在库录入返回信息');
    isZeroTable.value = res.data.data;
  });
};

// 数量录入
const QuantityEntry = val => {
  console.log(dataInfo.value, 'dataInfo.value');

  dataId.value = findIndexById(val.id); //记录当前点击的订单
  comprehensive.value = true; //开启弹窗
  QuantityEntryStatus.value = true; //此时开启零担录入
  EnteringLibrary.value = true; //显示零担
  SjTc.value = false; //关闭司机弹窗
  //   编辑状态
  if (RouteId.value) {
    $_getDeliveryZeroOrderDetail({
      deliveryId: RouteId.value,
      orderId: val.id,
    }).then(res => {
      console.log(res, '编辑状态在库录入');
      //   冻结数量-数量操作 =冻结数量
      for (let item of res.data.data) {
        item.deliveryQuantity = item.deliveryQuantity - item.reservationNum;
      }
      isZeroTable.value = res.data.data;
    });
  } else {
    // 新增状态
    getZeroOrderDetail(val.id).then(res => {
      console.log(res, '数量录入返回信息');
      isZeroTable.value = res.data.data;
    });
  }
};
// 修改零担数量
const ModifyLCL = () => {
  //  最大值校验
  for (const item of isZeroTable.value) {
    if (item.number > item.quantity) {
      ElMessage({
        message: item.firsts + ':最大值: 不能大于（数量）',
        type: 'warning',
      });
      return;
    }
  }
  //   最小值校验
  for (const item of isZeroTable.value) {
    if (item.number < item.deliveryQuantity + item.outboundQuantity) {
      ElMessage({
        message: item.firsts + ':最小值: 不能低于（冻结数量+出库数量）',
        type: 'warning',
      });
      return;
    }
  }
  updateEntryNum(isZeroTable.value).then(res => {
    console.log(res, '修改零担');
    console.log(isZeroTable.value, '修改零担的值');
  });
  comprehensive.value = false; //关闭弹窗
  QuantityEntryStatus.value = false; //此时关闭零担录入
  EnteringLibrary.value = false; //关闭零担
};
// 零担提交
const SubmitLoad = () => {
  // 新增订单
  // QuantityEntryStatus为真表示此时此刻操作的是数量录入提交

  let sum = 0; //最大值
  let Numberoperations = 0;
  isZeroTable.value.forEach(item => {
    sum += item.deliveryQuantity;
    Numberoperations += item.reservationNum;
  });
  let max = dataInfo.value[dataId.value].handQuantity - sum;
  console.log(dataInfo.value, ' dataInfo.value[');
  if (Numberoperations > max) {
    ElMessage({
      message: '操作数量总和不能大于冻结数量总和',
      type: 'warning',
    });

    return;
  }

  if (QuantityEntryStatus.value) {
    // if (RouteId.value) {
    //   for (let item of isZeroTable.value) {
    //     if (
    //       item.reservationNum >
    //       item.handQuantity - item.deliveryQuantity - item.outboundQuantity
    //     ) {
    //       ElMessage({
    //         message: item.firsts + item.reservationNum + ':最大值:不能超过（可用数量）',
    //         type: 'warning',
    //       });

    //       return;
    //     }
    //   }
    // }
    // console.log(dataInfo.value[dataId.value], '当前零担信息');
  } else {
    
    // 操作数量最小值校验  冻结数量+出库数量
    // for (const item of isZeroTable.value) {
    //   if (item.number < item.deliveryQuantity + item.outboundQuantity) {
    //     ElMessage({
    //       message: item.firsts + ':最小值:不能低于（冻结数量+在库数量）',
    //       type: 'warning',
    //     });
    //     return;
    //   }
    // }
    // 操作数量最大值校验

    // for (const item of isZeroTable.value) {
    //   if (item.handQuantity + item.number > item.quantity) {
    //     ElMessage({
    //       message: item.firsts + ':最大值:不能超过(在库数量+输入的数量)>数量',
    //       type: 'warning',
    //     });
    //     return;
    //   }
    // }
    entryNum(isZeroTable.value).then(res => {
      console.log(res, '提交零担');
      console.log(isZeroTable.value, '提交零担的值');
    });
  }
  dataInfo.value[dataId.value].parcelNumberVOS = isZeroTable.value;
  comprehensive.value = false; //关闭弹窗
  EnteringLibrary.value = false; //关闭零担
  QuantityEntryStatus.value = false; //此时开启零担录入
};
// 零担数量操作
const isZeroNumber = val => {
  console.log(val, '当前零担信息');

  if (!QuantityEntry.value) {
    val.reservationNum = val.reservationNum;
  } else {
    val.reservationNum = val.number;
  }
};
// 刷新功能触发事件
const refresh = () => {
  if (!wrapLoading.value) {
    AddInfo();
  } else {
    ViewEvent(Packageow.value);
  }
};
// 搜索展开功能
const search = () => {
  searchSo.value = !searchSo.value;
};
// 顶部搜索功能
const SoInput = () => {
  loading.value = true; //关闭加载效果
  currentPage.value = 1; //重置页码功能
  console.log('点击了搜索功能');

  if (!wrapLoading.value) {
    if (kind.value) {
      OrderSelection(0, parameter.value);
    } else {
      OrderSelection(1, parameter.value);
    }
  } else {
    PackageFn();
  }
};
// 顶部清空搜索
const SoEmpty = () => {
  if (!wrapLoading.value) {
    parameter.value = {};
    if (kind.value) {
      OrderSelection(0);
    } else {
      OrderSelection(1);
    }
  } else {
    PackageFrom.value = {};
    PackageFn();
  }
};

// 去重函数 接收一个数字通过ID匹配去掉重复项
function removeDuplicatesById(arr) {
  const uniqueArray = arr.reduce((acc, current) => {
    const found = acc.find(item => item.id === current.id);
    if (!found) {
      acc.push(current);
    }
    return acc;
  }, []);
  console.log(uniqueArray, 'uniqueArray处理好的值');
  return uniqueArray;
}
// 选择备货人员触发
const StockPersonnel = val => {
  console.log(val);
  let data = [];
  data = findObjectById(val, StockInfo.value.StockPersonnel);
  DataSubmit.value.stockup.forkliftId = data.id; //备货人员ID
  DataSubmit.value.stockup.forkliftName = data.realName; //备货人员姓名
};
// 选择备货区域触发
const StockUpSera = val => {
  let data = [];
  data = findObjectById(val, StockInfo.value.StockUpArea);
  DataSubmit.value.stockup.goodsAreaId = data.id; //备货区域ID
  console.log(data, '备货区域');
  DataSubmit.value.stockup.goodsAreaName = data.headline; //备货区域名称
};
//装车班组触发
const Loading = val => {
  let data = [];
  data = findObjectById(val, StockInfo.value.LoadingTeam);
  console.log(data, '装车');
  DataSubmit.value.stockup.loaderId = data.id; //装车ID
  DataSubmit.value.stockup.loaderName = data.groupName; //装车名称
};
// 卸车班组触发
const unload = val => {
  let data = [];
  data = findObjectById(val, StockInfo.value.UnloadingTeam); //卸车ID
  DataSubmit.value.stockup.unloaderId = data.id;
  DataSubmit.value.stockup.unloaderName = data.groupName; //卸车ID
  console.log(data, '卸车');
};
// 外协来源触发
const Outsourcing = val => {
  let data = [];
  data = findObjectById(val, StockInfo.value.OutsourcingSources);
  console.log(data);
  DataSubmit.value.tripartite.distributionCompany = data.dictValue; //外协来源赋值
};
// 选择司机触发
const SJchangeSelect = val => {
  if (val.length === 0) {
    DataSubmit.value.masterDriverName = null; //清空司机信息
    StockInfo.value.VehicleInformation[1].options = vehicle.value; //初始化车辆
    return;
  }
  if (val.length > 0) {
    let SJname = null; //用来少选第一选择的司机名称
    SJname = CurrentVehicle(val, StockInfo.value.DriverInformation[1].options);
    console.log(SJname[0].name, '司机');
    DataSubmit.value.masterDriverName = SJname[0].name;
    let data = []; //存储函数筛选后的司机车辆信息
    let dataInfo = []; //临时存储的司机车辆信息
    let SjData = []; //临时存放司机信息
    //   CurrentVehicle()方法 传入ID可以匹配出数组里面对应的数据
    data = CurrentVehicle(val, StockInfo.value.DriverInformation[1].options);
    if (data) {
      data.forEach(item => {
        SjData.push({
          driverId: item.id, //司机ID
          driverName: item.name, //司机姓名
          driverPhone: item.phone, //司机电话
        });
      });
      DriverTemporaryStorage.value = SjData;
      console.log(DriverTemporaryStorage.value, '司机处理好的信息');
    }
    //   获取当前司机的车辆
    if (data) {
      data.forEach(item => {
        if (item.vehicleVOList) {
          item.vehicleVOList.forEach(item => {
            dataInfo.push(item);
          });
        }
      });
      //   调用去重函数对重复车辆进行去重然后赋值给当前选中司机的所有车辆
      dataInfo = removeDuplicatesById(dataInfo);
      //VehicleInformation[0] 存储的是当下司机名下所有车辆信息
      StockInfo.value.VehicleInformation[0].options = dataInfo;
    }
  }
};

// 选择车辆触发
const CLchangeSelect = val => {
  if (val.length === 0) {
    StockInfo.value.DriverInformation[1].options = driver.value; //初始化司机信息
    DataSubmit.value.masterVehicleNub = null; //清空司机牌照
    return;
  }
  // 接收一个车辆ID 用于查询车辆车牌
  let data = [];
  let dataInfo = []; //临时存储的当前车辆的所有司机信息
  let ClData = []; //临时存放车辆信息
  let ClName = null; //用来筛选第一选择的车牌信息
  if (val.length > 0) {
    ClName = CurrentVehicle(val, StockInfo.value.VehicleInformation[1].options);
    DataSubmit.value.masterVehicleNub = ClName[0].vehicleNub; //处理好的车牌
    data = CurrentVehicle(val, StockInfo.value.VehicleInformation[1].options);
    console.log(data, '返回的值===');

    //   处理从车辆 信息 获取车辆的ID和车牌号
    if (data) {
      data.forEach(item => {
        ClData.push({
          vehicleId: item.id, //车辆ID
          vehicleNub: item.vehicleNub, //车牌号
        });
      });
      VehicleTemporaryStorage.value = ClData;
      console.log(VehicleTemporaryStorage.value, '车辆处理好的信息');
    }
    console.log(data, '查询出来的车辆信息');
    //   筛选出当前车辆下面的所有司机
    if (data) {
      console.log(data, '目前的信息data');
      data.forEach(item => {
        // 防止有些车辆下面没有绑定司机
        if (item.driverArteryEntityList) {
          item.driverArteryEntityList.forEach(item => {
            dataInfo.push(item);
            console.log(item, 'itemInfo解析');
          });
        }
      });
      dataInfo = removeDuplicatesById(dataInfo); //对当前选择的车辆司机去重
      console.log(dataInfo, 'dataInfo信息');
      StockInfo.value.DriverInformation[0].options = dataInfo; // 把去重后的值赋值给当前车辆下面的司机
    }
  }
};

// 合并司机和车辆信息
const merge = (val, kindS) => {
  if (kindS == 'WX') {
    // 如果是外协就不进行下面的司机合并
    console.log('当前是外协');

    if (!DataSubmit.value.tripartite.distributionCompany) {
      ElMessage({
        message: '请选择外协来源',
        type: 'warning',
      });
      return;
    }

    if (!DataSubmit.value.tripartite.driverName) {
      ElMessage({
        message: '请选填写司机名称',
        type: 'warning',
      });
      return;
    }

    const phoneRegExp = /^[0-9]{11}$/;
    if (!phoneRegExp.test(DataSubmit.value.tripartite.driverPhone)) {
      ElMessage({
        message: '请输入正确的11位司机电话号码',
        type: 'warning',
      });
      return;
    }

    if (!DataSubmit.value.tripartite.vehicleNum) {
      ElMessage({
        message: '请选填车辆车牌',
        type: 'warning',
      });
      return;
    }

    if (!DataSubmit.value.taskTime) {
      ElMessage({
        message: '请填写配送日期',
        type: 'warning',
      });
      return;
    }
    state.value = true; //满足提交条件
    return;
  }

  // 判断司机配置是否选择
  if (!DriverTemporaryStorage.value.length && !VehicleTemporaryStorage.value.length) {
    ElMessage({
      message: '未选择司机配置!',
      type: 'warning',
    });
    return;
  }
  //   判读司机配置是否选择完整
  if (DriverTemporaryStorage.value.length != VehicleTemporaryStorage.value.length) {
    ElMessage({
      message: '司机配置未选择完整!',
      type: 'warning',
    });
    return;
  }
  //   判读主司机否选择
  if (DataSubmit.value.masterDriverName == null) {
    ElMessage({
      message: '未选择主司机!',
      type: 'warning',
    });
    return;
  }
  //   判读主车辆否选择
  if (DataSubmit.value.masterVehicleNub == null) {
    ElMessage({
      message: '未选择主车辆!',
      type: 'warning',
    });
    return;
  }
  if (!DataSubmit.value.taskTime) {
    ElMessage({
      message: '请填写配送日期',
      type: 'warning',
    });
    return;
  }
  //   如果是提交就不弹窗
  delete DataSubmit.value.tripartite; //删掉外协字段
  //   合并司机和车辆信息
  let dataInfo = []; //暂存司机配置
  dataInfo = DriverTemporaryStorage.value.map((driver, index) => ({
    ...driver,
    ...VehicleTemporaryStorage.value[index],
  }));
  console.log(data, '处理好的');

  DvInfoData.value = dataInfo; //查看司机配置
  DataSubmit.value.allocationInfo = dataInfo; //提交的时候司机配置
  state.value = true; //满足提交条件
  if (val == 'submit') {
    return;
  }
  comprehensive.value = true; //开启弹窗
  SjTc.value = true;
  EnteringLibrary.value = false; //关闭零担弹窗
};

// 查看司机合并数据
const DriverConfiguration = () => {
  merge();
  //   开启弹窗显示司机配置
};
// 切换主司机
const moveUpVehictle = row => {
  let i = 0;
  console.log(row);
  DvInfoData.value.forEach((item, index) => {
    if (item.driverId === row.driverId) {
      i = index;
    }
  });
  //获取当当前选中的下标，如果下标为第一个则不能上移
  if (i > 0) {
    let index = DvInfoData.value[i - 1];
    DvInfoData.value.splice(i - 1, 1);
    DvInfoData.value.splice(i, 0, index);
  } else {
    ElMessage({
      message: '已经是第一条了，不能移动!',
      type: 'warning',
    });
  }
  console.log(DvInfoData.value, '切换好的司机');
  DataSubmit.value.masterDriverName = DvInfoData.value[0].driverName; //主司机
  DataSubmit.value.masterVehicleNub = DvInfoData.value[0].vehicleNub; //主车牌
};

/** 返回 */
const handleBack = () => {
  $store.commit('DEL_TAG_CURRENT'); //关闭当前页面
  router.back();
};

// 最后提交订单
const SubmitCommercial = async () => {
  let code = null;
  try {
    //kind为假就说明目前是在外协页面
    console.log(kind.value);
    if (kind.value) {
      merge('submit', 'TJ');
    } else {
      merge('submit', 'WX');
    }
    //  不符合判断条件不能提交
    if (!state.value) {
      return;
    }

    // 如果订单下面没有选择包件就默认给每个订单包件下面添加packageListInfo字段为空数组
    dataInfo.value.forEach(item => {
      if (!item.packageListInfo) {
        item.packageListInfo = [];
      }
    });
    DataSubmit.value.stockArticle = dataInfo.value; //订单列表
    // 提交
    editLoading.value = true; //开启提交加载
    // 编辑修改
    if (RouteId.value) {
      if (!kind.value) {
        delete DataSubmit.value.allocationInfo; //如果为外协删掉此参数
      }
      let DataSubmitRenamed = Object.assign({}, DataSubmit.value); //浅拷贝需要提交的参数

      // 是否修改了司机或车辆的信息
      DataSubmitRenamed.isDeliveryDriverUpdate = 0;
      if (
        DriverTemporaryStorage.value.length !== chooseDriverIds.value.length ||
        VehicleTemporaryStorage.value.length !== chooseCarIds.value.length
      )
        DataSubmitRenamed.isDeliveryDriverUpdate = 1;
      else {
        // 循环对比司机和车辆的信息, 和编辑初始化带出的信息进行比对
        for (const iterator of DriverTemporaryStorage.value) {
          if (chooseDriverIds.value.indexOf(iterator.driverId) === -1) {
            DataSubmitRenamed.isDeliveryDriverUpdate = 1;
            break;
          }
        }

        // 查看司机是否被改, 被改则跳过循环
        if (DataSubmitRenamed.isDeliveryDriverUpdate === 0) {
          for (const iterator of VehicleTemporaryStorage.value) {
            if (chooseCarIds.value.indexOf(iterator.vehicleId) === -1) {
              DataSubmitRenamed.isDeliveryDriverUpdate = 1;
              break;
            }
          }
        }
      }

      delete DataSubmitRenamed.stockup; //删除不需要的参数
      DataSubmitRenamed.stockupInfo = DataSubmit.value.stockup; //把原来的参数赋值给新对象名字,这里用于修改对象名字
      DataSubmitRenamed.id = RouteId.value; //修改提交的时候带上参数ID
      const res = await updateDeliveryList(DataSubmitRenamed);
      console.log(res, '修改之后提交的返回值');
      code = res.data.code;
    } else {
      // 新增信息

      console.log(DataSubmit.value, '准备提交的信息');
      const res = await deliveryBusinessTask(DataSubmit.value);
      code = res.data.code;
      console.log(res, '新增之后的返回值');
    }
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    editLoading.value = false; //关闭提交加载

    if (code !== 200) return;
    state.value = false; //重置满足条件
    ElMessage.success('操作成功');

    ElMessageBox.alert('操作成功', '', {
      confirmButtonText: '关闭',
      callback: (action: Action) => {
        handleBack();
      },
      type: 'success',
      draggable: true,
    }).catch(() => {
      handleBack();
    });
  }
  console.log(DataSubmit.value, '准备提交的信息');
};
// 备货区域
</script>

<style lang="scss" scoped>
.orderPage,
.orderPageS {
  height: 100%;
  :deep(.el-form) {
    display: flex;
    align-items: flex-start;
    .el-form-item {
      flex-direction: column;
      margin-bottom: 0;
      width: 356px;
    }
  }
  :deep(.el-tabs--border-card) {
    // border: none;
    // overflow-y: hidden;
    height: 100%;
  }
}
.orderPageS {
  :deep(.el-form) {
    .el-form-item {
      width: 330px;
    }
  }
}

.leftInfo {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
  :deep(.el-input__wrapper) {
    min-height: 30px;
  }

  :deep(.el-form-item__label) {
    justify-content: flex-start;
  }
}
.wxInfo {
  :deep(.el-input) {
    width: 239px;
  }
}
:deep(.el-form-item__content) {
  align-items: flex-start;
  .el-select {
    width: 238px !important;
  }
}
.Information {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  .infoCls {
    display: flex;
    align-items: flex-start;
    .el-input {
      width: 238px !important;
    }
    span {
      width: 118px;
      height: 32px;
      display: block;
    }
    .Infos {
      margin-right: 120px;
    }
  }
}
:deep(.el-select-tags-wrapper) {
  width: 100%;
  margin-left: 11px;
  display: flex !important;
  flex-direction: column !important;

  .el-tag {
    border-bottom: 1px solid #ccc;
    justify-content: space-between;
    width: 100%;
    background-color: transparent;
  }
}
.time {
  :deep(.el-input) {
    width: 239px;
  }
}
.StockUParea {
  :deep(.el-form-item) {
    margin-bottom: 20px !important;
  }
}
.notes {
  width: 100%;
  :deep(.el-form-item) {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
.move {
  cursor: pointer;
}
// 表格
// 最外层 IDV
.el-content-el {
  padding: 0 8px;
  padding-top: 8px;
  background-color: #fff;
  height: 100%;
  box-sizing: border-box;
  overflow-y: hidden; //防止页面重新计算高度的时候出现滚动条闪烁
  // 表格顶部按钮
  :deep(.el-Cart-button) {
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
  }
  // 表格顶部左侧、右侧按钮样式
  .el-Cart-button-left,
  .el-Cart-button-right {
    display: flex;
    justify-content: space-between;
    margin: 0 0px;
  }

  .el-Cart-button-left {
    width: 100%;
    :deep(button) {
      padding: 0 14px;
      min-width: 70px;
      display: flex;
      span {
        width: 100%;
        display: inline-flex;
        align-items: center;
        justify-content: space-between;
        i {
          margin-right: 6px;
        }
      }
    }
  }
  .el-Cart-button-right {
    display: flex;
    margin: 0 0px;
    justify-content: space-between;
    align-items: center;
    button {
      background-color: transparent;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #ccc;
      margin-right: 8px;

      &:hover {
        background-color: #172e601f;
        i {
          color: #0e2549;
        }
      }
      // 去掉最后一个按钮右侧边距
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .el-Cart {
    // 表格标题颜色
    :deep(.el-table__header) {
      th {
        background-color: #fafafa;
        color: #000;
      }
    }
    // 组件样式开始
    // 分页样式
    .demo-pagination-block {
      display: flex;
      justify-content: flex-end;
      margin-top: 6px;
    }

    // 表格行高度
    // :deep(.el-table__row) {
    //   height: 60px;
    // }
    // 表格图片
    .el-Img {
      width: 100%;
      height: 40px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  // 新增数据弹窗组件样式
  :deep(.addlalog) {
    // 弹窗

    .el-dialog__header {
      border-bottom: 1px solid #172e607d;
      margin-right: 0;
      margin-bottom: 0;
      padding-bottom: 20px;
      position: relative;
      i {
        color: #172e60;
        border-radius: 50%;
        border: 1px solid;
        transition: transform 1s;
      }
    }

    .el-dialog__header button:hover {
      i {
        transform: rotate(360deg);
      }
    }
    // 弹窗标题左侧小竖线
    .el-dialog__header::after {
      content: '';
      display: block;
      width: 3px;
      height: 16px;
      background-color: #172e60;
      position: absolute;
      left: 8px;
      top: 24px;
    }
    .el-dialog__body {
      padding: 8px;
      .el-form {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
      .el-form-item {
        width: 276px;
        flex-direction: row;
        .el-form-item__label {
          justify-content: flex-start;
        }
      }
      /* 去掉第三个、第六个、第九个div的右外边距 */
      .el-form-item:nth-child(2n) {
        margin-right: 0;
      }
    }

    .el-form-item__content {
      height: 30px;
      // 日期选择框
      .el-input {
        width: 100%;
        height: 30px !important;
      }
      //  下拉选择框
      .el-select {
        width: 100%;
      }
    }
    // 弹窗分页样式
    .TCdemo-pagination-block {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 28px;
    }
  }

  // 底部提交
  :deep(.el-dialog-button) {
    display: flex;
    justify-content: flex-end;
  }
  .el-dialog-button button:hover {
    color: #fff;
    background-color: #10d070;
    transition: all 0.3s ease-in-out; /* 添加动画效果 */
    background-color: #10d070;
    border: 1px solid #10d070;
  }
  // 图片上传
  .img-icon {
    width: 100%;
    position: relative;
    .el-button {
      width: 100%;
      background-color: #fff;
      color: #a8abb9;
      justify-content: flex-start;
      border: 1px solid #dcdfe6;
    }
    i {
      position: absolute;
      left: 110px;
      top: 8px;
      font-size: 18px;
    }
  }
  :deep(.el-load-img) {
    width: 100%;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-image {
      width: 100%;
      height: auto;
      img {
        width: 100%;
      }
    }
    .el-image-viewer__canvas {
      img {
        width: 50%;
        height: 50%;
        z-index: 10;
      }
    }
    .el-z {
      .el-image {
        position: absolute;
        height: 28px;
        top: 2px;
        left: 1px;
      }
    }
    .el-icon {
      color: #10d070;
    }
  }
  :deep(.upload-demo) {
    width: 100%;
    .el-upload {
      width: 100%;
    }
    ul {
      margin-top: 0;
    }
  }
  // 图片上传成功
  .el-img {
    border: 1px solid #ccc;
    width: 100%;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 30px;
    position: absolute;
    top: 0;
    left: 0;
    .el-img-left {
      display: flex;
      align-items: center;
      span {
        z-index: 9;
      }
      i {
        margin-right: 8px;
        color: #10d070;
        z-index: 9;
      }
    }
    i {
      color: #10d070;
      margin-left: 6px;
    }
  }
  // 侧边弹窗功能样式
  :deep(.el-menu-load) {
    .el-drawer__header {
      padding: 0;
      padding-left: 20px;
      position: relative;
      border-bottom: 1px solid #172e5f;
      margin-bottom: 0;
      i {
        color: #172e60;
      }
    }
    .el-drawer__header::after {
      content: '';
      display: block;
      width: 4px;
      height: 18px;
      background-color: #172e60;
      position: absolute;
      top: 23px;
      left: 9px;
    }
    .el-table__inner-wrapper {
      .cell {
        text-align: center;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .el-table__row {
        height: 40px;
        .el-btn-danger {
          background-color: #f56c6c !important;
          border: 1px solid #f56c6c;
        }
      }
    }
    // 上移,下移按钮
    .el-text {
      margin: 0 5px;
    }
    // 按钮功能样式标题
    .el-title-btn {
      margin-bottom: 20px;
    }
  }
  .el-table__row {
    height: 40px;

    // 链接样式风格(默认)
    .el-Btn-link {
      .el-btn-danger,
      .el-btn-success,
      .el-btn-view {
        color: #172e60;
        background-color: transparent;
        border: 1px solid transparent;
      }
    }
    // 按钮样式风格
    .el-Btn-btn {
      // 删除按钮颜色
      .el-btn-danger {
        background-color: #f56c6c;
        border: 1px solid #f56c6c;
        color: #fff;
        padding: 5px 11px;
      }
      // 编辑按钮颜色
      .el-btn-success {
        background-color: #409eff;
        border: 1px solid #409eff;
        color: #fff;
        padding: 5px 11px;
      }
      // 查看按钮颜色
      .el-btn-view {
        background-color: #172e60;
        border: 1px solid #172e60;
        color: #fff;
        padding: 5px 11px;
      }
    }
  }
  //   弹窗表格
  .addlalogS {
    :deep(.el-dialog) {
      width: 81%;
      min-height: 70%;
      margin-top: 0;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .el-Cart-button-btn {
    display: flex;
    justify-content: space-between;
    margin-top: 18px;
  }
}

:deep(.SoInput) {
  width: 100%;
  transition: all 0.5s;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  .el-form {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 360px;
      display: flex;
      align-items: center;
      justify-items: center;
      margin-bottom: 8px;
      margin-right: 18px;
      justify-content: space-between;
      flex-direction: row;
    }
    .el-form-item__label {
      margin-bottom: 0;
    }
    .el-form-item__content {
      width: 259px;
    }
  }
  // 右侧搜索清空按钮样式
  .SoBtn {
    display: flex;
    margin-left: auto;
    margin-bottom: 8px;
    .SoEmpty {
      background-color: transparent;
      color: #000;
      border: 1px solid #ccc;
    }
  }
}

.iszer {
  :deep(.cell) {
    display: flex;
    padding: 0;
    align-items: center;
    justify-content: center;
    .el-input-number {
      width: 100%;
    }
  }
  .isZel-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 26px;
  }
}
.el_multifunctional {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 24%;
  .el-input {
    margin-right: 4px;
  }
  button {
    width: 100px;
  }
}

.static-class {
  padding: 0 4px;
  scroll-behavior: smooth;
  background-color: #ff0000;
  color: #fff;
}
.el_package {
  :deep(.el-form) {
    justify-content: flex-start !important;
  }
}
.el_tool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-width: 300px;
  font-size: 14px;
}
</style>
