<template>
  <basic-container>
    <div
      class="avue-crud"
      v-loading="details.loadingObj.pageLoading"
      element-loading-text="数据加载中..."
    >
      <!-- 基础信息 -->
      <div class="w100">
        <!-- 标题 -->
        <el-divider content-position="left">基础信息</el-divider>
        <!-- 表单内容 -->
        <el-form :rules="details.rules" :model="details.form" ref="ruleFormRef" label-width="80px">
          <!-- 仓库节点 -->
          <el-steps finish-status="success" :active="details.active" space="300px">
            <el-step v-for="(item, index) in details.nodeInfoData" :key="item">
              <template #icon>
                <el-icon size="20px" v-if="index === 0"><LocationFilled /></el-icon>
                <el-icon size="20px" v-else><Van /></el-icon>
              </template>
              <template #title>
                <div class="form_row">
                  <div class="flex-c-c steps_title">
                    <div class="count_icon">{{ index + 1 }}</div>
                    <div v-if="index === 0">始发仓</div>
                    <div v-else>目的仓</div>
                  </div>

                  <!-- 控件 -->
                  <div v-if="Number(details.pageType) !== 3">
                    <!-- 删除节点 -->
                    <el-button
                      icon="Delete"
                      v-if="index !== 0"
                      @click="handleDelNode(index, item)"
                    />
                    <!-- 新增节点 -->
                    <el-button
                      v-if="
                        (index === details.nodeInfoData.length - 1 && index === 0) || index !== 0
                      "
                      type="primary"
                      icon="Plus"
                      @click="handleAddNode(index)"
                    />
                  </div>
                </div>
              </template>
              <template #description>
                <el-select
                  class="mt10"
                  ref="selectNodeRef"
                  v-model="item.nodeName"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="目的仓"
                  @change="val => destinationWarehouseNameChange(val, index)"
                  :remote-method="remoteMethod"
                  :loading="details.loadingObj.loading"
                  :disabled="
                    Number(details.pageType) === 3
                      ? true
                      : Number(details.pageType) === 1
                      ? index === 0
                      : index <= details.active
                  "
                >
                  <!--  Number(details.pageType) !== 3 &&
                   ( Number(details.pageType) === 1 ||
                    index === 0) ||
                    (Number(details.pageType) === 2 ||
                    index > details.active) -->
                  <el-option
                    v-for="val in details.options"
                    :key="val.warehouseName"
                    :disabled="
                      details.nodeInfoData.findIndex(value => value.nodeId === val.warehouseId) !==
                      -1
                    "
                    :label="val.warehouseName"
                    :value="val.warehouseId"
                  />
                </el-select>
              </template>
            </el-step>
          </el-steps>

          <!-- 第一排 -->
          <div class="form_row mt10">
            <!-- 车牌号 -->
            <div class="form_row_item">
              <el-form-item label="车牌号" prop="carNumber">
                <el-select
                  v-model="form.carNumber"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入并选择车牌号"
                  @change="handleCarChange"
                  :remote-method="remoteMethodCar"
                  :loading="details.loadingObj.loading"
                >
                  <el-option
                    v-for="val in details.carListByName"
                    :key="val.carNumber"
                    :label="val.carNumber"
                    :value="val.carId"
                  />
                </el-select>
              </el-form-item>
              <el-button type="primary" @click="handleAddCar" icon="Plus"></el-button>
            </div>

            <!-- 主驾司机 -->
            <div class="form_row_item">
              <el-form-item inline label="主驾司机" prop="driverName">
                <el-select
                  v-model="form.driverName"
                  filterable
                  remote
                  @change="handleNameChange(1)"
                  reserve-keyword
                  placeholder="请输入并选择司机名称"
                  :remote-method="remoteMethodDriver"
                  :loading="details.loadingObj.loading"
                >
                  <el-option
                    v-for="val in details.driverListByName"
                    :key="val.driverName"
                    :label="val.driverName"
                    :value="val.driverId"
                  />
                </el-select>
              </el-form-item>
              <el-button type="primary" @click="handleAddDriver" icon="Plus"></el-button>
            </div>

            <!-- 外请人 -->
            <div
              class="form_row_item"
              v-if="Number(form.driverType) === 3 || Number(form.driverType) === 4"
            >
              <el-form-item inline label="外请人">
                <!-- <el-select
                  v-model="form.assistantName"
                  filterable
                  remote
                  reserve-keyword
                  @change="handleNameChange(2)"
                  placeholder="请输入并选择外请人"
                  :remote-method="remoteMethodDriver"
                  :loading="details.loadingObj.loading"
                >
                  <el-option
                    v-for="val in details.driverListByName"
                    :key="val.driverName"
                    :label="val.driverName"
                    :value="val.driverId"
                  />
                </el-select> -->

                <el-input v-model="form.outDriverPerson" placeholder="请输入外请人" />
              </el-form-item>
            </div>

            <!-- 副驾司机 -->
            <div class="form_row_item">
              <el-form-item inline label="副驾司机">
                <el-select
                  v-model="form.assistantName"
                  filterable
                  remote
                  reserve-keyword
                  @change="handleNameChange(2)"
                  placeholder="请输入并选择司机名称"
                  :remote-method="remoteMethodDriver"
                  :loading="details.loadingObj.loading"
                >
                  <el-option
                    v-for="val in details.driverListByName"
                    :key="val.driverName"
                    :label="val.driverName"
                    :value="val.driverId"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 装车方式 -->
            <div class="form_row_item">
              <el-form-item inline label="装车方式" prop="loadingType">
                <el-radio-group v-model="form.loadingType" class="ml-4">
                  <el-radio label="1" size="large">手动装车(后台)</el-radio>
                  <el-radio label="2" size="large">扫描装车</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>

          <!-- 第二排 -->
          <div class="form_row">
            <!-- 经办人 -->
            <div class="form_row_item">
              <el-form-item inline label="经办人">
                <el-input v-model="form.operator" readonly />
              </el-form-item>
            </div>

            <!-- 配载类型 -->
            <div class="form_row_item">
              <el-form-item inline label="配载类型" prop="loadType">
                <el-select v-model="form.loadType" class="m-2" filterable placeholder="配载类型">
                  <el-option
                    v-for="item in details.pageInfo.loadType"
                    :key="item.dictValue"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 分摊方式 -->
            <div class="form_row_item">
              <el-form-item inline label="分摊方式" prop="chargeType">
                <el-select v-model="form.chargeType" class="m-2" filterable placeholder="分摊方式">
                  <el-option
                    v-for="item in details.pageInfo.chargeType"
                    :key="item.dictValue"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 合计运费 -->
            <div class="form_row_item">
              <el-form-item inline label="合计运费">
                <el-input-number
                  :controls="false"
                  v-model="form.countTransportCost"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  :step="1"
                  readonly
                />
              </el-form-item>
            </div>

            <!-- 预计发车 -->
            <!--             <div class="form_row_item">
              <el-form-item inline label="预计发车">
                <el-input />
              </el-form-item>
            </div> -->
          </div>

          <!-- 备注 -->
          <el-form-item label="备注">
            <el-input autosize v-model="form.remark" type="textarea" placeholder="备注" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 节点信息 -->
      <div class="w100">
        <!-- 标题 -->
        <el-divider content-position="left">节点信息</el-divider>

        <tablecmt
          class="nodeInfo"
          :columnList="details.nodeInfoColumnList"
          :tableData="details.nodeInfoData"
          :loading="loadingObj.stowageLoading"
          ref="nodeInfoRef"
          :isShowRefresh="false"
        >
          <template #default="slotProps">
            <el-input-number
              :controls="false"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="1"
              :disabled="slotProps.scope.row.blackList.includes(slotProps.scope.column.property)"
              :value-on-clear="0"
              @change="handleComputedNum"
              v-model.lazy="slotProps.scope.row[slotProps.scope.column.property]"
            />
          </template>
        </tablecmt>
        <!-- 列表 -->
      </div>

      <!-- 订单池和调度池 -->
      <template v-if="Number(details.pageType) !== 3 && details.nodeInfoData.length > 1">
        <div class="add_row" v-for="(item, index) in details.nodeInfoData">
          <template v-if="index > details.warehouseIndex">
            <div style="width: 49%">
              <!-- 头部 -->
              <el-divider content-position="left">
                <span style="margin-right: 20px">{{
                  details.nodeInfoData[details.warehouseIndex].nodeName
                }}</span>
                <span>运单池</span>
              </el-divider>

              <!-- 搜索区域 -->
              <div v-h5uShow="!search">
                <el-form inline label-width="80px" :model="details.oldQuery" class="el-fr-d">
                  <!-- <el-form-item label="订单号" class="el-times">
                    <el-input v-model.trim="query.orderCode" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="目的网点" class="el-times">
                    <el-input></el-input>
                  </el-form-item>
                  <el-form-item label="到站" class="el-times">
                    <el-input></el-input>
                  </el-form-item>
                  <el-form-item label="目标品类" class="el-times">
                    <el-input></el-input>
                  </el-form-item>
                  <el-form-item label="备注" class="el-times">
                    <el-input></el-input>
                  </el-form-item>
                  <el-form-item label="托盘码" class="el-times">
                    <el-input></el-input>
                  </el-form-item> -->
                  <el-form-item label="开单时间" class="el-times">
                    <el-date-picker
                      v-model="query.enterTime"
                      type="daterange"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :shortcuts="shortcuts"
                      clearable
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                  <el-form-item label="入库时间" class="el-times">
                    <el-date-picker
                      v-model="query.openTime"
                      type="daterange"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :shortcuts="shortcuts"
                      clearable
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="searchChange"
                      >搜 索</el-button
                    >
                    <el-button icon="el-icon-delete" @click="searchReset">重 置</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 控件 -->
              <div style="margin-bottom: 10px" class="flex-c-sb">
                <!-- 控件 -->
                <div class="avue-crud__right">
                  <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
                  <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
                </div>

                <el-button type="text" style="cursor: pointer" @click="handleAddWaybill(index)">
                  加入调度池
                  <el-icon><CaretRight /></el-icon>
                </el-button>
              </div>

              <!-- 列表模块 -->
              <tablecmt
                ref="oldColumnListNode"
                class="columnList"
                :columnList="details.columnList"
                :tableData="details.data"
                @inputTxt="inputsc"
                :loading="loadingObj.oldListLoading"
                @selection="selectionChange"
              >
              </tablecmt>

              <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
                <div class="total_row" style="margin-top: 0">
                  选中: {{ details.selectionList.length }}
                </div>

                <!-- 分页模块 -->
                <el-pagination
                  style="zoom: 0.9"
                  align="right"
                  background
                  @size-change="sizeChange"
                  @current-change="currentChange"
                  :current-page="page.pageNum"
                  :teleported="false"
                  :page-sizes="[30, 50, 80, 120]"
                  :page-size="page.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="page.total"
                >
                </el-pagination>
              </div>
            </div>

            <!-- 列表模块 -->
            <div style="width: 49%">
              <!-- 头部 -->
              <el-divider content-position="left">
                <span style="margin-right: 20px">{{ item.nodeName }}</span>
                <span>调度池</span>
              </el-divider>

              <!-- 搜索区域 -->
              <div v-h5uShow="!search">
                <el-form
                  :inline="true"
                  label-width="80px"
                  :model="details.newQuery"
                  class="el-fr-d"
                >
                  <!-- <el-form-item label="关键词" class="el-times">
                      <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="目的网点" class="el-times">
                      <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="到站" class="el-times">
                      <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="目标品类" class="el-times">
                      <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="备注" class="el-times">
                      <el-input></el-input>
                    </el-form-item>
                    <el-form-item label="托盘码" class="el-times">
                      <el-input></el-input>
                    </el-form-item> -->
                  <el-form-item label="开单时间" class="el-times">
                    <el-date-picker
                      v-model="item.createTimeArr"
                      type="daterange"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :shortcuts="shortcuts"
                      clearable
                      @change="value => item.itemTimesc(value, { prop: 'createTimeArr' })"
                    />
                  </el-form-item>
                  <el-form-item label="入库时间" class="el-times">
                    <el-date-picker
                      v-model="item.openTimeArr"
                      type="daterange"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      :shortcuts="shortcuts"
                      clearable
                      value-format="YYYY-MM-DD"
                      @change="value => item.itemTimesc(value, { prop: 'openTimeArr' })"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="() => item.itemFilterData()"
                    >
                      搜 索
                    </el-button>
                    <el-button icon="el-icon-delete" @click="() => item.itemClearQuery()">
                      重 置
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 控件 -->
              <div style="margin-bottom: 10px" class="flex-c-sb">
                <el-button type="text" class="pointer" @click="handleRemoveWaybill(index)">
                  <el-icon><CaretLeft /></el-icon>
                  移除调度池
                </el-button>

                <!-- 展开搜索和刷新 -->
                <div class="avue-crud__right">
                  <!-- <el-button
                    icon="el-icon-refresh"
                    @click="handleNewDataRefresh(item)"
                    circle
                  ></el-button> -->
                  <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
                </div>
              </div>

              <!-- 列表 -->
              <tablecmt
                class="columnList"
                ref="newColumnListNode"
                :columnList="item.newColumnList"
                :tableData="item.renderData"
                :loading="item.loading"
                @inputTxt="(value, row) => item.itemInputsc(value, row, index)"
                @selection="list => item.selectionChange(list, index)"
                :isselectfun="
                  row => {
                    return !Boolean(row.realNum);
                  }
                "
              >
                <template #default="slotProps">
                  <template v-if="slotProps.scope.column.label === '计划数'">
                    <el-input-number
                      :controls="false"
                      v-if="Number(details.pageType) === 1 || !slotProps.scope.row.carsOrderId"
                      v-model="slotProps.scope.row.planNum"
                      controls-position="right"
                      :precision="0"
                      :min="slotProps.scope.row.realNum || 1"
                      :max="slotProps.scope.row.stockNum"
                      :step="1"
                    />

                    <el-text
                      size="small"
                      v-else
                      text
                      @click="handleEditplanNum(slotProps.scope, item)"
                      >{{ slotProps.scope.row.planNum }}</el-text
                    >
                  </template>
                </template>
              </tablecmt>

              <div class="total_row">
                <span> 选中: {{ item.selectionList.length }} 条 </span>
                <span> 共 {{ item.lineCarsOrderList.length }} 条 </span>
              </div>
            </div>
          </template>
        </div>
      </template>

      <!-- 页面底部占位 -->
      <div class="footer"></div>
      <!-- 底部提交 -->
      <div class="button-container">
        <el-button class="submitButton" icon="CircleClose" @click="back"> 关闭 </el-button>

        <el-button
          class="submitButton"
          icon="Promotion"
          type="primary"
          :loading="btnLoadingObj.submitBtn"
          @click="handleSubmit(ruleFormRef)"
        >
          提交
        </el-button>
      </div>
    </div>
  </basic-container>

  <!-- 修改计划数量 -->
  <el-dialog
    title="修改计划数量"
    v-model="details.popUpShow.editPlanNumberVisited"
    width="40%"
    append-to-body
    class="packageDetailColumnListVisited"
  >
    <div class="edit_title">订单号: {{ details.editInfo.orderCode }}</div>
    <div class="flex-c-sb edit_row">
      <div class="flex1">
        <span>当前在库数</span>
        {{ details.editInfo.stockNum }}
      </div>
      <div class="flex1">
        <span>已装车数量</span>
        {{ details.editInfo.realNum }}
      </div>
    </div>
    <el-form>
      <el-form-item label="计划数量：" label-width="100px">
        <el-input-number
          :controls="false"
          controls-position="right"
          :min="0"
          :precision="0"
          :max="details.editInfo.stockNum"
          class="editInput"
          v-model="details.editInfo.enterPlanNum"
          style="flex: 1; text-align: left !important"
        />
      </el-form-item>
    </el-form>
    <div class="flex-c-c">
      <el-button @click="details.popUpShow.editPlanNumberVisited = false">取消</el-button>
      <el-button
        type="primary"
        :loading="btnLoadingObj.editPlanNumBtn"
        icon="Promotion"
        @click="handleSubmitEdit"
      >
        提交
      </el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: '/distribution/artery/AddVehicleStowage',
};
</script>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, onActivated, watch } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  setNodeHeight,
  computeNumber,
  isNumber,
  deepClone,
  debounce,
  handleClearTableQuery,
} from '@/utils/util';
import {
  columnList,
  nodeInfoColumnList,
  newColumnList,
} from '@/option/distribution/addVehicleStowage';
import {
  postloadFindLoadInitData,
  postFindWarehouseListByName,
  postFindAllOrderList,
  postFindCarListByName,
  postFindDriverListByName,
  postSaveNew,
  postSelectEditDetailByLoadId,
  postFindUseOrderList,
  postRemoveCarsOrderByCarsOrderId,
  postUpdatePlanNumByCarsOrderId,
  postAddOrderToFinalNodeId,
  postUpdateCarsLoadBasicData,
  postUpdateLoadFeeByNodeId,
} from '@/api/distribution/AddVehicleStowage';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import type { FormInstance, FormRules } from 'element-plus';

// 获取节点信息列表, 除开节点名称
const nodeInfokeys = nodeInfoColumnList.slice(1).map(val => val.prop);

// 获取路由实例
const $router = useRouter();
const $route = useRoute();

// vuex 实例
const $store = useStore();

// 表单实例
const ruleFormRef = ref();

// 节点下拉框实例
const selectNodeRef = ref();

// 获取用户信息
const userInfo = computed(() => $store.state.user.userInfo);

const details = reactive<any>({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  /** 时间快捷选择设置 */
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ],
  /** 时间选择器数据 */
  stockupDate: [],
  /** 订单池表头 */
  columnList: deepClone(columnList),
  /** 调度池表头 */
  newColumnList: deepClone(newColumnList),
  /** 节点信息列表表头 */
  nodeInfoColumnList: deepClone(nodeInfoColumnList),
  /** 列表数据 */
  data: [],
  /** 节点信息数据 */
  nodeInfoData: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    oldListLoading: false,
    loading: false,
    /** 整页loading */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 装车明细分页参数 */
  trickleLoadingPage: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 修改计划数量 */
    editPlanNumberVisited: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: { loadingType: '2', chargeType: '1', loadType: '1' },
  /** 全屏 */
  fullscreenObj: {
    /** 装车明细 */
    truckLoadingDetailPopUp: false,
  },
  /** 匹配 */
  rules: {
    /** 车牌号 */
    carNumber: [
      {
        required: true,
        message: '请填写并选择车牌号',
        trigger: ['change'],
      },
    ],
    /** 主驾司机 */
    driverName: [
      {
        required: true,
        message: '请填写并选择主驾司机',
        trigger: ['change'],
      },
    ],
    /** 装车方式 */
    loadingType: [
      {
        required: true,
        message: '请选择装车方式',
        trigger: ['change'],
      },
    ],
    /** 配载类型 */
    loadType: [
      {
        required: true,
        message: '请选择配载类型',
        trigger: ['change'],
      },
    ],
    /** 分摊方式 */
    chargeType: [
      {
        required: true,
        message: '请选择分摊方式',
        trigger: ['change'],
      },
    ],
  },
  /** 页面信息 */
  pageInfo: {
    startWarehouseInfo: {},
  },
  /** 目的仓 */
  options: [],
  /** 车牌号 */
  carListByName: [],
  /** 司机 */
  driverListByName: [],
  /** 当前页面类型 -- 1: 新增; 2: 编辑; 3: 节点费用 */
  pageType: 1,
  /** 编辑&节点费用下的loadId */
  loadId: '',
  /** 编辑模式下当前仓的位置索引 */
  warehouseIndex: 0,
  /** 步骤条激活位置 */
  active: computed(() => {
    if (Number(details.pageType) === 1) return details.nodeInfoData.length + 1;
    else if (Number(details.pageType) === 2) return details.warehouseIndex;
  }),
  /** 被选中的orderCode组成的list */
  orderCodeList: [],
  /** 计划数修改的信息 */
  editInfo: {},
  /** 所有的仓库节点id组成的list */
  allCarsLineList: [],
  /** 编辑时记录被删除的node节点信息 */
  remveNodeList: [],
});

const btnLoadingObj = reactive({
  /** 提交按钮 */
  submitBtn: false,
  /** 修改计划数量 */
  editPlanNumBtn: false,
});
const {
  search,
  query,
  shortcuts,
  stockupDate,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
  zeroAdditionalRecordingInfo,
  popUpShow,
  form,
} = toRefs(details);

// 列表组件实例 -- 节点信息
const nodeInfoRef = ref(null);

const oldColumnListNode = ref();
const newColumnListNode = ref();

/** vuex */
const permission = computed(() => mapGetters(['permission', 'tagWel', 'tagList']));

/** 设置页面表格高度 */
const setTabelHeight = async () => {
  // 等待子组件渲染完成
  await nextTick();

  const _listNode = document.querySelectorAll('.columnList.maboxhi');

  // 节点信息列表高度
  setNodeHeight(nodeInfoRef.value.$el, 'auto');

  if (_listNode.length === 0) return;
  setNodeHeight(_listNode, '55vh');
};

// 初始化设置列表高度
onMounted(() => {
  setTabelHeight();
});

// 清空复选框
const clearSelectionList = () => {
  details.selectionList = [];
  newColumnListNode.value.forEach(val => {
    val.handleCheckSelect([]);
  });
  oldColumnListNode.value.forEach(val => {
    val.handleCheckSelect([]);
  });
};

/** 设置节点费用禁用 */
const handleEditForbidden = (_arr: any[]) => {
  if (_arr.length === 0) return;

  // 获取第一项 (第一项和后续项禁用项不同, 分开设置)
  const _firstChild = _arr[0];
  _firstChild.blackList = ['unloadCost', 'unloadOtherCost'];

  const _otherList = _arr.slice(1);

  // 其它项的白名单
  const _otherwhiteList = ['tollFee', 'reachTransportCost'];
  // 通过白名单筛选出黑名单
  const _otherBlackList = nodeInfokeys.filter(val => _otherwhiteList.indexOf(val) === -1);
  // 设置其他项的黑名单;
  for (let item of _otherList) {
    item.blackList = _otherBlackList;
  }

  return [_firstChild, ..._otherList];
};

/** 请求运单数据 */
const initOriginWarehouseOrder = debounce(async (params = {}) => {
  try {
    details.loadingObj.oldListLoading = true;
    const submitData = {
      ...details.page,
      orderCodes: details.orderCodeList,
      ...details.query,
      ...params,
      isTransfer: 0,
    };

    for (const key in submitData) {
      const value = submitData[key];
      if (!value && value !== false && value !== 0) delete submitData[key];
    }

    delete submitData.enterTime;
    delete submitData.openTime;

    if (Number(details.pageType) === 2) submitData.loadId = details.loadId;
    if (submitData.orderCodes.length === 0) delete submitData.orderCodes;
    const res = await postFindAllOrderList(submitData);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.oldListLoading = false;
  }
}, 100);

/** 请求添加在调度池中的数据 */
const initDispatchOrder = async item => {
  try {
    // 开启列表加载动画
    item.loading = true;
    const submitData = {
      loadId: details.loadId,
      finalNodeId: item.nodeId,
    };
    const res = await postFindUseOrderList(submitData);
    const { code, data } = res.data;
    if (code !== 200) return;
    item.lineCarsOrderList = data;
    item.renderData = data;
    item.MappingData = deepClone(data);

    details.orderCodeList = [
      ...new Set([
        ...details.orderCodeList,
        ...data.map(val => val.orderCode + ',' + val.waybillNo),
      ]),
    ];
  } catch (error) {
  } finally {
    // 关闭列表加载动画
    item.loading = false;

    return null;
  }
};

/** 请求页面数据 */
const onLoad = async () => {
  // 获取当前页面的信息
  details.loadId = $route.query.loadId;
  details.pageType = $route.query.type;

  try {
    details.loadingObj.pageLoading = true;

    // 新增
    if (Number(details.pageType) === 1) {
      details.form = { loadingType: '2', chargeType: '1', loadType: '1' };
      const res = await postloadFindLoadInitData();
      const { code, data } = res.data;
      if (code !== 200) return;
      details.pageInfo = data;
      details.nodeInfoData = [
        {
          nodeName: data.startWarehouseInfo.warehouseName,
          nodeId: data.startWarehouseInfo.warehouseId,
          linkMan: data.startWarehouseInfo.linkMan,
          linkPhone: data.startWarehouseInfo.linkMobile,
          linkAddress: data.startWarehouseInfo.linkAddress,
        },
      ];
      details.nodeInfoData = handleEditForbidden(details.nodeInfoData);
      details.form.startWarehouseName = data.startWarehouseInfo.warehouseName;
      details.form.startWarehouseId = data.startWarehouseInfo.warehouseId;
      details.form.operator = userInfo.value.nick_name;
    }
    // 编辑
    else {
      const res = await postSelectEditDetailByLoadId({ loadId: details.loadId });
      const { code, data } = res.data;
      if (code !== 200) return;

      details.allCarsLineList = data.allWarehouseIds;

      const promiseArr = [];

      details.nodeInfoData = handleEditForbidden(
        data.allCarsLineList.map((val, index) => {
          const _node = {
            ...val,
            // 筛选
            query: {},
            // 时间筛选
            timeQuery: {},
            // 复选框
            selectionList: [],
            // 参数
            lineCarsOrderList: [],
            /** 渲染数据 */
            renderData: [],
            // 克隆表头
            newColumnList: deepClone(newColumnList),
            loading: false,
            selectionChange(list, index) {
              details.nodeInfoData[index].selectionList = list;
            },
            itemInputsc(value, { prop }, index) {
              console.log('this :>> ', this);

              // 动态设置正则
              const reg = new RegExp('^' + value);

              this.query[prop] = reg;

              if (value === '') delete this.query[prop];

              this.itemFilterData();
            },
            itemTimesc(value, { prop }) {
              this.timeQuery[prop] = value;

              if (!value) delete this.timeQuery[prop];

              // this.itemFilterData();
            },
            /** 筛选数据 */
            itemFilterData() {
              if (Object.keys(this.query).length === 0 && Object.keys(this.timeQuery).length === 0)
                return (this.renderData = this.lineCarsOrderList);

              let _filterArr = [];
              for (let i = 0; i < this.lineCarsOrderList.length; i++) {
                const value = this.lineCarsOrderList[i];

                let _flag = true;
                for (let key in this.query) {
                  if (!this.query[key].test(value[key])) _flag = false;
                  if (!_flag) break;
                }

                if (!_flag) continue;

                for (let key in this.timeQuery) {
                  const item = this.timeQuery[key];
                  console.log('item :>> ', item);

                  const _startTime = Date.parse(item[0]);
                  const _endTime = Date.parse(item[1]) + 1000 * 60 * 60 * 24 - 1;

                  const _time = Date.parse(value[key.replace('Arr', '')]);

                  if (_time !== _time) _flag = false;
                  else if (_time < _startTime || _time > _endTime) _flag = false;

                  if (!_flag) break;
                }
                if (_flag) _filterArr.push(value);
              }

              this.renderData = _filterArr;
            },
            /** 清空搜索的值 */
            itemClearQuery() {
              this.query = {};
              this.timeQuery = {};
              handleClearTableQuery(this.newColumnList);
              this.itemFilterData();
            },
            MappingData: [],
          };

          if (val.nodeName === data.warehouseName) {
            // 显示当前节点
            details.warehouseIndex = index;
          }
          if (Number(details.pageType) === 2) promiseArr.push(initDispatchOrder(_node));
          return _node;
        })
      );
      details.form = data.carsLoadEntity;
      details.pageInfo.loadType = data.loadType;
      details.pageInfo.chargeType = data.chargeType;
      details.pageInfo.startWarehouseInfo.warehouseId = data.carsLoadEntity.startWarehouseId;
      details.pageInfo.startWarehouseInfo.warehouseName = data.carsLoadEntity.startWarehouseName;
      // 请求节点
      if (Number(details.pageType) === 2) {
        await Promise.all(promiseArr);
        initOriginWarehouseOrder();
      }

      // 设置页面列表高度
      setTabelHeight();
    }
  } catch (error) {
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

// 初始化调用
onLoad();

/** 查询仓库 */
const remoteMethod = async val => {
  // if (!val) return;
  const res = await postFindWarehouseListByName({ warehouseName: val });
  const { code, data } = res.data;
  if (code !== 200) return;
  details.options = data;
};

remoteMethod('');

/** 目的仓选择时给目的仓名称赋值 */
const destinationWarehouseNameChange = (val, index) => {
  const _value = details.options.find(value => value.warehouseId === val);
  details.nodeInfoData[index].nodeName = _value.warehouseName;
  details.nodeInfoData[index].nodeId = _value.warehouseId;
  details.nodeInfoData[index].linkMan = _value.linkMan;
  details.nodeInfoData[index].linkPhone = _value.linkPhone;
  details.nodeInfoData[index].linkAddress = _value.linkAddress;
};

/** 搜索 */
const searchChange = () => {
  console.log('details.query.enterTime :>> ', details.query.enterTime);
  console.log('details.query.openTime :>> ', details.query.openTime);

  if (details.query.enterTime && details.query.enterTime.length > 0) {
    details.query.enterTimeStartStr = details.query.enterTime[0];
    details.query.enterTimeEndStr = details.query.enterTime[1];
  } else {
    delete details.query.enterTimeStartStr;
    delete details.query.enterTimeEndStr;
  }

  if (details.query.openTime && details.query.openTime.length > 0) {
    details.query.openTimeStartStr = details.query.openTime[0];
    details.query.openTimeEndStr = details.query.openTime[1];
  } else {
    delete details.query.openTimeStartStr;
    delete details.query.openTimeEndStr;
  }

  console.log('details.query :>> ', details.query);

  initOriginWarehouseOrder();
};

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.page.pageNum = 1;

  handleClearTableQuery(details.columnList);
  initOriginWarehouseOrder();
};

/** 展开列表控件 */
const showdrawer = (_flag?: boolean) => {
  details.drawerShow = _flag;
};

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  if (index === '') delete details.query[row.prop];
  initOriginWarehouseOrder();
};

/** 表格表头时间选择 */
const timesc = (index, row) => {
  if (!!index) {
    index = dayjs(index).format('YYYY-MM-DD');
  }
  details.query[row.prop] = index;
  if (!index) {
    delete details.query[row.prop];
  }
  initOriginWarehouseOrder();
};

/** 表格表头输入框搜索 */
const btnsc = () => {};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index && index !== 0) delete details.query[row.prop];
  if (row.prop === 'certificateTypeName') {
    details.query['certificateType'] = index;
    if (!index) delete details.query['certificateType'];
  }
  initOriginWarehouseOrder();
};

/** 表格表头复选框选择 */
const selectionChange = (list: any) => {
  details.selectionList = list;
};

/** 每页数量改变执行的回调 */
const sizeChange = (pageSize: number) => {
  details.page.pageSize = pageSize;
  initOriginWarehouseOrder();
};

/** 页码改变执行的回调 */
const currentChange = pageNum => {
  details.page.pageNum = pageNum;
  initOriginWarehouseOrder();
};

/**
 * 设置列表 -- 固定函数
 * 弹窗的勾选回调，用于更改头部数组
 * 固定搭配，只需要更换   columnList
 *  */
const setnewcolum = (newarr, headarr, type) => {
  if (type == 1) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'checkList', headarr);
  } else if (type == 2) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'flexList', headarr);
  } else if (type == 3) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'sortlist', headarr);
  }
};

const handleNewDataRefresh = item => {
  for (let index = 0; index < item.lineCarsOrderList.length; index++) {
    const iterator = item.lineCarsOrderList[index];
    const _code = iterator.orderCode + ',' + iterator.waybillNo;
    const _index = details.orderCodeList.indexOf(_code);
    // 删除映射的订单号+运单号
    details.orderCodeList.splice(_index, 1);
  }

  item.lineCarsOrderList = [];
  item.renderData = [];

  details.page.pageNum = 1;
  initOriginWarehouseOrder();
};

/** 弹出层开启前清除数据 */
const beforeClose = done => {
  done();
  details.form = {};
  details.view = false;
};

/** 司机改变时 1: 主驾 2: 副驾 */
const handleNameChange = (type: number) => {
  const findValue = type === 1 ? form.value.driverName : form.value.assistantName;

  const _value = details.driverListByName.find(value => value.driverId === findValue);
  if (type === 1) {
    form.value.driverName = _value.driverName;
    form.value.driverId = _value.driverId;
    form.value.driverMobile = _value.driverPhone;
    form.value.driverType = _value.driverType;
  } else {
    form.value.assistantName = _value.driverName;
    form.value.assistantMobile = _value.driverPhone;
    form.value.assistantId = _value.driverId;
  }
};

/** 车辆改变 */
const handleCarChange = (type: number) => {
  const _value = details.carListByName.find(value => value.carId === form.value.carNumber);
  form.value.carNumber = _value.carNumber;
  form.value.carId = _value.carId;
};

/** 新增车辆 */
const handleAddCar = () => {
  $router.push('/basicdata/vehicle/basicdataVehicle');
};

/** 新增司机 */
const handleAddDriver = () => {
  $store.commit('DEL_ONCE_TAG', 'basicdataDriverArteryAdd');

  $router.push({
    path: '/basicdata/driverArtery/basicdataDriverArteryAdd',
    query: {
      name: '司机信息新增',
      type: 'add',
      backPatch: '/basicdata/driverArtery/basicdataDriverArtery',
    },
  });
};

/** 计算合计 */
let timer = null;
const handleComputedNum = () => {
  if (timer) clearTimeout(timer);

  timer = setTimeout(() => {
    let _totalNum = 0;

    for (let item of details.nodeInfoData) {
      for (let index = 0; index < nodeInfokeys.length; index++) {
        const _key = nodeInfokeys[index];
        // 检测是否为数字
        if (!isNumber(item[_key])) item[_key] = 0;
        else item[_key] = Number(item[_key]);
        _totalNum = computeNumber(_totalNum, '+', item[_key]).result;
      }
    }

    details.form.countTransportCost = _totalNum;
    // 清除定时器
    clearTimeout(timer);
  }, 1000);
};
// 初始化计算
handleComputedNum();

/** 新增目的仓 */
const handleAddNode = async (index: number) => {
  const _flag = details.nodeInfoData.every(val => val.nodeName);
  if (!_flag) {
    return ElMessage({
      type: 'warning',
      message: '请选择节点仓库',
    });
  }

  details.nodeInfoData.splice(index + 1, 0, {
    // 筛选
    query: {},
    // 时间筛选
    timeQuery: {},
    // 复选框
    selectionList: [],
    // 参数
    lineCarsOrderList: [],
    /** 渲染数据 */
    renderData: [],
    // 克隆表头
    newColumnList: deepClone(newColumnList),
    loading: false,
    selectionChange(list, index) {
      details.nodeInfoData[index].selectionList = list;
    },
    itemInputsc(value, { prop }, index) {
      console.log('this :>> ', this);

      // 动态设置正则
      const reg = new RegExp('^' + value);

      this.query[prop] = reg;

      if (value === '') delete this.query[prop];

      this.itemFilterData();
    },
    itemTimesc(value, { prop }) {
      this.timeQuery[prop] = value;

      if (!value) delete this.timeQuery[prop];

      // this.itemFilterData();
    },
    /** 筛选数据 */
    itemFilterData() {
      if (Object.keys(this.query).length === 0 && Object.keys(this.timeQuery).length === 0)
        return (this.renderData = this.lineCarsOrderList);

      let _filterArr = [];
      for (let i = 0; i < this.lineCarsOrderList.length; i++) {
        const value = this.lineCarsOrderList[i];

        let _flag = true;
        for (let key in this.query) {
          if (!this.query[key].test(value[key])) _flag = false;
          if (!_flag) break;
        }

        if (!_flag) continue;

        for (let key in this.timeQuery) {
          const item = this.timeQuery[key];
          console.log('item :>> ', item);

          const _startTime = Date.parse(item[0]);
          const _endTime = Date.parse(item[1]) + 1000 * 60 * 60 * 24 - 1;

          const _time = Date.parse(value[key.replace('Arr', '')]);

          if (_time !== _time) _flag = false;
          else if (_time < _startTime || _time > _endTime) _flag = false;

          if (!_flag) break;
        }
        if (_flag) _filterArr.push(value);
      }

      this.renderData = _filterArr;
    },
    /** 清空搜索的值 */
    itemClearQuery() {
      this.query = {};
      this.timeQuery = {};
      handleClearTableQuery(this.newColumnList);
      this.itemFilterData();
    },
    MappingData: [],
  });

  // details.nodeInfoData.push();
  details.nodeInfoData = handleEditForbidden(details.nodeInfoData);
  // 始发仓没有数据时, 请求数据
  if (details.data.length === 0) initOriginWarehouseOrder();
  setTabelHeight();
  handleComputedNum();

  await nextTick();
  selectNodeRef.value[selectNodeRef.value.length - 1].focus();
};

/** 删除目的仓 */
const handleDelNode = (index: number, row) => {
  ElMessageBox.confirm('确认删除该节点吗?', '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const value = details.nodeInfoData.splice(index, 1);

      const _id = value[0].id;

      for (const iterator of row.lineCarsOrderList) {
        const _code = iterator.orderCode + ',' + iterator.waybillNo;
        const _index = details.orderCodeList.indexOf(_code);
        // 删除映射的订单号+运单号
        details.orderCodeList.splice(_index, 1);
      }

      if (!_id) return;
      details.allCarsLineList[index] = '移除';
      // 记录被移除的id
      details.remveNodeList.push({ id: _id });
      details.page.pageNum = 1;
      initOriginWarehouseOrder();
    })
    .catch(() => {});
};

/** 加入调度池 */
const handleAddWaybill = async (index: number) => {
  const _node = details.nodeInfoData[index];
  if (!_node.nodeName || !_node.nodeId) {
    return ElMessage({
      type: 'warning',
      message: '未选择目的仓或目的仓信息异常',
    });
  }

  // 新增
  if (Number(details.pageType) === 3) return;
  for (let item of details.selectionList) {
    item.totalNum = item.totalNum || 20;
    item.planNum = item.stockNum;
    item.loadingNum = 0;
    _node.lineCarsOrderList.push(item);
  }

  details.orderCodeList = [
    ...new Set([
      ...details.orderCodeList,
      ...details.selectionList.map(val => val.orderCode + ',' + val.waybillNo),
    ]),
  ];

  _node.itemFilterData();
  // _node.renderData = _node.lineCarsOrderList;

  clearSelectionList();
  details.page.pageNum = 1;
  initOriginWarehouseOrder();
};

/** 移除调度池 */
const handleRemoveWaybill = async (index: number) => {
  const _node = details.nodeInfoData[index];
  // 新增

  if (!_node.nodeName || !_node.nodeId) {
    return ElMessage({
      type: 'warning',
      message: '未选择目的仓或目的仓信息异常',
    });
  }
  // 浅拷贝被选中的数据
  const _selectList = [..._node.selectionList];

  // 将被选中的数据筛选出去
  _node.lineCarsOrderList = _node.lineCarsOrderList.filter((val, index) => {
    const _flag = !_selectList.includes(val);
    if (!_flag) {
      const _code = val.orderCode + ',' + val.waybillNo;
      const _index = details.orderCodeList.indexOf(_code);
      // 删除映射的订单号+运单号
      details.orderCodeList.splice(_index, 1);
    }
    return _flag;
  });

  _node.renderData = _node.renderData.filter((val, index) => {
    const _flag = !_selectList.includes(val);
    return _flag;
  });
  clearSelectionList();
  initOriginWarehouseOrder();
};

/** 查询司机信息 */
const remoteMethodDriver = async val => {
  // if (!val) return;

  const res = await postFindDriverListByName({ driverName: val });
  const { code, data } = res.data;
  if (code !== 200) return;
  details.driverListByName = data;
};

// 初始化空调
remoteMethodDriver('');

/** 查询车辆信息 */
const remoteMethodCar = async val => {
  // if (!val) return;

  const res = await postFindCarListByName({ carNumber: val });
  const { code, data } = res.data;
  if (code !== 200) return;
  details.carListByName = data;
};
remoteMethodCar('');

/** 修改计划数 */
const handleEditplanNum = ({ row }, item) => {
  details.editInfo = row;
  details.editInfo.enterPlanNum = Number(row.planNum);
  // details.editInfo.item = item;

  details.popUpShow.editPlanNumberVisited = true;
};

/** 提交修改计划数量 */
const handleSubmitEdit = async () => {
  try {
    btnLoadingObj.editPlanNumBtn = true;

    const submitData = {
      carsOrderId: details.editInfo.carsOrderId,
      planNum: details.editInfo.enterPlanNum,
    };

    const res = await postUpdatePlanNumByCarsOrderId(submitData);
    const { code } = res.data;
    if (code !== 200) return;
    ElMessage.success('修改成功');
    details.editInfo.planNum = details.editInfo.enterPlanNum;
    // initDispatchOrder(details.editInfo.item);
    details.popUpShow.editPlanNumberVisited = false;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    // 关闭按钮loading
    btnLoadingObj.editPlanNumBtn = false;
  }
};

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

/** 新增提交 */
const addSubmit = async () => {
  try {
    btnLoadingObj.submitBtn = true;
    const _warehouseIds = [];
    const _warehouseNames = [];

    // 判定有节点是否有空未选
    const _flag = details.nodeInfoData.every((value, index) => {
      _warehouseNames.push(value.nodeName);
      if (index === 0) return true;
      _warehouseIds.push(value.nodeId);

      return value.nodeName && value.nodeId;
    });

    if (!_flag) {
      return ElMessage({
        type: 'warning',
        message: '节点信息有误',
      });
    }

    const submitData = {
      ...form.value,
      // 深拷贝数据防止修改原数据
      addCarsLoadLineList: JSON.parse(JSON.stringify(details.nodeInfoData)),
      removeCarsLoadLineList: [],
    };

    // 目的仓
    submitData.endWarehouseIds = _warehouseIds.join(',');
    submitData.endWarehouseNames = _warehouseNames.slice(1).join(',');
    submitData.carsLineName = _warehouseNames.join('->');

    let _lineCarsOrderList = [];
    submitData.addCarsLoadLineList.forEach((val, i) => {
      val.nodeType = '1';
      val.sort = i + 1;
      val.updateType = 2;
      delete val.blackList;
      if (i === 0) return;
      // 删除无用数据
      delete val.query;
      delete val.selectionList;
      delete val.loading;
      delete val.data;
      delete val.renderData;
      delete val.newColumnList;

      _lineCarsOrderList = [
        ..._lineCarsOrderList,
        ...val.lineCarsOrderList.map(value => {
          value.nodeId = submitData.startWarehouseId;
          value.nodeName = submitData.startWarehouseName;
          value.finalNodeId = val.nodeId;
          return value;
        }),
      ];
      delete val.lineCarsOrderList;
    });

    submitData.addCarsLoadLineList[0].addList = _lineCarsOrderList;
    submitData.addCarsLoadLineList[0].removeList = [];

    const res = await postSaveNew(submitData);
    const { code, msg } = res.data;
    if (code !== 200) return;
    ElMessage({
      message: msg,
      type: 'success',
    });
    back();
    console.log('res :>> ', res);
  } catch (error) {
  } finally {
    btnLoadingObj.submitBtn = false;
    return false;
  }
};

/** 修改提交 */
const editSubmit = async () => {
  try {
    btnLoadingObj.submitBtn = true;
    const _warehouseIds = [];
    const _warehouseNames = [];

    // 判定有节点是否有空未选
    const _flag = details.nodeInfoData.every((value, index) => {
      _warehouseNames.push(value.nodeName);
      if (index === 0) return true;
      _warehouseIds.push(value.nodeId);

      return value.nodeName && value.nodeId;
    });

    if (!_flag) {
      return ElMessage({
        type: 'warning',
        message: '节点信息有误',
      });
    }

    console.log('details.nodeInfoData :>> ', details.nodeInfoData);

    const submitData = {
      ...form.value,
      // 深拷贝数据防止修改原数据
      addCarsLoadLineList: deepClone(details.nodeInfoData),

      removeCarsLoadLineList: details.remveNodeList,
    };

    // 目的仓
    submitData.endWarehouseIds = _warehouseIds.join(',');
    submitData.endWarehouseNames = _warehouseNames.slice(1).join(',');
    submitData.carsLineName = _warehouseNames.join('->');

    let _lineCarsOrderList = [];
    let _removeList = [];
    submitData.addCarsLoadLineList.forEach((val, i) => {
      val.nodeType = '1';
      val.sort = i + 1;

      const _index = details.allCarsLineList.indexOf(val.nodeId);
      if (_index === -1) {
        // 本节点为新增
        val.updateType = 2;
        // 修改
      } else {
        val.updateType = 1;
      }
      delete val.blackList;
      if (i === 0) return;
      // 删除无用数据
      delete val.query;
      delete val.selectionList;
      delete val.loading;
      delete val.data;
      delete val.renderData;
      delete val.newColumnList;
      delete val.itemInputsc;
      delete val.selectionChange;

      // 新增数据
      const _addArr = [];

      console.log('val.lineCarsOrderList :>> ', val.lineCarsOrderList);

      for (let index = 0; index < val.lineCarsOrderList.length; index++) {
        const element = val.lineCarsOrderList[index];

        if (element.carsOrderId)
          for (let j = 0; j < val.MappingData.length; j++) {
            const item = val.MappingData[j];

            if (!element.carsOrderId === item.carsOrderId) continue;
            val.MappingData.splice(j, 1);
            break;
          }

        console.log('val.MappingData :>> ', val.MappingData);

        // 检测该运单是否与配载任务挂载
        if (!element.carsOrderId)
          _addArr.push({
            ...element,
            nodeId: submitData.startWarehouseId,
            nodeName: submitData.startWarehouseName,
            finalNodeId: val.nodeId,
          });
      }

      // 存在删除数据或新增数据, 则该节点存在更新
      // if ((val.updateType !== 2 && _addArr.length > 0) || val.MappingData.length > 0)
      //   val.updateType = 1;

      _lineCarsOrderList = [..._lineCarsOrderList, ..._addArr];
      _removeList = [..._removeList, ...val.MappingData];
      delete val.lineCarsOrderList;
    });

    submitData.addCarsLoadLineList[details.active].addList = _lineCarsOrderList;

    for (let i = 0; i < _removeList.length; i++) {
      const value = _removeList[i];
      value.id = value.carsOrderId;
    }
    submitData.addCarsLoadLineList[details.active].removeList = _removeList;

    const res = await postUpdateCarsLoadBasicData(submitData);
    const { code, msg } = res.data;
    if (code !== 200) return;
    ElMessage({
      message: msg,
      type: 'success',
    });
    back();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    btnLoadingObj.submitBtn = false;
    return false;
  }
};

/** 节点费用修改提交 */
const nodeCostSubmit = async () => {
  try {
    btnLoadingObj.submitBtn = false;

    const submitData = {
      loadId: details.loadId,
      ...details.form,
      carsLoadLineList: details.nodeInfoData,
    };

    const res = await postUpdateLoadFeeByNodeId(submitData);
    const { code, msg } = res.data;
    if (code !== 200) return;
    ElMessage({
      message: msg,
      type: 'success',
    });
    back();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    btnLoadingObj.submitBtn = false;
    return false;
  }
};

/** 提交 */
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (btnLoadingObj.submitBtn) return;
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      const _driverType = Number(details.form.driverType);

      if ((_driverType === 3 || _driverType === 4) && !details.form.outDriverPerson)
        return ElMessage.warning('请输入外请人');

      ElMessageBox.confirm('是否确认提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          details.loadingObj.pageLoading = true;

          // 新增提交
          if (Number(details.pageType) === 1) await addSubmit();
          // 修改提交
          else if (Number(details.pageType) === 2) await editSubmit();
          else if (Number(details.pageType) === 3) await nodeCostSubmit();
        } catch (error) {
          console.log('error :>> ', error);
        } finally {
          details.loadingObj.pageLoading = false;
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

// watch($route, () => {
//   if ($route.path !== '/distribution/artery/AddVehicleStowage') return;
//   onLoad();
// });
</script>

<style scoped lang="scss">
// 日期选择器
:deep(.el-date-editor.el-input) {
  height: 100% !important;
  width: 100% !important;
}

:deep(.el-range-editor.el-input__wrapper) {
  height: 100% !important;
}

.fwb {
  font-weight: bold;
}

// 弹出层标题
.popUp_title {
  font-size: 18px;
  font-weight: bold;
  padding: 5px 20px;
  position: relative;
  margin: 20px 0;

  &:first-child {
    margin-top: 0;
  }

  &::before {
    width: 4px;
    height: 100%;
    background: #172e60;
    content: '';
    display: inline-block;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.red {
  color: var(--token-simulation-red-base-62);
}

.w100 {
  width: 100%;
}

// 标题
:deep(.el-divider__text.is-left) {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
}

// 表单行
.form_row {
  display: flex;
  align-items: center;

  .form_row_item {
    display: flex;
    margin-right: 20px;

    :deep(.el-form-item.asterisk-left) {
      margin-right: 10px;
      min-width: 260px;
    }
  }
}

// 单选框
:deep(.el-radio.el-radio--large) {
  height: auto;
}

// 数字输入框
:deep(.nodeInfo .el-table .cell) {
  overflow: initial;
}

:deep(.slotbuts) {
  height: 30px;

  .el-input-number {
    height: 100%;
  }
}

:deep(.el-steps) {
  --el-color-success: #1a3061;
}

:deep(.el-step__title.is-process) {
  font-weight: bold;
  --el-text-color-primary: #60df54;
}

:deep(.el-step__head.is-process) {
  --el-text-color-primary: #60df54;
}

:deep(.el-step__title.is-process .count_icon) {
  background: #60df54;
}

.count_icon {
  --width: 25px;
  margin-right: 20px;
  width: var(--width);
  height: var(--width);
  background: var(--el-color-primary);
  color: #fff;
  border-radius: 50%;
  text-align: center;
  line-height: var(--width);
}

.steps_title {
  margin-right: 30px;
}

// 步骤条
:deep(.el-steps) {
  flex-wrap: wrap;
}

:deep(.el-step.is-horizontal) {
  max-width: none !important;
}

// 新增行
.add_row {
  display: flex;
  justify-content: space-between;
}

:deep(.el-table__row) {
  height: 30px;
}

// 页面底部站位
.footer {
  height: 80px;
}

// 提交按钮
.button-container {
  z-index: 99;
  position: fixed;
  bottom: 30px;
  left: 50%;
}

// 错误提示
:deep(.el-form-item__error) {
  z-index: 99;
  --el-color-danger: #f00;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  --el-color-danger: #f00;
}

:deep(
    .el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before,
    .el-form-item.is-required:not(.is-no-asterisk).asterisk-left
      > .el-form-item__label-wrap
      > .el-form-item__label:before
  ) {
  --el-color-danger: #f00;
}

// 修改数字输入框
:deep(.editInput .el-input__inner) {
  text-align: left !important;
}

// 修改弹窗内样式
.edit_title {
  font-size: 18px;
  font-weight: bold;
}

.edit_row {
  margin: 20px 0;

  .flex1 {
    flex: 1;
  }
}

// 统计行
.total_row {
  margin-top: 5px;
  zoom: 0.9;
  color: var(--el-color-primary);
}
</style>
