<template>
  <div v-loading="details.loadingObj.submitLoadingBtn">
    <basic-container>
      <el-divider style="font-size: 28px">货物托运单</el-divider>
      <el-form
        ref="ruleFormRef"
        :inline="true"
        :rules="details.rules"
        :model="query"
        class="table_form"
        label-width="100px"
      >
        <!-- 顶部 -->
        <div class="flex-c-sb form_top">
          <div>
            <el-form-item class="mt10 mr10" label="运单号: " prop="waybillNo" label-width="80px">
              <el-input
                v-model.trim="query.waybillNo"
                :disabled="$route.query && $route.query.type === 'edit'"
                placeholder="运单号"
                clearable
              />
            </el-form-item>

            <el-form-item class="mt10" label="品牌: " prop="brandId" label-width="80px">
              <el-select
                class="w100"
                style="width: 200px"
                v-model="query.brandId"
                filterable
                placeholder="品牌"
                default-first-option
                @change="
                  val => {
                    details.query.brand = details.brandOptions.find(
                      val => val.brandId === details.query.brandId
                    ).brandName;

                    console.log('details.query.brand :>> ', details.query.brand);
                    handleFindPrice();
                  }
                "
              >
                <el-option
                  v-for="item in details.brandOptions"
                  :key="item.brandId"
                  :label="item.brandName"
                  :value="item.brandId"
                />
              </el-select>
            </el-form-item>
          </div>

          <div class="flex-c-c">
            <div style="margin-right: 10px" class="flex-c-c">
              <el-icon><User /></el-icon>
              <span style="margin-left: 10px">{{ details.query.openOrderUserName }}</span>
            </div>

            <el-date-picker
              v-model="query.openOrderDate"
              :readonly="$route.query.type === 'edit'"
              prefix-icon="Calendar"
              type="datetime"
              placeholder="创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :clearable="false"
            />
          </div>
        </div>

        <!-- 第一排 -->
        <div class="table-row mt15 border-top">
          <el-form-item label="发站仓:" prop="departureWarehouseName" class="el-times">
            <el-input disabled v-model="query.departureWarehouseName" placeholder="货号"></el-input>
          </el-form-item>

          <el-form-item label="发站:" prop="departure">
            <div class="w100">
              <el-cascader
                pleceholder="请选择到站地址"
                :options="details.regionOptione"
                style="width: 100%"
                v-model="query.departure"
                :props="{
                  checkStrictly: true,
                }"
                @change="() => handleFindPrice()"
                filterable
                clearable
              >
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </div>
          </el-form-item>

          <el-form-item label="到站:" prop="destination">
            <div class="w100">
              <el-cascader
                pleceholder="请选择到站地址"
                :options="details.regionOptione"
                style="width: 100%"
                v-model="query.destination"
                :props="{
                  checkStrictly: true,
                }"
                @change="() => handleFindPrice()"
                filterable
                clearable
              >
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </div>
          </el-form-item>

          <el-form-item label="目的仓:" class="el-times" prop="queryDestinationWarehouseName">
            <el-select
              class="w100"
              v-model="query.queryDestinationWarehouseName"
              filterable
              remote
              reserve-keyword
              placeholder="目的仓"
              @change="
                val => {
                  destinationWarehouseNameChange(val);
                  handleFindPrice();
                }
              "
              :remote-method="value => debounce(remoteMethod(value), 500)"
              :loading="details.loadingObj.loading"
            >
              <el-option
                v-for="item in details.options || []"
                :key="item.value"
                :label="item.warehouseName"
                :value="item.warehouseId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="货号:" prop="goodsCode">
            <el-input v-model="query.goodsCode" placeholder="货号"></el-input>
          </el-form-item>
        </div>

        <!-- 发货方 && 收货方 -->
        <div class="table-row">
          <div style="margin-right: 10px">
            <div class="flex-c table-row-title">发货方</div>
            <div>
              <el-row>
                <el-form-item
                  label="发货单位:"
                  prop="shipper"
                  :class="!query.shipperId ? 'is-error' : ''"
                >
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('shipper', 1)"
                    v-model="query.shipper"
                    placeholder="发货单位"
                    ref="shipper"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.shipperOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseShipper(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="发货单位" width="130" />
                      <el-table-column prop="linkMan" label="发货人" width="130" />
                      <el-table-column prop="linkPhone" label="发货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="发货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>

                <el-form-item label="发货人:" prop="shipperName">
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('shipperName')"
                    v-model="query.shipperName"
                    placeholder="发货人"
                    ref="shipperName"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.shipperNameOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseShipper(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="发货单位" width="130" />
                      <el-table-column prop="linkMan" label="发货人" width="130" />
                      <el-table-column prop="linkPhone" label="发货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="发货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="联系电话:" prop="shipperMobile">
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('shipperMobile')"
                    v-model="query.shipperMobile"
                    placeholder="联系电话"
                    ref="shipperMobile"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.shipperMobileOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseShipper(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="发货单位" width="130" />
                      <el-table-column prop="linkMan" label="发货人" width="130" />
                      <el-table-column prop="linkPhone" label="发货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="发货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="发货地址:">
                  <el-input
                    @change="e => handleRefreshText('shipperAddress', e, '')"
                    v-model="query.shipperAddress"
                    placeholder="发货地址"
                  ></el-input>
                </el-form-item>
              </el-row>
            </div>
          </div>
          <div class="border-left">
            <div class="flex-c table-row-title">收货方</div>
            <div>
              <el-row>
                <el-form-item
                  label="收货单位:"
                  prop="consignee"
                  :class="!query.consigneeId ? 'is-error' : ''"
                >
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('consignee', 1)"
                    v-model="query.consignee"
                    placeholder="收货单位"
                    ref="consignee"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.consigneeOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseConsigner(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="收货单位" width="130" />
                      <el-table-column prop="linkMan" label="收货人" width="130" />
                      <el-table-column prop="linkPhone" label="收货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="收货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>

                <el-form-item label="收货人:" prop="consigneeName">
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('consigneeName')"
                    v-model="query.consigneeName"
                    placeholder="收货人"
                    ref="consigneeName"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.consigneeNameOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseConsigner(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="收货单位" width="130" />
                      <el-table-column prop="linkMan" label="收货人" width="130" />
                      <el-table-column prop="linkPhone" label="收货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="收货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="联系电话:" prop="consigneeMobile">
                  <SelectBox
                    :focus="handleCloseSelcet"
                    :input="() => handleFindClientInfo('consigneeMobile')"
                    v-model="query.consigneeMobile"
                    placeholder="联系电话"
                    ref="consigneeMobile"
                    :minWidth="true"
                  >
                    <el-table
                      :data="details.consigneeMobileOptions"
                      style="width: 100%"
                      @row-click="
                        (column, prop, order) => {
                          handleChooseConsigner(column, prop, order);
                          handleFindPrice();
                        }
                      "
                      v-loading="details.loadingObj.consignerLoading"
                    >
                      <el-table-column prop="clientName" label="收货单位" width="130" />
                      <el-table-column prop="linkMan" label="收货人" width="130" />
                      <el-table-column prop="linkPhone" label="收货联系电话" width="130" />
                      <el-table-column prop="linkAddress" label="收货地址" width="200" />
                    </el-table>
                  </SelectBox>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="收货地址:">
                  <el-input
                    @change="e => handleRefreshText('consigneeAddress', e, '')"
                    v-model="query.consigneeAddress"
                    placeholder="收货地址"
                  ></el-input>
                </el-form-item>
              </el-row>
            </div>
          </div>
        </div>

        <div class="table-row table_row_number">
          <div class="flex-c-c title">提 货</div>
          <el-form-item label="是否提货:" label-width="fit-content" prop="num" class="flex1">
            <el-radio-group
              @change="
                () => {
                  details.query.pickupFee = 0;
                  if (!details.query.isPickUp) return;
                  handlePrice(false, 'pickup');
                }
              "
              v-model="query.isPickUp"
              class="flex-a"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否整车:" label-width="fit-content" prop="num" class="flex1">
            <el-radio-group
              :disabled="!query.isPickUp"
              v-model="query.pickupCompleteOrNot"
              class="flex-a"
              @change="
                () => {
                  details.query.pickupFee = 0;
                  handlePrice(false, 'pickup');
                }
              "
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="车型:" label-width="fit-content" prop="num" class="flex1">
            <el-select
              class="w100"
              :disabled="!query.isPickUp || !query.pickupCompleteOrNot"
              v-model="query.pickupVehicleTypeId"
              filterable
              clearable
              placeholder="请选择车型"
              @change="
                () => {
                    let _item = {} as any

                    for (let i = 0; i < details.vehicleTypeArr.length; i++) {
                      const val = details.vehicleTypeArr[i];
                      
                      if (val.dictKey !== query.pickupVehicleTypeId) continue
                      _item = val
                      break
                    }

                    query.pickupVehicleType = _item.dictValue || ''
                  details.query.pickupFee = 0;
                  handlePrice(false, 'pickup');
                }
              "
            >
              <el-option
                v-for="item in details.vehicleTypeArr"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
                :disabled="item.isCheck === true"
              />
            </el-select>
          </el-form-item>

          <div class="flex-c-c title">干 线</div>

          <el-form-item label="是否整车:" label-width="fit-content" prop="num" class="flex1">
            <!-- 金牌不存在整车一口价费用 -->
            <el-radio-group
              v-model="query.trunklineCompleteOrNot"
              class="flex-a"
              @change="
                () => {
                  details.query.totalFreight = 0;
                  handlePrice(false, 'trunkline');
                }
              "
              :disabled="isDisabled"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="车型:" label-width="fit-content" prop="num" class="flex1">
            <el-select
              class="w100"
              :disabled="!query.trunklineCompleteOrNot"
              v-model="query.trunklineVehicleTypeId"
              filterable
              clearable
              placeholder="请选择车型"
              @change="
                () => {
                    let _item = {} as any

                    for (let i = 0; i < details.vehicleTypeArr.length; i++) {
                      const val = details.vehicleTypeArr[i];
                      
                      if (val.dictKey !== query.trunklineVehicleTypeId) continue
                      _item = val
                      break
                    }

                    query.trunklineVehicleType = _item.dictValue || ''
                    details.query.totalFreight = 0;
                    handlePrice(false, 'trunkline');
                }
              "
            >
              <el-option
                v-for="item in details.vehicleTypeArr"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
                :disabled="item.isCheck === true"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 计价方式行 -->
        <div
          class="table-row table_row_number"
          style="display: flex"
          v-for="(item, index) in details.goodsList"
          :key="item"
        >
          <!-- 加减按钮 -->
          <div style="width: 55px; flex: none" class="flex-c-c" v-if="query.zeroEditStatus !== 0">
            <el-button
              v-if="index === 0"
              @click="handleAdd"
              icon="Plus"
              type="primary"
              size="small"
              circle
            ></el-button>

            <el-button
              v-else
              @click="handleRemove(index)"
              icon="Minus"
              type="primary"
              size="small"
              circle
            ></el-button>
          </div>

          <div style="width: 230px; flex: none">
            <el-form-item
              label="计价方式:"
              label-width="fit-content"
              prop="chargeType"
              class="el-times"
            >
              <el-radio-group
                v-model="item.chargeType"
                @change="() => handleAssignmentItemPrice(item, false, item.chargeType)"
                style="display: flex"
              >
                <el-radio :label="1">件</el-radio>
                <el-radio :label="2">方</el-radio>
                <el-radio :label="3">公斤</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 货物名称 -->
          <el-form-item
            label="货物名称:"
            label-width="fit-content"
            prop="goodsName"
            class="el-times"
          >
            <SelectBox
              ref="goodsNameRef"
              className="goodsName"
              :input="() => debounce(handleFindGoods(item.goodsName, item, 1), 1000)"
              :focus="handleCloseSelcet"
              v-model="item.goodsName"
              :class="!item.goodsId ? 'is-error' : ''"
              :disabled="query.zeroEditStatus === 0"
              placeholder="货物名称"
            >
              <div v-loading="item.loading">
                <template v-if="item.goodsListOptions.length > 0">
                  <div
                    :class="{ goodsNameRow: true, active: val.goodsId === item.goodsId }"
                    v-for="val in item.goodsListOptions"
                    :key="val.goodsId"
                    @click="() => handleChooseGoods(item, val)"
                  >
                    {{ val.goodsName }}
                  </div>
                </template>
                <template v-else>
                  <div class="goodsNameRow" @click="handleCloseSelcet">暂无数据</div>
                </template>
              </div>
            </SelectBox>
          </el-form-item>

          <el-form-item label="件数:" label-width="fit-content" prop="num" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :disabled="query.zeroEditStatus === 0"
              :value-on-clear="0"
              :controls="false"
              v-model="item.num"
              :min="0"
              :precision="0"
              :step="1"
              @change="handleComputed(item)"
            />
          </el-form-item>

          <el-form-item label="体积(方):" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="item.volume"
              :min="0"
              :precision="4"
              :step="0.1"
              @change="handleComputed(item)"
            />
          </el-form-item>

          <el-form-item label="重量(kg):" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="item.weight"
              :min="0"
              :precision="3"
              :step="0.1"
              @change="handleComputed(item)"
            />
          </el-form-item>

          <el-form-item label="单价:" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="item.price"
              :min="0"
              :precision="2"
              :step="0.1"
              @change="handleComputed(item, true)"
            />
          </el-form-item>

          <el-form-item label="运费小计:" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="item.subtotalFreight"
              :precision="2"
              :min="0"
              :step="0.1"
              :disabled="item.price > 0 || Number(item.price) !== Number(item.price)"
              @change="
                () => {
                  handleTrunkLinePrice(
                    details.priceTemplate.trunkLine,
                    details.priceTemplate.template
                  );
                }
              "
            />
          </el-form-item>
        </div>

        <!-- 合计行 -->
        <div class="table-row table_row_number table_row_total">
          <div
            style="width: 55px; flex: none"
            class="flex-c-c"
            v-if="query.zeroEditStatus !== 0"
          ></div>
          <div style="width: 230px; flex: none">合计</div>
          <!-- 货物名称 -->
          <div>{{ details.goodsList.length }}</div>
          <!-- 件数 -->
          <div>{{ details.totalObj.totalCount }}</div>
          <!-- 体积 -->
          <div>{{ details.totalObj.totalVolume }}</div>
          <!-- 重量 -->
          <div>{{ details.totalObj.totalWeghit }}</div>
          <div></div>
          <!-- 运费 -->
          <div>{{ details.totalObj.totalFreight }}</div>
        </div>

        <!-- 合计运费 && 支付方式 -->
        <div class="table-row">
          <!-- 合计运费 -->
          <div style="margin-right: 10px; width: 55%; flex: none; zoom: 0.9">
            <div style="flex: 1">
              <div class="table-row-title" style="margin-bottom: 10px">
                <div class="table-row-title-item fwb">
                  合计费用
                  <span class="red" style="margin-left: 10px">{{ totalCost }}</span>
                </div>
              </div>
              <div>
                <el-form label-width="fit-content">
                  <el-row>
                    <el-form-item label="运费:">
                      <!-- <el-input v-model="details.totalObj.totalFreight" disabled></el-input> -->
                      <el-input-number
                        @focus="handleInputFocus"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.totalFreight"
                        :disabled="!query.trunklineCompleteOrNot"
                        :value-on-clear="0"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="送货费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.deliveryFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="提货费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.pickupFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="仓库管理费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.warehouseManagementFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="仓储费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.storageFee"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>

                  <el-row>
                    <el-form-item label="仓储操作费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.handlingFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="仓储分拣费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :controls="false"
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.sortingFee"
                        :value-on-clear="0"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="其它费用:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.otherFee"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="保价费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.insuranceFee"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="申明价值:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.claimingValue"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>

                  <el-row>
                    <el-form-item label="回扣:" style="flex: none !important">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.rebate"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="安装费:">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.installFee"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>
                </el-form>
              </div>
            </div>
          </div>

          <!-- 付款方式 -->
          <div style="zoom: 0.9" class="border-left">
            <div style="flex: 1">
              <div class="table-row-title" style="margin-bottom: 10px">
                <div class="table-row-title-item fwb">付款方式</div>
              </div>
              <div>
                <el-row>
                  <el-form-item label-width="fit-content" label="支付方式:">
                    <el-select
                      v-model="query.payType"
                      :teleported="false"
                      class="m-2"
                      placeholder="支付方式"
                    >
                      <el-option
                        v-for="item in details.info.payTypeList"
                        :key="item.dictValue"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="付款方式:" label-width="fit-content" prop="payWay">
                    <el-select
                      v-model="query.payWay"
                      :teleported="false"
                      class="m-2"
                      @change="handlePayWay"
                      placeholder="付款方式"
                    >
                      <el-option
                        v-for="item in details.info.payWayList"
                        :key="item.dictValue"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item label-width="fit-content" label="现付:">
                    <el-input-number
                      @focus="handleInputFocus"
                      :value-on-clear="0"
                      :controls="false"
                      :precision="2"
                      :min="0"
                      :step="0.1"
                      v-model="query.xianPay"
                    ></el-input-number>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label-width="fit-content" label="到付:">
                    <el-input-number
                      @focus="handleInputFocus"
                      :value-on-clear="0"
                      :controls="false"
                      :precision="2"
                      :min="0"
                      :step="0.1"
                      v-model="query.daoPay"
                    ></el-input-number>
                  </el-form-item>

                  <el-form-item label-width="fit-content" label="月结:">
                    <el-input-number
                      @focus="handleInputFocus"
                      :value-on-clear="0"
                      :controls="false"
                      :precision="2"
                      :min="0"
                      :step="0.1"
                      v-model="query.yuePay"
                    ></el-input-number>
                  </el-form-item>

                  <el-form-item label-width="fit-content" label="回付:">
                    <el-input-number
                      @focus="handleInputFocus"
                      :value-on-clear="0"
                      :controls="false"
                      :precision="2"
                      :min="0"
                      :step="0.1"
                      v-model="query.huiPay"
                    ></el-input-number>
                  </el-form-item>
                </el-row>
              </div>
            </div>
          </div>

          <!-- 代收款 -->
          <div style="width: 10%; flex: none; zoom: 0.9">
            <div style="flex: 1">
              <div class="table-row-title" style="margin-bottom: 10px">
                <div class="table-row-title-item fwb">代收款</div>
              </div>
              <div>
                <el-form label-width="fit-content" :rules="details.rules">
                  <el-row>
                    <div style="font-size: 14px">代收货款:</div>
                    <el-form-item label-width="0">
                      <el-input-number
                        @focus="handleInputFocus"
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.replacePrice"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>
                </el-form>
              </div>
            </div>
          </div>
        </div>

        <!-- 计价方式行 -->
        <div class="table-row table_row_number">
          <div>
            <el-form-item label="开单人:" label-width="fit-content" class="el-times">
              <el-input v-model="query.openOrderUserName" disabled />
            </el-form-item>
          </div>

          <el-form-item label="三方操作费:" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="query.thirdOperationFee"
              :precision="2"
              :step="0.1"
            />
          </el-form-item>

          <el-form-item
            prop="deliveryWay"
            label="送货方式:"
            label-width="fit-content"
            class="el-times"
          >
            <el-select v-model="query.deliveryWay" class="m-2" placeholder="送货方式">
              <el-option
                v-for="item in details.info.deliveryWayList"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="紧急度:" label-width="fit-content" prop="urgency" class="el-times">
            <el-select v-model="query.urgency" class="m-2" placeholder="紧急度">
              <el-option
                v-for="item in details.info.urgencyList"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="回单" label-width="fit-content" class="el-times">
            <el-input-number
              @focus="handleInputFocus"
              :value-on-clear="0"
              :controls="false"
              v-model="query.receiptNum"
              :precision="0"
              :step="1"
            />
          </el-form-item>

          <el-form-item label="回单要求:" label-width="fit-content" class="el-times">
            <el-select
              v-model="query.receipt"
              class="m-2"
              filterable
              multiple
              placeholder="回单要求"
            >
              <el-option
                v-for="item in details.info.receiptList"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="运输方式:" label-width="fit-content" class="el-times">
            <el-select v-model="query.transportType" class="m-2" placeholder="运输方式">
              <el-option
                v-for="item in details.info.transportTypeList"
                :key="item.dictValue"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 备注 -->
        <div class="table-row">
          <el-form-item label="备注:" class="el-times">
            <el-input v-model="query.remark" type="textarea" placeholder="备注"></el-input>
          </el-form-item>

          <div class="flex-c-c">
            <el-button icon="Close" @click="back">关闭</el-button>
            <el-button type="primary" icon="Position" @click="handleSubmit(ruleFormRef)"
              >提交</el-button
            >
            <!-- <el-button type="primary" icon="Refresh" @click="resetForm(ruleFormRef)">
              重置
            </el-button> -->
          </div>
        </div>
      </el-form>
    </basic-container>

    <!-- 选取订单 -->
    <el-dialog
      title="提示"
      :center="true"
      :align-center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      v-model="details.popUpShow.titleVisited"
    >
      <div v-loading="details.loadingObj.pageLoading">
        <div style="text-align: center">是否继续开单</div>
        <div class="flex-c-c mt20">
          <el-button icon="CircleClose" @click="back">取 消</el-button>
          <el-button type="primary" icon="CircleCheck" @click="handleRepetition">确 认</el-button>
          <el-button type="primary" icon="Printer" v-if="details.waybillId" @click="handlePrint">
            打 印
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 改单原因 -->
    <el-dialog
      title="修改信息"
      :center="true"
      :align-center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="50%"
      v-model="details.popUpShow.causeVisited"
    >
      <el-form :model="details.causeForm" ref="causeFormRef" label-width="120px">
        <el-form-item
          label="修改原因："
          style="margin-right: 0"
          prop="editResonCode"
          :rules="[{ required: true, message: '请选择修改原因', trigger: ['blur', 'change'] }]"
        >
          <el-select
            v-model="details.causeForm.editResonCode"
            clearable
            placeholder="请选择修改原因"
            style="width: 100%"
          >
            <el-option
              v-for="item in query.editWaybillReasonTypeList"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注：" style="margin-right: 0">
          <el-input type="textarea" v-model="details.causeForm.refer" placeholder="请输入描述" />
        </el-form-item>
      </el-form>

      <tablecmt
        style="height: 40vh"
        ref="tableNode"
        :columnList="details.changeColumnList"
        :tableData="details.changeData"
        :loading="loadingObj.list"
      >
        <template #default="slotProps"> </template>
      </tablecmt>

      <div class="flex-c-c mt20">
        <el-button icon="CircleClose" @click="() => (details.popUpShow.causeVisited = false)"
          >取 消</el-button
        >
        <el-button type="primary" icon="CircleCheck" @click="handleSubmitCause">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 运单打印 -->
    <WaybillPrintTemplate
      v-model="details.popUpShow.WaybillPrintTemplate"
      :html="details.html"
      width="fit-content"
    />
  </div>
</template>

<script lang="ts">
export default {
  name: '/waybill/CreateZeroOrder',
};
</script>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  computed,
  onMounted,
  nextTick,
  getCurrentInstance,
  watch,
} from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { postPrintBatch } from '@/api/waybill/WaybillOrderList.js';
import { downloadXls, computeNumber, debounce, setNodeHeight } from '@/utils/util';
import { getLazyTreeAll } from '@/api/base/region';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import {
  postOpenOrderFindClientInfo,
  getOpenOrderAdvanceToWaybillInfo,
  postOpenOrderOpenWaybill,
  getOpenOrderAdvanceFindWarehouseList,
  postOpenOrderOpenZeroWaybillInfo,
  postOpenOrderOpenZeroWaybill,
  postFindWaybillDetail,
  postUpdateWaybillVerify,
  postUpdateWaybill,
  postFindCategoryInfo,
  postFindArrPrice,
} from '@/api/distribution/CreateOrder.js';
import { postFindBrandList } from '@/api/waybill/TemporaryStorageList.js';
import { isNumber, getObjType, deepClone, floorToDecimalPlaces } from '@/utils/util.js';
import { getList } from '@/api/basicdata/basicdataVehicleInfo';

// 获取vue实例
const instance = getCurrentInstance();

// 获取表单实例
const ruleFormRef = ref<FormInstance>();
const causeFormRef = ref<FormInstance>();

// 组件实例
const tableNode = ref();

// vuex
const $store = useStore();

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

const details = reactive<any>({
  /** 请求的数据 */
  info: {},
  /** 表单 */
  query: {
    /** 品牌 */
    brand: '',
    /** 创建时间 */
    openOrderDate: new Date(),
    /** 客户车次号 */
    customerTrain: '',
    /** 运单号 */
    waybillNo: '',
    /** 发站仓id */
    departureWarehouseId: '',
    /** 发站仓名称 */
    departureWarehouseName: '',
    /** 到站 */
    destination: '',
    /** 订单自编号 */
    orderCode: '',
    /** 目的站名称 */
    destinationWarehouseName: '',
    /** 目的仓Id */
    destinationWarehouseId: '',
    queryDestinationWarehouseName: '',
    /** 货物号 */
    goodsCode: '',
    /** 发货单位id */
    shipperId: '',
    /** 发货单位 */
    shipper: '',
    /** 发货人 */
    shipperName: '',
    /** 发货人电话 */
    shipperMobile: '',
    /** 发货人地址 */
    shipperAddress: '',
    /** 收货单位id */
    consigneeId: '',
    /** 收货单位 */
    consignee: '',
    /** 收货人 */
    consigneeName: '',
    /** 收货人电话 */
    consigneeMobile: '',
    /** 收货人地址 */
    consigneeAddress: '',
    /** 货物品类 */
    waybillDetailList: [],
    /** 送货费 */
    deliveryFee: 0,
    /** 提货费 */
    pickupFee: 0,
    /** 仓库管理费 */
    warehouseManagementFee: 0,
    /** 仓储费 */
    storageFee: 0,
    /** 仓储操作费 */
    handlingFee: 0,
    /** 仓储分拣费 */
    sortingFee: 0,
    /** 其他费 */
    otherFee: 0,
    /** 保价费 */
    insuranceFee: 0,
    /** 安装费 */
    installFee: 0,
    /** 申明价值 */
    claimingValue: 0,
    /** 支付方式 */
    payType: '',
    /** 付款方式 */
    payWay: '2',
    /** 现付 */
    xianPay: 0,
    /** 到付 */
    daoPay: 0,
    /** 月付 */
    yuePay: 0,
    /** 回付 */
    huiPay: 0,
    /** 回扣 */
    rebate: 0,
    huilaiPay: 0,
    /** 三方操作费 */
    thirdOperationFee: 0,
    /** 送货方式 */
    deliveryWay: '1',
    /** 紧急度 */
    urgency: '1',
    /** 回单方式(多选) */
    receipt: [],
    /** 运输方式 */
    transportType: '1',
    /** 开单人 */
    openOrderUserName: '',
    /** 回单数 */
    receiptNum: 0,
    /** 代收货款 */
    replacePrice: 0,
    /** 备注 */
    remark: '',
    /** 运单类型 */
    waybillType: 2,
    /** 是否提货 */
    isPickUp: 0,
    /** 是否整车 -- 提货 */
    pickupCompleteOrNot: 0,
    /** 提货整车车型 */
    pickupVehicleTypeId: '',
    pickupVehicleType: '',
    /** 是否整车 -- 干线 */
    trunklineCompleteOrNot: 0,
    /** 干线整车车型 */
    trunklineVehicleTypeId: '',
    trunklineVehicleType: '',
  },
  /** 价格模板数据 */
  priceTemplate: {} as any,
  /** 车型 */
  vehicleTypeArr: [],
  deepQuery: {},
  /** 合计 */
  totalObj: {
    /** 总件数 */
    totalCount: computed(() => {
      let _totalNum = 0;

      for (let i = 0; i < details.goodsList.length; i++) {
        const value = details.goodsList[i];
        if (value.num) _totalNum += value.num;
      }

      return _totalNum;
    }),
    /** 总重量 */
    totalWeghit: computed(() => {
      return details.goodsList.reduce((curr, item) => {
        if (item.weight) return computeNumber(curr, '+', item.weight).result;
        return curr;
      }, 0);
    }),
    /** 总体积 */
    totalVolume: computed(() => {
      return details.goodsList.reduce((curr, item) => {
        if (item.volume) return computeNumber(curr, '+', item.volume).result;
        return curr;
      }, 0);
    }),
    /** 总运费 */
    totalFreight: computed(() => {
      return details.goodsList.reduce((curr, item) => {
        if (item.subtotalFreight) return computeNumber(curr, '+', item.subtotalFreight).result;
        return curr;
      }, 0);
    }),
  },
  /** 暂存单Id集合 */
  advanceIds: [],
  /** 货物集合 */
  goodsList: [
    {
      index: 0,
      /** 货物名称  */
      goodsName: '',
      /** 品类Id */
      goodsId: '',
      /** 计费方式 */
      chargeType: 1,
      /** 系统维护 -- 干线计价方式 */
      systemChargeType: 1,
      /** 系统维护 -- 配送计价方式 */
      systemDeliveryChargeType: 1,
      /** 系统维护 -- 提货计价方式 */
      systemPickupChargeType: 1,
      /** 系统维护 -- 仓库计价方式 */
      systemWarehouseChargeType: 1,
      /** 件数 */
      num: 0,
      /** 重量(kg) */
      weight: 0,
      /** 体积(方) */
      volume: 0,
      /** 单价 */
      price: 0,
      /** 系统维护 -- 运费单价 */
      freightPrice: 0,
      /** 系统维护 -- 配送单价 */
      deliveryPrice: 0,
      /** 系统维护 -- 提货单价 */
      pickupPrice: 0,
      /** 运费小计 */
      subtotalFreight: 0,
      /** 货物名称list */
      goodsListOptions: [],
    },
  ],
  /** 仓库数组 */
  options: [],
  /** 品牌数组 */
  brandOptions: [],
  /** 到站地区数组 */
  regionOptione: [],
  /** 收货方 -- 收货单位 */
  consigneeOptions: [],
  /** 收货方 -- 收货人 */
  consigneeNameOptions: [],
  /** 收货方 -- 收货电话 */
  consigneeMobileOptions: [],
  /** 发货方 -- 收货单位 */
  shipperOptions: [],
  /** 收货方 -- 收货人 */
  shipperNameOptions: [],
  /** 收货方 -- 收货电话 */
  shipperMobileOptions: [],
  /** 必填 */
  rules: {
    /** 品牌 */
    brandId: {
      required: true,
      message: '请选择品牌',
      trigger: ['change', 'blur'],
    },
    /** 发站仓名称 */
    departureWarehouseName: [
      {
        required: true,
        message: '请填写或选择发站仓',
        trigger: ['change', 'blur'],
      },
    ],
    /** 发站 */
    departure: [
      {
        required: true,
        message: '请填写或选择发站地',
        trigger: ['change', 'blur'],
      },
    ],
    /** 到站 */
    destination: [
      {
        required: true,
        message: '请填写或选择到站地',
        trigger: ['change', 'blur'],
      },
    ],
    /** 目的站名称 */
    queryDestinationWarehouseName: [
      {
        required: true,
        message: '请选择目的仓',
        trigger: ['blur', 'change'],
      },
    ],
    /** 发货单位 */
    shipper: [
      {
        required: true,
        message: '请选择或输入发货单位',
        trigger: ['change', 'blur'],
      },
    ],
    /** 发货人 */
    shipperName: [
      {
        required: true,
        message: '请选择或输入收货人',
        trigger: ['change', 'blur'],
      },
    ],
    /** 发货人电话 */
    shipperMobile: [
      {
        required: true,
        message: '请选择或输入发货人电话',
        trigger: ['change', 'blur'],
      },
    ],
    /** 收货单位 */
    consignee: [
      {
        required: true,
        message: '请选择或输入收货单位',
        trigger: ['change', 'blur'],
      },
    ],
    /** 收货人 */
    consigneeName: [
      {
        required: true,
        message: '请选择或输入收货人',
        trigger: ['change', 'blur'],
      },
    ],
    /** 收货人电话 */
    consigneeMobile: [
      {
        required: true,
        message: '请选择或输入收货人电话',
        trigger: ['change', 'blur'],
      },
    ],
    /** 付款方式 */
    payWay: [
      {
        required: true,
        message: '请选择付款方式',
        trigger: 'change',
      },
    ],
    /** 送货方式 */
    deliveryWay: [
      {
        required: true,
        message: '请选择送货方式',
        trigger: 'change',
      },
    ],
    /** 紧急度 */
    urgency: [
      {
        required: true,
        message: '请选择紧急度',
        trigger: 'change',
      },
    ],
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 是否继续开单 */
    titleVisited: false,
    /** 改单原因 */
    causeVisited: false,
    /** 打印弹窗 */
    WaybillPrintTemplate: false,
  },
  itemRules: {
    /** 计价方式 */
    chargeType: [
      {
        required: true,
        message: '请填写运单号',
        trigger: 'blur',
      },
    ],
    /** 收货人地址 */
    goodsName: [
      {
        required: true,
        message: '请填写运单号',
        trigger: 'blur',
      },
    ],

    /** 收货人地址 */
    num: [
      {
        required: true,
        message: '请填写运单号',
        trigger: 'blur',
      },
    ],
  },
  /** 页面loading */
  loadingObj: {
    loading: false,
    /** 配载信息loading */
    stowageLoading: false,
    /** 收货方 */
    consignerLoading: false,
    /** 提交 */
    submitLoadingBtn: false,
    /** qrCode */
    qrCodeLoading: false,
    pageLoading: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 页面数据 */
  pageInfo: {},
  /** 修改 -- 深拷贝goodsList, 区别：新增 / 删除 / 修改 */
  deepCloneGoodsList: [],
  /** 提交数据 */
  submitData: {},
  priceArr: [
    /** 单价 */
    { name: '运费', key: 'price' },
    /** 送货费 */
    { name: '配送费', key: 'deliveryFee' },
    // { name: '提货费', key: 'pickupFee' },
    /** 仓库管理费 */
    { name: '仓库管理费', key: 'warehouseManagementFee' },
    /** 仓储费 */
    { name: '仓库存储费', key: 'storageFee' },
    /** 装卸费 */
    // { name: '仓库存储费', key: 'storageFee' },
  ],
  /** 修改原因 */
  causeForm: {},
  /** 修改列表 */
  changeColumnList: [
    {
      prop: 'itemName',
      label: '修改项',
      type: 1,
      values: '',
      width: '',
      checkarr: [],
      fixed: false,
      sortable: true,
    },
    {
      prop: 'oldValue',
      label: '修改前',
      type: 1,
      values: '',
      width: '',
      checkarr: [],
      fixed: false,
      sortable: true,
    },
    {
      prop: 'newValue',
      label: '修改后',
      type: 1,
      values: '',
      width: '',
      checkarr: [],
      fixed: false,
      sortable: false,
    },
  ],
  /** 修改数据 */
  changeData: [],
  /** 提交后后台返回的waybillId */
  waybillId: '',
  /** 打印html */
  html: '',
  /** 页面Id -- 新增为空 */
  pageId: undefined,
});

/** 是否禁用 */
const isDisabled = computed(() => {
  if (getObjType(details.priceTemplate) !== 'object') return false;

  const { template } = details.priceTemplate;

  if (getObjType(template) !== 'object') return false;

  // 是否干线特殊配置
  const { trunklineIsPeculiarSetup } = template;

  const blackArr = ['金牌'];

  const _flag = blackArr.includes(details.query.brand);

  if (_flag && trunklineIsPeculiarSetup) return true;
  else return false;
});

const { query, data, drawerShow, loadingObj } = toRefs(details);

// 深拷贝基础数据
details.deepQuery = deepClone(details.query);

// 合计费用
const totalCost = computed(() => {
  // let _num = 0;
  const _num = computeNumber(0, '+', details.query.totalFreight || 0)
    .next('+', details.query.deliveryFee || 0)
    .next('+', details.query.pickupFee || 0)
    .next('+', details.query.warehouseManagementFee || 0)
    .next('+', details.query.storageFee || 0)
    .next('+', details.query.handlingFee || 0)
    .next('+', details.query.sortingFee || 0)
    .next('+', details.query.otherFee || 0)
    .next('+', details.query.insuranceFee || 0)
    .next('+', details.query.rebate || 0)
    .next('+', details.query.installFee || 0)
    .next('+', details.query.thirdOperationFee || 0).result;

  handlePayWay(_num);
  return _num;
});

const consignee = ref();
const consigneeName = ref();
const consigneeMobile = ref();
// 存放收货方节点的数组
const consigneeNodeList = [consignee, consigneeName, consigneeMobile];

const shipper = ref();
const shipperName = ref();
const shipperMobile = ref();
// 存放发货方节点的数组
const shipperNodeList = [shipper, shipperName, shipperMobile];

// 货物数组
const goodsNameRef = ref();

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

// 改单时, 对数据库内到站值进行转译
const handleTranslationLocation = key => {
  // 获取数据库中地址值
  const _location = details.query[key];

  let _arr = [];

  // 循环查找匹配的到站地址
  for (const iterator of details.regionOptione) {
    let isBreak = false;

    if (iterator.label === _location) {
      _arr = [iterator.value];
      isBreak = true;
    } else if (getObjType(iterator.children) === 'array') {
      for (const item of iterator.children) {
        if (item.label === _location) {
          _arr = [iterator.value, item.value];
          isBreak = true;
          break;
        } else if (getObjType(item.children) === 'array') {
          for (const value of item.children) {
            if (value.label === _location) {
              _arr = [iterator.value, item.value, value.value];
              isBreak = true;
              break;
            }
          }
        }
      }
      if (isBreak) break;
    }

    if (isBreak) break;
  }

  details.query[key] = _arr;
};

onMounted(() => {});

/** 获取车型 */
/** 获取车型 */
getList({}).then(res => {
  const { code, data } = res.data;
  if (code !== 200 || getObjType(data) !== 'array') return;

  details.vehicleTypeArr = data.map(val => {
    return {
      dictKey: val.id,
      dictValue: val.vehicleModel,
    };
  });
});

const initPageInfo = async () => {
  details.pageInfo = $route.query;

  try {
    details.loadingObj.submitLoadingBtn = true;

    await getLazyTreeAll().then(res => {
      if (res.data.success) {
        details.regionOptione = res.data.data;

        // if (details.query.destination) handleTranslationLocation();
      }
    });

    console.log('$route :>> ', $route);
    // 新增
    if ($route.query.type !== 'edit') await onLoad();
    // 编辑
    else {
      const res = await postFindWaybillDetail({ waybillId: details.pageInfo.id, isEdit: 1 });
      const { code, data } = res.data;
      if (code !== 200) return;

      details.query = { ...data, ...data.warehouseWaybill };

      details.query.trainNumber = details.query.customerTrain;

      details.info = data;
      details.query.openOrderUserName = data.warehouseWaybill.agent;
      delete details.query.warehouseWaybill;
      details.query.queryDestinationWarehouseName = details.query.destinationWarehouseName;
      console.log('data :>> ', data);
      details.query.openOrderDate = data.warehouseWaybill.documentMakingTime;
      details.query.orderCode = data.warehouseWaybill.orderNo;

      // 是否提货
      details.query.isPickUp =
        details.query.pickupFee && Number(details.query.pickupFee) > 0 ? 1 : 0;
      // 是否整车 -- 提货
      details.query.pickupCompleteOrNot = details.query.pickupCompleteOrNot
        ? details.query.pickupCompleteOrNot
        : 0;
      // 是否整车 -- 干线
      details.query.trunklineCompleteOrNot = details.query.trunklineCompleteOrNot
        ? details.query.trunklineCompleteOrNot
        : 0;

      details.query.transportType = details.query.transportType ? details.query.transportType : '1';
      details.query.deliveryWay = details.query.deliveryWay ? details.query.deliveryWay : '1';
      details.query.urgency = details.query.urgency ? details.query.urgency : '1';
      details.query.receipt = data.warehouseWaybill.receipt
        ? data.warehouseWaybill.receipt.split(',')
        : [];

      details.query.xianPay = isNumber(data.warehouseWaybill.xpay)
        ? Number(data.warehouseWaybill.xpay)
        : data.warehouseWaybill.xpay || 0;
      details.query.huiPay = isNumber(data.warehouseWaybill.hpay)
        ? Number(data.warehouseWaybill.hpay)
        : data.warehouseWaybill.hpay || 0;
      details.query.yuePay = isNumber(data.warehouseWaybill.ypay)
        ? Number(data.warehouseWaybill.ypay)
        : data.warehouseWaybill.ypay || 0;
      details.query.daoPay = isNumber(data.warehouseWaybill.dpay)
        ? Number(data.warehouseWaybill.dpay)
        : data.warehouseWaybill.dpay || 0;
      // 转译到站
      if (details.regionOptione.length !== 0) {
        handleTranslationLocation('departure');
        handleTranslationLocation('destination');
      }

      if (details.query.zeroEditStatus === 0)
        ElMessage.warning('该零担运单始发仓或目的仓未齐套，禁止编辑货物名称和件数');

      // 初始化goodsList
      if (data.warehouseWaybill.detailList.length === 0)
        details.goodsList = [
          {
            index: 0,
            /** 货物名称  */
            goodsName: '',
            /** 品类Id */
            goodsId: '',
            /** 计费方式 */
            chargeType: 1,
            /** 系统维护 -- 干线计价方式 */
            systemChargeType: 1,
            /** 系统维护 -- 配送计价方式 */
            systemDeliveryChargeType: 1,
            /** 系统维护 -- 提货计价方式 */
            systemPickupChargeType: 1,
            /** 系统维护 -- 仓库计价方式 */
            systemWarehouseChargeType: 1,
            /** 件数 */
            num: 0,
            /** 重量(kg) */
            weight: 0,
            /** 体积(方) */
            volume: 0,
            /** 单价 */
            price: 0,
            /** 系统维护 -- 运费单价 */
            freightPrice: 0,
            /** 系统维护 -- 配送单价 */
            deliveryPrice: 0,
            /** 系统维护 -- 提货单价 */
            pickupPrice: 0,
            /** 运费小计 */
            subtotalFreight: 0,
            /** 货物名称list */
            goodsListOptions: [],
          },
        ];
      else {
        details.deepCloneGoodsList = [];
        details.goodsList = data.warehouseWaybill.detailList.map(val => {
          val.num = Number(val.num);
          val.volume = Number(val.volume);
          val.weight = Number(val.weight);
          val.price = Number(val.price);
          val.freightPrice = isNumber(val.freightPrice) ? Number(val.freightPrice) : 0;
          val.deliveryPrice = isNumber(val.deliveryPrice) ? Number(val.deliveryPrice) : 0;
          val.pickupPrice = isNumber(val.pickupPrice) ? Number(val.pickupPrice) : 0;
          val.subtotalFreight = isNumber(val.subtotalFreight) ? Number(val.subtotalFreight) : 0;
          val.subtotalPickup = isNumber(val.subtotalPickup) ? Number(val.subtotalPickup) : 0;
          val.subtotalDeliveryFee = isNumber(val.subtotalDeliveryFee)
            ? Number(val.subtotalDeliveryFee)
            : 0;

          /** 系统维护 -- 干线计价方式 */
          val.systemChargeType = val.systemChargeType || 1;
          /** 系统维护 -- 配送计价方式 */
          val.systemDeliveryChargeType = val.systemDeliveryChargeType || 1;
          /** 系统维护 -- 提货计价方式 */
          val.systemPickupChargeType = val.systemPickupChargeType || 1;
          /** 系统维护 -- 仓库计价方式 */
          val.systemWarehouseChargeType = val.systemWarehouseChargeType || 1;

          val.goodsName = val.productName;
          val.goodsId = val.productId;
          val.chargeType = val.chargeType || 1;

          /** 货物名称list */
          val.goodsListOptions = [];

          // 计算运费小计
          // if (!val.subtotalFreight) handleComputed(val);

          // 计算件数最大值
          details.deepCloneGoodsList.push({ ...val });
          return val;
        });
      }

      // 获取客户价格, 但不对干线价格进行赋值
      handleFindPrice(true);
    }

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

      handleFindGoods(element.goodsName, element);
    }

    if (shipper) handleFindClientInfo('shipper');
    if (shipperName) handleFindClientInfo('shipperName');
    if (shipperMobile) handleFindClientInfo('shipperMobile');
    if (consignee) handleFindClientInfo('consignee');
    if (consigneeName) handleFindClientInfo('consigneeName');
    if (consigneeMobile) handleFindClientInfo('consigneeMobile');
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.submitLoadingBtn = false;
  }
};

/** 初始化获取暂存单转运单信息 */
const onLoad = async () => {
  try {
    details.query = deepClone(details.deepQuery);

    const res = await postOpenOrderOpenZeroWaybillInfo();
    const { code, data } = res.data;
    console.log('data :>> ', data);
    if (code !== 200) return;
    // 存储请求的数据
    details.info = data;

    for (let key in data) {
      if (data[key]) details.query[key] = data[key];
    }
    // 初始化选择支付方式
    if (details.info.defaultPayWay) {
      details.query.payWay = details.info.defaultPayWay;
    } else {
      details.query.payWay =
        details.info.payWayList.find(val => val.dictValue === '到付').dictKey || '2';
    }
    details.query.transportType = '1';
    details.query.deliveryWay = '1';
    details.query.urgency = '1';
    // details.query.destination = '';
    details.query.shipperId = data.shipperClientId || '';
    details.query.consigneeId = data.consigneeClientId || '';

    details.query.destination =
      getObjType(data.destinationArray) === 'array' ? data.destinationArray : [];
    details.query.departure =
      getObjType(data.departureArray) === 'array' ? data.departureArray : [];

    details.query.queryDestinationWarehouseName = data.destinationWarehouseName || '';
    // 是否提货
    details.query.isPickUp = details.query.isPickUp ? details.query.isPickUp : 0;
    // 是否整车 -- 提货
    details.query.pickupCompleteOrNot = details.query.pickupCompleteOrNot
      ? details.query.pickupCompleteOrNot
      : 0;
    // 是否整车 -- 干线
    details.query.trunklineCompleteOrNot = details.query.trunklineCompleteOrNot
      ? details.query.trunklineCompleteOrNot
      : 0;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    console.log('details :>> ', details);
    return null;
  }
};

/** 新增 */
const handleAdd = () => {
  const _arr = [];

  for (let i = 0; i < details.goodsList.length; i++) {
    const val = details.goodsList[i];

    if (_arr.includes(val.goodsName)) return ElMessage.warning('存在重复品类名，请移除其中一项');
    else _arr.push(val.goodsName);

    if (val.goodsName === '' || !val.num) {
      return ElMessage({
        message: '请填写完整件数和名称',
        type: 'warning',
      });
    }
    if (val.chargeType === 2 && val.volume === 0) {
      return ElMessage({
        message: '请填写方数',
        type: 'warning',
      });
    }
    if (val.chargeType === 3 && val.weight === 0) {
      return ElMessage({
        message: '请填写重量',
        type: 'warning',
      });
    }
  }

  const _obj = {
    /** 货物名称  */
    goodsName: '',
    /** 品类Id */
    goodsId: '',
    /** 货物品类 */
    waybillDetailList: '',
    /** 计费方式 */
    chargeType: 1,
    /** 系统维护 -- 干线计价方式 */
    systemChargeType: 1,
    /** 系统维护 -- 配送计价方式 */
    systemDeliveryChargeType: 1,
    /** 系统维护 -- 提货计价方式 */
    systemPickupChargeType: 1,
    /** 系统维护 -- 仓库计价方式 */
    systemWarehouseChargeType: 1,
    /** 件数 */
    num: 0,
    /** 重量(kg) */
    weight: 0,
    /** 体积(方) */
    volume: 0,
    /** 单价 */
    price: 0,
    /** 系统维护 -- 运费单价 */
    freightPrice: 0,
    /** 系统维护 -- 配送单价 */
    deliveryPrice: 0,
    /** 系统维护 -- 提货单价 */
    pickupPrice: 0,
    /** 运费小计 */
    subtotalFreight: 0,
    goodsListOptions: [],
  };

  handleAssignmentItemPrice(_obj);

  details.goodsList.push(_obj);
};

/** 移除 */
const handleRemove = (index: number) => {
  details.goodsList.splice(index, 1);
};

/** 关闭select弹窗 */
const handleCloseSelcet = () => {
  shipperNodeList.forEach(val => val.value.handleClose());
  consigneeNodeList.forEach(val => val.value.handleClose());
  goodsNameRef.value.forEach(val => val.handleClose());
};

/** 查询目的仓 */
const remoteMethod = async val => {
  try {
    details.loadingObj.loading = true;
    const res = await getOpenOrderAdvanceFindWarehouseList({ warehouseName: val });
    const { data, code } = res.data;
    if (code !== 200) return;
    details.options = data || [];
  } catch (error) {
  } finally {
    details.loadingObj.loading = false;
  }
};

/** 查询品牌 */
const handleFindBrand = async () => {
  try {
    const res = await postFindBrandList();
    console.log('res :>> ', res);
    const { data, code } = res.data;
    if (code !== 200) return;
    console.log('data :>> ', data);
    details.brandOptions = data || [];
  } catch (error) {
    console.log('error :>> ', error);
  }
};

handleFindBrand();

remoteMethod('');

/** 目的仓选择时给目的仓名称赋值 */
const destinationWarehouseNameChange = val => {
  const _item = details.options.find(value => value.warehouseId === val);
  details.query.destinationWarehouseName = _item.warehouseName;
  details.query.destinationWarehouseId = _item.warehouseId;
  details.query.queryDestinationWarehouseName = details.query.destinationWarehouseName;
};

/** 查询货物 */
const handleFindGoods = async (goodsName, item, isClearId = 0) => {
  if (isClearId) {
    item.goodsId = '';
    item.confirmCostCategoryId = '';
    item.confirmCostCategoryName = '';
    item.confirmIncomeCategoryId = '';
    item.confirmIncomeCategoryName = '';
  }

  if (!goodsName) return (item.goodsListOptions = []);

  try {
    item.loading = true;
    const res = await postFindCategoryInfo({ goodsName });
    const { code, data } = res.data;

    if (code !== 200) return;
    item.goodsListOptions = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    item.loading = false;
  }
};

/** 计算行合计
 * row -- 行数据
 * onlyComputedTrunline -- 是否只计算干线的价格
 */
const handleComputed = (row: any, onlyComputedTrunline = false, chargeType = null) => {
  const { template, trunkLine } = details.priceTemplate;

  if (Boolean(isDisabled.value && template && trunkLine)) {
    if (!chargeType && !onlyComputedTrunline)
      handleSpecialBrandPrice(row, trunkLine, template, onlyComputedTrunline);
  }

  details.query.goodsCode = '-' + details.totalObj.totalCount;

  const typeArr = { 1: 'num', 2: 'volume', 3: 'weight' };

  const _trunklineKey = typeArr[row.chargeType];
  const _pickupKey = typeArr[row.systemPickupChargeType];
  const _dispatchKey = typeArr[row.systemDeliveryChargeType];
  const _warehouseManagementKey = typeArr[row.warehouseManagementType];
  const _warehouseHandlingKey = typeArr[row.warehouseHandlingType];
  const _warehouseSortingKey = typeArr[row.warehouseSortingType];

  // 计算干线价格 -- 行
  if (_trunklineKey)
    row.subtotalFreight = _trunklineKey
      ? computeNumber(row.price, '*', row[_trunklineKey]).result
      : 0;

  if (!onlyComputedTrunline) {
    // 计算提货价格 -- 行
    if (_pickupKey)
      row.subtotalPickup = _pickupKey
        ? computeNumber(row.pickupPrice || 0, '*', row[_pickupKey]).result
        : 0;

    // 计算配送价格 -- 行
    if (_dispatchKey)
      row.subtotalDeliveryFee = _dispatchKey
        ? computeNumber(row.deliveryPrice || 0, '*', row[_dispatchKey]).result
        : 0;

    if (_warehouseManagementKey)
      // 计算仓储管理费 -- 行
      row.subtotalWarehouseManagement = _warehouseManagementKey
        ? computeNumber(row.warehouseManagementPrice || 0, '*', row[_warehouseManagementKey]).result
        : 0;

    if (_warehouseHandlingKey)
      // 计算仓储操作费 -- 行
      row.subtotalWarehouseHandlingFee = _warehouseHandlingKey
        ? computeNumber(row.warehouseHandlingPrice || 0, '*', row[_warehouseHandlingKey]).result
        : 0;

    if (_warehouseSortingKey)
      // 计算仓储分拣费 -- 行
      row.subtotalWarehouseSortingFee = _warehouseSortingKey
        ? computeNumber(row.warehouseSortingPrice || 0, '*', row[_warehouseSortingKey]).result
        : 0;
    console.log('row :>> ', row);
  }

  handlePrice(!onlyComputedTrunline, 'trunkline');
};

/** 查询客户信息 */
const handleFindClientInfo = async (type, isClearId = 0) => {
  try {
    // 是否清除id
    if (isClearId === 1) {
      type === 'consignee' ? (details.query.consigneeId = '') : (details.query.shipperId = '');
    }

    if (!details.query[type]) return (details[type + 'Options'] = []);

    details.loadingObj.consignerLoading = true;

    const nameReg = new RegExp('Name');
    const MobileReg = new RegExp('Mobile');

    const submitData: any = {};
    if (nameReg.test(type)) submitData.linkMan = details.query[type];
    else if (MobileReg.test(type)) submitData.linkPhone = details.query[type];
    else submitData.clientName = details.query[type];

    const res = await postOpenOrderFindClientInfo(submitData);
    const { code, data } = res.data;
    if (code !== 200) return;
    details[type + 'Options'] = data || [];
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.consignerLoading = false;
  }
};

/** 客户选择 */
const handleChooseShipper = (column, prop, order) => {
  // 赋值
  details.query.shipper = column.clientName;
  details.query.shipperId = column.clientId;
  details.query.shipperAddress = column.linkAddress;
  details.query.shipperName = column.linkMan;
  details.query.shipperMobile = column.linkPhone;

  // 发站
  const _departure = [];
  if (column.provinceId) _departure[0] = column.provinceId;
  if (column.cityId) _departure[1] = column.cityId;
  if (column.areaId) _departure[2] = column.areaId;

  if (_departure.length > 0) details.query.departure = _departure;

  handleFindClientInfo('shipper');
  handleFindClientInfo('shipperName');
  handleFindClientInfo('shipperMobile');
  handleCloseSelcet();
};

/** 收货客户选择 */
const handleChooseConsigner = (column, prop, order) => {
  // 赋值
  details.query.consignee = column.clientName;
  details.query.consigneeId = column.clientId;
  details.query.consigneeAddress = column.linkAddress;
  details.query.consigneeName = column.linkMan;
  details.query.consigneeMobile = column.linkPhone;

  // 仓库
  if (column.destinationWarehouseId) {
    details.query.destinationWarehouseId = column.destinationWarehouseId;
    details.query.destinationWarehouseName = column.destinationWarehouseName;
    details.query.queryDestinationWarehouseName = column.destinationWarehouseName;
  }

  // 送货方式
  if (column.defaultDeliveryWay) details.query.deliveryWay = column.defaultDeliveryWay;
  if (column.defaultPayWay) details.query.payWay = column.defaultPayWay + '';

  // 到站
  const _destination = [];
  if (column.provinceId) _destination[0] = column.provinceId;
  if (column.cityId) _destination[1] = column.cityId;
  if (column.areaId) _destination[2] = column.areaId;

  if (_destination.length > 0) details.query.destination = _destination;

  // 收货单位维护过品牌，自动切换品牌
  if (column.brandId) {
    details.query.brandId = column.brandId;
    details.query.brand = details.brandOptions.find(
      val => val.brandId === details.query.brandId
    ).brandName;
  }

  handleFindClientInfo('consignee');
  handleFindClientInfo('consigneeName');
  handleFindClientInfo('consigneeMobile');
  handleCloseSelcet();
};

/** 返回 */
const back = () => {
  $store.commit('DEL_TAG_CURRENT');
  if (details.pageInfo.backPath) $router.push(details.pageInfo.backPath);
  else $router.push('/waybill/WaybillOrderList');
};

/** 检测支付金额 */
const handleDetectionPayWay = () => {
  const minNum = 0;
  const payType = Number(details.query.payWay);
  let content = '';

  switch (payType) {
    // 现付
    case 1:
      if (Number(details.query.xianPay) <= minNum) content = '请输入大于0的现付金额';
      break;

    // 到付
    case 2:
      if (Number(details.query.daoPay) <= minNum) content = '请输入大于0的到付金额';
      break;

    // 月结
    case 3:
      if (Number(details.query.yuePay) <= minNum) content = '请输入大于0的月结金额';
      break;

    // 回付
    case 4:
      if (Number(details.query.huiPay) <= minNum) content = '请输入大于0的回付金额';
      break;

    default:
      break;
  }

  return content;
};

/** 处理付款方式对应费用 */
const handlePayWay = (number?: number) => {
  const payType = Number(details.query.payWay);
  const enumPayType = {
    1: 'xianPay',
    2: 'daoPay',
    3: 'yuePay',
    4: 'huiPay',
  };

  for (const key in enumPayType) {
    const value = enumPayType[key];
    details.query[value] = 0;
  }

  const _item = enumPayType[payType];

  if (_item) {
    details.query[_item] = isNumber(number) ? number : totalCost.value;
  }
};

/** 处理提货费用 */
const handlePickUpPrice = (pickup, template) => {
  // 是否存在提货费用
  if (!details.query.isPickUp) return (details.query.pickupFee = 0);

  // 是否存在模板和维护价格
  if (!pickup || !template) return;

  // 是否整车
  if (details.query.pickupCompleteOrNot) {
    // 是否存在模板和维护价格
    if (!pickup || !template) return (details.query.pickupFee = 0);

    const { fullVehicle } = pickup;

    if (getObjType(fullVehicle) !== 'array') return;

    let item = {} as any;

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

      if (Number(value.vehicleType) !== Number(details.query.pickupVehicleTypeId)) continue;
      item = value;
      break;
    }

    details.query.pickupFee = details.query.pickupFee ? details.query.pickupFee : item.price || 0;
  } else {
    // 非整车
    let _total = 0;

    for (let i = 0; i < details.goodsList.length; i++) {
      _total = computeNumber(_total, '+', details.goodsList[i].subtotalPickup || 0).result;
    }

    // 是否存在最低计费
    if (
      (pickup || template) &&
      template.pickupIsMinCost &&
      Number(details.query.pickupCompleteOrNot) === 0
    ) {
      switch (Number(template.pickupMinCostType)) {
        // 价格
        case 1:
          details.query.pickupFee = pickup.minCost > _total ? pickup.minCost : _total;
          break;

        // 件
        case 2:
          details.query.pickupFee =
            pickup.minCost > details.totalObj.totalCount
              ? computeNumber(_total, '+', pickup.additionalCost || 0).result
              : _total;
          break;

        // 方
        case 3:
          details.query.pickupFee =
            pickup.minCost > details.totalObj.totalVolume
              ? computeNumber(_total, '+', pickup.additionalCost || 0).result
              : _total;
          break;

        // 重量
        case 4:
          details.query.pickupFee =
            pickup.minCost > details.totalObj.totalWeghit
              ? computeNumber(_total, '+', pickup.additionalCost || 0).result
              : _total;
          break;

        default:
          break;
      }
    } else details.query.pickupFee = _total;

    // details.query.pickupFee = _total;
  }
};

/** 处理干线费用 */
const handleTrunkLinePrice = (trunkLine, template) => {
  // 是否整车
  if (details.query.trunklineCompleteOrNot) {
    // 是否存在模板和维护价格
    if (!trunkLine || !template) return;

    const { fullVehicle } = trunkLine;

    if (getObjType(fullVehicle) !== 'array') return;

    let item: any = {};

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

      if (Number(value.vehicleType) !== Number(details.query.trunklineVehicleTypeId)) continue;
      item = value;
      break;
    }

    details.query.totalFreight = details.query.totalFreight
      ? details.query.totalFreight
      : item.price || 0;
  } else {
    // 非整车
    let _total = 0;

    for (let i = 0; i < details.goodsList.length; i++) {
      const value = details.goodsList[i];
      if (value.subtotalFreight)
        _total = computeNumber(_total, '+', value.subtotalFreight || 0).result;
    }

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

    // 是否存在最低计费
    if (trunkLine && template && template.trunklineIsMinCost) {
      switch (Number(template.trunklineMinCostType)) {
        // 价格
        case 1:
          details.query.totalFreight = trunkLine.minCost > _total ? trunkLine.minCost : _total;
          break;

        // 件
        case 2:
          details.query.totalFreight =
            trunkLine.minCost > details.totalObj.totalCount
              ? computeNumber(_total, '+', trunkLine.additionalCost || 0).result
              : _total;
          break;

        // 方
        case 3:
          details.query.totalFreight =
            trunkLine.minCost > details.totalObj.totalVolume
              ? computeNumber(_total, '+', trunkLine.additionalCost || 0).result
              : _total;
          break;

        // 重量
        case 4:
          details.query.totalFreight =
            trunkLine.minCost > details.totalObj.totalWeghit
              ? computeNumber(_total, '+', trunkLine.additionalCost || 0).result
              : _total;
          break;

        default:
          break;
      }
    } else details.query.totalFreight = _total;
  }
};

/** 处理配送费 */
const handleDispatchPrice = (dispatch, template) => {
  // 是否存在模板和维护价格
  if (!dispatch || !template) return (details.query.deliveryFee = 0);

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

  // 非整车
  let _total = 0;

  for (let i = 0; i < details.goodsList.length; i++) {
    const value = details.goodsList[i];
    if (value.subtotalDeliveryFee)
      _total = computeNumber(_total, '+', value.subtotalDeliveryFee || 0).result;
  }

  // 是否存在最低计费
  if (
    dispatch &&
    template &&
    template.trunklineIsMinCost &&
    Number(template.dispatchMinCostMode) === 1
  ) {
    switch (Number(template.dispatchMinCostType)) {
      // 价格
      case 1:
        details.query.deliveryFee = dispatch.minCost > _total ? dispatch.minCost : _total;
        break;

      // 件
      case 2:
        details.query.deliveryFee =
          dispatch.minCost > details.totalObj.totalCount
            ? computeNumber(_total, '+', dispatch.additionalCost || 0).result
            : _total;
        break;

      // 方
      case 3:
        details.query.deliveryFee =
          dispatch.minCost > details.totalObj.totalVolume
            ? computeNumber(_total, '+', dispatch.additionalCost || 0).result
            : _total;
        break;

      // 重量
      case 4:
        details.query.deliveryFee =
          dispatch.minCost > details.totalObj.totalWeghit
            ? computeNumber(_total, '+', dispatch.additionalCost || 0).result
            : _total;
        break;

      default:
        break;
    }
  } else details.query.deliveryFee = _total;
};

/** 处理仓库管理费 */
const handleWarehouseManagement = () => {
  let _total = 0;

  for (let i = 0; i < details.goodsList.length; i++) {
    const value = details.goodsList[i];

    _total = computeNumber(_total, '+', value.subtotalWarehouseManagement || 0).result;
  }

  details.query.warehouseManagementFee = _total;
};

/** 处理仓储操作费 */
const handleWarehouseHandlingFee = () => {
  let _total = 0;

  for (let i = 0; i < details.goodsList.length; i++) {
    const value = details.goodsList[i];

    _total = computeNumber(_total, '+', value.subtotalWarehouseHandlingFee || 0).result;
  }

  details.query.handlingFee = _total;
};

/** 处理仓储分拣费 */
const handleWarehouseSortingFee = () => {
  let _total = 0;

  for (let i = 0; i < details.goodsList.length; i++) {
    const value = details.goodsList[i];

    _total = computeNumber(_total, '+', value.subtotalWarehouseSortingFee || 0).result;
  }

  details.query.sortingFee = _total;
};

/** 处理模板费用 */
const handlePrice = (isAll = false, type) => {
  const { dispatch, pickup, template, trunkLine } = details.priceTemplate;

  /** 处理提货费用 */
  (isAll || type === 'pickup') && handlePickUpPrice(pickup, template);
  /** 处理干线费用 */
  (isAll || type === 'trunkline') && handleTrunkLinePrice(trunkLine, template);
  /** 处理配送费 */
  (isAll || type === 'dispatch') && handleDispatchPrice(dispatch, template);
  /** 处理仓库管理费 */
  (isAll || type === 'warehouseMangement') && handleWarehouseManagement();
  /** 处理仓储操作费 */
  (isAll || type === 'warehousehandling') && handleWarehouseHandlingFee();
  /** 处理仓储分拣费 */
  (isAll || type === 'warehouseSorting') && handleWarehouseSortingFee();
};

/** 聚焦后全选 */
const handleInputFocus = e => {
  e.srcElement.select();
};

/** 重置值 */
const handleRefreshText = (key, value, refreshValue?: string | number) => {
  if (value) return;
  query.value[key] = refreshValue ? refreshValue : '';
};

/** 重置数据 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  details.goodsList = [
    {
      /** 货物名称  */
      goodsName: '',
      /** 品类Id */
      goodsId: '',
      /** 货物品类 */
      waybillDetailList: '',
      /** 计费方式 */
      chargeType: 1,
      /** 系统维护 -- 干线计价方式 */
      systemChargeType: 1,
      /** 系统维护 -- 配送计价方式 */
      systemDeliveryChargeType: 1,
      /** 系统维护 -- 提货计价方式 */
      systemPickupChargeType: 1,
      /** 系统维护 -- 仓库计价方式 */
      systemWarehouseChargeType: 1,
      /** 件数 */
      num: 0,
      /** 重量(kg) */
      weight: 0,
      /** 体积(方) */
      volume: 0,
      /** 单价 */
      price: 0,
      /** 系统维护 -- 运费单价 */
      freightPrice: 0,
      /** 系统维护 -- 配送单价 */
      deliveryPrice: 0,
      /** 系统维护 -- 提货单价 */
      pickupPrice: 0,
      /** 运费小计 */
      subtotalFreight: 0,
      goodsListOptions: [],
    },
  ];
  initPageInfo();
};

/** 计算品类单价 -- 系统单价 */
const handleComputedPlanPrice = submitData => {
  const { dispatch, pickup, template, trunkLine } = details.priceTemplate;

  // 总件数
  const _totalCount = details.totalObj.totalCount;

  const { addList } = submitData;
  const typeArr = { 1: 'num', 2: 'volume', 3: 'weight' };

  // 计算 运费 & 提货费 & 送货费 & 仓库管理费 基础合计
  let _total = 0;
  /** 干线 */
  let _planTrunklineFee = 0;
  let _trunklineFee = 0;
  /** 提货 */
  let _planSubtotalPickup = 0;
  let _subtotalPickup = 0;
  /** 送货 */
  let _totalPlanPrce = 0;
  let _totalPrce = 0;

  for (let i = 0; i < addList.length; i++) {
    const _val = addList[i];
    const _trunklineKey = typeArr[_val.chargeType];
    const _pickupKey = typeArr[_val.systemPickupChargeType];
    const _deliveryKey = typeArr[_val.systemDeliveryChargeType];
    console.log('_trunklineKey :>> ', _trunklineKey);
    console.log('_pickupKey :>> ', _pickupKey);

    // 干线费
    _trunklineFee = computeNumber(
      _trunklineFee,
      '+',
      _trunklineKey ? computeNumber(_val.freightPrice || 0, '*', _val[_trunklineKey]).result : 0
    ).result;

    // 提货费
    _subtotalPickup = computeNumber(
      _subtotalPickup,
      '+',
      _pickupKey ? computeNumber(_val.pickupPrice || 0, '*', _val[_pickupKey]).result : 0
    ).result;

    // 送货费
    _totalPrce = computeNumber(
      _totalPrce,
      '+',
      _deliveryKey ? computeNumber(_val.deliveryPrice || 0, '*', _val[_deliveryKey]).result : 0
    ).result;
  }

  // 是否存在最低计费 -- 干线
  if (trunkLine && template && template.trunklineIsMinCost) {
    switch (Number(template.trunklineMinCostType)) {
      // 价格
      case 1:
        _planTrunklineFee = trunkLine.minCost > _trunklineFee ? trunkLine.minCost : _trunklineFee;
        break;

      // 件
      case 2:
        _planTrunklineFee =
          trunkLine.minCost > details.totalObj.totalCount
            ? _trunklineFee + (trunkLine.additionalCost || 0)
            : _trunklineFee;
        break;

      // 方
      case 3:
        _planTrunklineFee =
          trunkLine.minCost > details.totalObj.totalVolume
            ? _trunklineFee + (trunkLine.additionalCost || 0)
            : _trunklineFee;
        break;

      // 重量
      case 4:
        _planTrunklineFee =
          trunkLine.minCost > details.totalObj.totalWeghit
            ? _trunklineFee + (trunkLine.additionalCost || 0)
            : _trunklineFee;
        break;

      default:
        break;
    }
  }

  // 是否存在最低计费 -- 提货
  if (pickup && template && template.pickupIsMinCost) {
    switch (Number(template.pickupMinCostType)) {
      // 价格
      case 1:
        _planSubtotalPickup = pickup.minCost > _subtotalPickup ? pickup.minCost : _subtotalPickup;
        break;

      // 件
      case 2:
        _planSubtotalPickup =
          pickup.minCost > details.totalObj.totalCount
            ? _subtotalPickup + (pickup.additionalCost || 0)
            : _subtotalPickup;
        break;

      // 方
      case 3:
        _planSubtotalPickup =
          pickup.minCost > details.totalObj.totalVolume
            ? _subtotalPickup + (pickup.additionalCost || 0)
            : _subtotalPickup;
        break;

      // 重量
      case 4:
        _planSubtotalPickup =
          pickup.minCost > details.totalObj.totalWeghit
            ? _subtotalPickup + (pickup.additionalCost || 0)
            : _subtotalPickup;
        break;

      default:
        break;
    }
  }

  // 配送
  if (dispatch && template && template.dispatchIsMinCost) {
    switch (Number(template.dispatchMinCostType)) {
      // 价格
      case 1:
        _totalPlanPrce = dispatch.minCost > _totalPrce ? dispatch.minCost : _totalPrce;
        break;

      // 件
      case 2:
        _totalPlanPrce =
          dispatch.minCost > details.totalObj.totalCount
            ? _totalPrce + (dispatch.additionalCost || 0)
            : _totalPrce;
        break;

      // 方
      case 3:
        _totalPlanPrce =
          dispatch.minCost > details.totalObj.totalVolume
            ? _totalPrce + (dispatch.additionalCost || 0)
            : _totalPrce;
        break;

      // 重量
      case 4:
        _totalPlanPrce =
          dispatch.minCost > details.totalObj.totalWeghit
            ? _totalPrce + (dispatch.additionalCost || 0)
            : _totalPrce;
        break;

      default:
        break;
    }
  }

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

  for (let i = 0; i < addList.length; i++) {
    const val = addList[i];
    // 干线
    if (trunkLine && template && template.trunklineIsMinCost) {
      const differenceValue = computeNumber(_planTrunklineFee, '-', _trunklineFee).next(
        '/',
        _totalCount
      ).result;

      val.freightPrice = floorToDecimalPlaces(
        computeNumber(differenceValue, '*', val.num)
          .next('/', val[typeArr[val.chargeType]])
          .next('+', val.freightPrice).result,
        2
      );
    }

    // 提货
    if (pickup && template && template.pickupIsMinCost) {
      const differenceValue = computeNumber(_planSubtotalPickup, '-', _subtotalPickup).next(
        '/',
        _totalCount
      ).result;

      val.pickupPrice = floorToDecimalPlaces(
        computeNumber(differenceValue, '*', val.num)
          .next('/', val[typeArr[val.systemPickupChargeType]])
          .next('+', val.pickupPrice).result,
        2
      );
    }

    // 配送
    if (dispatch && template && template.dispatchIsMinCost) {
      console.log('_totalPlanPrce :>> ', _totalPlanPrce);
      console.log('_totalPrce :>> ', _totalPrce);
      const differenceValue = computeNumber(_totalPlanPrce, '-', _totalPrce).next(
        '/',
        _totalCount
      ).result;
      console.log('differenceValue :>> ', differenceValue);

      val.deliveryPrice = floorToDecimalPlaces(
        computeNumber(differenceValue, '*', val.num)
          .next('/', val[typeArr[val.systemDeliveryChargeType]])
          .next('+', val.deliveryPrice).result,
        2
      );
    }
  }
};

const getTranslationArr = codeArr => {
  const _nameArr = [];
  let _item = {};

  _nameArr[0] = details.regionOptione.find(val => val.value === codeArr[0]);

  _nameArr[1] = _nameArr[0].children.find(val => val.value === codeArr[1]);

  if (codeArr.length === 2) {
    _item = _nameArr[1];
  } else {
    _nameArr[2] = _nameArr[1].children.find(val => val.value === codeArr[2]);
    _item = _nameArr[2];
  }

  return {
    locationItem: _item,
    nameArr: _nameArr,
  };
};

/** 提交 */
const handleSubmit = async (formEl: FormInstance | undefined) => {
  await nextTick();

  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      details.loadingObj.submitLoadingBtn = true;

      const timer = setTimeout(async () => {
        try {
          // if (!details.query.shipperId)
          //   return ElMessage.warning('请选择系统内维护的发货单位，请选择或维护');
          // if (!details.query.consigneeId)
          //   return ElMessage.warning('请选择系统内维护的收货单位，请选择或维护');
          if (!details.query.openOrderDate) return ElMessage.warning('请选择制单时间');

          let _arr = [];

          for (let i = 0; i < details.goodsList.length; i++) {
            const val = details.goodsList[i];
            // 检测货物名称和件数是否正确填写
            if (!val.goodsName || !isNumber(val.num) || val.num === 0)
              return ElMessage.warning('请填写正确的货物名称和件数');

            if (_arr.includes(val.goodsName))
              return ElMessage.warning('存在重复的货物名称，请移除');

            val.chargeType = !isNumber(val.chargeType) || !val.chargeType ? 1 : val.chargeType;
            val.systemChargeType =
              !isNumber(val.systemChargeType) || !val.systemChargeType ? 1 : val.systemChargeType;
            val.systemDeliveryChargeType =
              !isNumber(val.systemDeliveryChargeType) || !val.systemDeliveryChargeType
                ? 1
                : val.systemDeliveryChargeType;
            val.systemPickupChargeType =
              !isNumber(val.systemPickupChargeType) || !val.systemPickupChargeType
                ? 1
                : val.systemPickupChargeType;
            val.systemWarehouseChargeType =
              !isNumber(val.systemWarehouseChargeType) || !val.systemWarehouseChargeType
                ? 1
                : val.systemWarehouseChargeType;
            val.weight = !isNumber(val.weight) ? 0 : val.weight;
            val.volume = !isNumber(val.volume) ? 0 : val.volume;
            val.price = !isNumber(val.price) ? 0 : val.price;
            val.freightPrice = !isNumber(val.freightPrice) ? 0 : val.freightPrice;
            val.deliveryPrice = !isNumber(val.deliveryPrice) ? 0 : val.deliveryPrice;
            val.pickupPrice = !isNumber(val.pickupPrice) ? 0 : val.pickupPrice;
            val.subtotalFreight = !isNumber(val.subtotalFreight) ? 0 : val.subtotalFreight;
          }

          // if (!(details.query.totalFreight > 0)) return ElMessage.warning('请输入大于零的运费');
          if (totalCost.value === 0) return ElMessage.warning('合计费用不能等于0');

          console.log('submit!');
          const submitData = {
            ...details.totalObj,
            ...details.query,
            advanceIds: details.info.advanceIds,
            huilaiPay: 1,
            addList: [],
            removeList: [],
          };

          submitData.customerTrain = details.query.trainNumber;

          const { destination, departure } = submitData;

          console.log('destination :>> ', destination);
          if (destination.length === 1) {
            return ElMessage({ message: '请选择正确到站地址', type: 'warning' });
          }

          if (departure.length === 1)
            return ElMessage({ message: '请选择正确发站地址', type: 'warning' });

          // 筛选到站
          const { locationItem: _itemDestination, nameArr: dest_nameArr } =
            getTranslationArr(destination);

          submitData.destination = _itemDestination.label;
          submitData.destinationCode = _itemDestination.value;
          submitData.completeDestination = dest_nameArr.map(val => val.label).join('/');

          // 筛选发站
          const { locationItem: _itemDeparture, nameArr: de_nameArr } =
            getTranslationArr(departure);

          submitData.departure = _itemDeparture.label;
          submitData.departureCode = _itemDeparture.value;
          submitData.completeDeparture = de_nameArr.map(val => val.label).join('/');

          // let numFlag = false;

          // for (const iterator of details.goodsList) {
          //   if (iterator.subtotalFreight <= 0 || !iterator.subtotalFreight) {
          //     numFlag = true;
          //     break;
          //   }

          // }

          // if (numFlag) return ElMessage.warning('小计费用存在异常');

          const _content = handleDetectionPayWay();
          if (_content) return ElMessage.warning(_content);

          submitData.goodsName = details.goodsList.map(val => val.goodsName).join(',');
          let res: any = {};
          // 新增提交
          if (details.pageInfo.type !== 'edit') {
            submitData.addList = details.goodsList;
            submitData.removeList = [];

            if (typeof submitData.receipt === 'object')
              submitData.receipt = submitData.receipt.join(',');

            // 记录提交参数
            details.submitData = submitData;

            // 零担 -- 2
            submitData.waybillType = 2;
            handleComputedPlanPrice(submitData);

            console.log('submitData :>> ', submitData);
            res = await postOpenOrderOpenZeroWaybill(submitData);

            const { code, data, msg } = res.data;
            if (code !== 200) return;
            ElMessage({
              message: msg,
              type: 'success',
            });

            details.waybillId = getObjType(data) === 'object' ? data.waybillId || '' : '';

            // 开启提示框, 是否继续开单
            if (details.pageInfo.type !== 'edit') details.popUpShow.titleVisited = true;
          } else {
            submitData.waybillId = details.pageInfo.id;

            const oldGoodsList = [...details.deepCloneGoodsList];

            for (let iterator of details.goodsList) {
              // 查看每一项是否存在Id updateType: 1新增; 2修改
              if (iterator.id) {
                // 存在则证明为老数据

                // 根据存在的数据, 筛选被删除的数据
                const _item = oldGoodsList.splice(
                  oldGoodsList.findIndex(val => val.id === iterator.id),
                  1
                );

                // 检测是否被修改
                let _flag = false;

                for (const key in iterator) {
                  _flag = iterator[key] !== _item[key];
                  // 检测到不一致则退出循环
                  if (_flag) break;
                }

                if (_flag) submitData.addList.push({ ...iterator, updateType: 2 });
              } else {
                submitData.addList.push({ ...iterator, updateType: 1 });
              }
            }

            submitData.removeList = oldGoodsList;

            delete submitData.goodsList;

            submitData.waybillType = 1;
            if (typeof submitData.receipt === 'object')
              submitData.receipt = submitData.receipt.join(',');
            console.log('submitData :>> ', submitData);

            handleComputedPlanPrice(submitData);
            // 记录提交参数
            details.submitData = submitData;

            const response = await postUpdateWaybillVerify(submitData);
            if (response.data.code !== 200) return;

            if (!response.data.data || response.data.data.length === 0)
              return ElMessage.warning('没有更改的数据');

            details.changeData = response.data.data;
            details.popUpShow.causeVisited = true;
            await nextTick();

            setNodeHeight(tableNode.value.$el, '40vh');
          }
        } catch (error) {
          console.log('error :>> ', error);
        } finally {
          clearTimeout(timer);
          // 关闭页面laoding
          details.loadingObj.submitLoadingBtn = false;
        }
      }, 500);
    } else {
      console.log('error submit!');
      return false;
    }
  });
};

/** 重复开单 */
const handleRepetition = () => {
  details.popUpShow.titleVisited = false;
  resetForm(ruleFormRef.value);
};

/** 转译始发地和目的地
 * @param {Array} 循环数组
 * @param {String} province 省
 * @param {String} city 市
 * @param {String} region 区
 */
const handleTranslation = (province, city, region) => {
  let name = [];

  for (let i = 0; i < details.regionOptione.length; i++) {
    const value = details.regionOptione[i];

    if (value.value !== province + '') continue;
    name.push(value.value);

    if (!value.children || value.children.length === 0) return name;

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

      if (element.value !== city + '') continue;
      name.push(element.value);

      if (!element.children || element.children.length === 0) return name;

      for (let j = 0; j < element.children.length; j++) {
        const item = element.children[j];

        if (item.value === region + '') {
          name.push(item.value);
          break;
        }
      }
      break;
    }
    break;
  }

  return name;
};

/** 干线价格赋值 */
const handleAssignmentItemPriceTrunkline = (value, trunkLine, template, chargeType) => {
  const { pieceCategory, cubeCategory, weightCategory } = trunkLine;

  const _obj = {
    /** 件 */
    1: pieceCategory,
    /** 方 */
    2: cubeCategory,
    /** 公斤 */
    3: weightCategory,
  };

  // 是否区分品类
  if (template.trunklineIsByCategory) {
    // 品类是否存在id
    if (!value.goodsId) {
      value.price = 0;
      value.freightPrice = 0;
      value.systemChargeType = 1;
    } else if (chargeType === undefined) {
      let _item: any = {};
      // 件
      if (getObjType(pieceCategory) === 'array') {
        for (let j = 0; j < pieceCategory.length; j++) {
          const item = pieceCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          _item.chargeType = 1;
          break;
        }
      }

      // 方
      if (getObjType(cubeCategory) === 'array' && !_item.chargeType) {
        for (let j = 0; j < cubeCategory.length; j++) {
          const item = cubeCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          _item.chargeType = 2;
          break;
        }
      }

      // 重量
      if (getObjType(weightCategory) === 'array' && !_item.chargeType) {
        for (let j = 0; j < weightCategory.length; j++) {
          const item = weightCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          _item.chargeType = 3;
          break;
        }
      }

      if (!_item.chargeType) {
        value.price = 0;
        value.freightPrice = 0;
        value.systemChargeType = 1;
      } else {
        value.chargeType = _item.chargeType;
        value.systemChargeType = _item.chargeType;
        value.price = _item.price;
        value.freightPrice = _item.price || 0;
      }
    } else {
      console.log('123 :>> ', 123);
      // 定义计价方式 -- 不改变系统值

      const _arr = _obj[chargeType];
      value.systemChargeType = chargeType;
      let _item: any = {};

      if (getObjType(_arr) === 'array') {
        for (let j = 0; j < _arr.length; j++) {
          const item = _arr[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;
          break;
        }
      }

      value.price = _item.price || 0;
    }
  } else {
    // 不区分品类
    const _arr = _obj[value.chargeType];
    const _price = getObjType(_arr) === 'array' && _arr.length > 0 ? _arr[0].price || 0 : 0;

    value.price = _price;
    value.freightPrice = _price;
    value.systemChargeType = value.chargeType;
  }
};

/** 金牌 -- 干线特殊处理 */
const handleSpecialBrandPrice = (value, trunkLine, template, isInit) => {
  if (!isDisabled.value) return;

  // 总件数小于15件 && 总方数小于0.8 && 总方数 / 总件数小于0.11 则按件计费, 否则以按方计费
  const { totalCount, totalVolume } = details.totalObj;

  if (totalCount < 15 && totalVolume < 0.8 && totalVolume / (totalCount || 1) < 0.11) {
    if (value.chargeType === 1 && !isInit) return;

    value.chargeType = 1;
    value.systemChargeType = 1;

    // value.price = 5;

    if (getObjType(trunkLine) !== 'object' || getObjType(template) !== 'object') {
      value.freightPrice = 0;
      return (value.price = 0);
    }

    const { pieceCategory } = trunkLine;

    value.price = 5;
    value.freightPrice = 5;

    // 是否区分品类
    if (template.trunklineIsByCategory) {
      // 品类是否存在id
      if (!value.goodsId) {
        value.freightPrice = 0;
        value.price = 0;
      } else {
        let _item: any = {};
        // 件
        if (getObjType(pieceCategory) === 'array') {
          for (let j = 0; j < pieceCategory.length; j++) {
            const item = pieceCategory[j];

            if (item.categoryId !== value.goodsId) continue;
            _item = item;

            break;
          }
        }

        value.price = _item.price || 0;
        value.freightPrice = _item.price || 0;
      }
    } else {
      // 不区分品类
      const _price =
        getObjType(pieceCategory) === 'array' && pieceCategory.length > 0
          ? pieceCategory[0].price || 0
          : 0;
      // 不区分品类
      value.price = _price;
      value.freightPrice = _price;
    }
  } else {
    if (value.chargeType === 2 && !isInit) return;

    value.chargeType = 2;
    value.systemChargeType = 2;

    const { cubeCategory } = trunkLine;

    // 是否区分品类
    if (template.trunklineIsByCategory) {
      // 品类是否存在id
      if (!value.goodsId) {
        value.freightPrice = 0;
        value.price = 0;
      } else {
        let _item: any = {};

        // 方
        if (getObjType(cubeCategory) === 'array') {
          for (let j = 0; j < cubeCategory.length; j++) {
            const item = cubeCategory[j];

            if (item.categoryId !== value.goodsId) continue;
            _item = item;
            break;
          }
        }

        value.price = _item.price || 0;
        value.freightPrice = _item.price || 0;
      }
    } else {
      // 不区分品类
      const _price =
        getObjType(cubeCategory) === 'array' && cubeCategory.length > 0
          ? cubeCategory[0].price || 0
          : 0;

      // 不区分品类
      value.price = _price;

      value.freightPrice = _price;
    }
  }

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

/** 提货价格赋值 */
const handleAssignmentItemPricePickUp = (value, pickup, template) => {
  const { pieceCategory, cubeCategory, weightCategory } = pickup;

  const _obj = {
    /** 件 */
    1: pieceCategory,
    /** 方 */
    2: cubeCategory,
    /** 公斤 */
    3: weightCategory,
  };

  // 是否区分品类
  if (template.pickupIsByCategory) {
    // 品类是否存在id
    if (!value.goodsId) value.pickupPrice = 0;
    else {
      let _item: any = {};
      for (const key in _obj) {
        if (_item.chargeType) break;
        const _arr = _obj[key];

        if (getObjType(_arr) === 'array') {
          for (let j = 0; j < _arr.length; j++) {
            const item = _arr[j];

            if (item.categoryId !== value.goodsId) continue;
            _item = { ...item };

            _item.chargeType = key;
            break;
          }
        }
      }

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

      // 赋值
      value.systemPickupChargeType = _item.chargeType || 0;
      value.pickupPrice = _item.price || 0;
    }
  } else {
    // 不区分品类 -- 暂时默认为按件
    const _arr = _obj[1];

    value.pickupPrice = getObjType(_arr) === 'array' && _arr.length > 0 ? _arr[0].price || 0 : 0;

    value.systemPickupChargeType = 1;
  }
};

/** 配送价格赋值 */
const handleAssignmentItemPriceDispatch = (value, dispatch, template) => {
  const { pieceCategory, cubeCategory, weightCategory } = dispatch;

  const _obj = {
    /** 件 */
    1: pieceCategory,
    /** 方 */
    2: cubeCategory,
    /** 公斤 */
    3: weightCategory,
  };

  // 是否区分品类
  if (template.dispatchIsByCategory) {
    // 品类是否存在id
    if (!value.goodsId) value.deliveryPrice = 0;
    else {
      let _item: any = {};
      for (const key in _obj) {
        if (_item.chargeType) break;
        const _arr = _obj[key];

        if (getObjType(_arr) === 'array') {
          for (let j = 0; j < _arr.length; j++) {
            const item = _arr[j];

            if (item.categoryId !== value.goodsId) continue;
            _item = { ...item };

            _item.chargeType = key;
            break;
          }
        }
      }

      // 赋值
      value.systemDeliveryChargeType = _item.chargeType || 1;
      value.deliveryPrice = _item.price || 0;
    }
  } else {
    // 不区分品类 -- 暂时默认为按件
    const _arr = _obj[1];

    value.deliveryPrice = getObjType(_arr) === 'array' && _arr.length > 0 ? _arr[0].price || 0 : 0;

    value.systemDeliveryChargeType = 1;
  }
};

/** 仓储管理价格赋值 */
const handleAssignmentItemPriceWarehouseManagementPrice = (value, warehouse, template) => {
  if (!template || !template.warehouseIsAddFee || !template.warehouseIsManageFee) {
    value.warehouseManagementPrice = 0;
    value.warehouseManagementType = 1;
    return;
  }

  value.warehouseManagementType = Number(template.warehousePricingType);

  const { additionalCategory } = warehouse;

  if (template.warehouseIsCategorySubjoin) {
    // 品类是否存在id
    if (!value.goodsId) value.warehouseManagementPrice = 0;
    else {
      let _item: any = {};

      if (getObjType(additionalCategory) === 'array') {
        for (let j = 0; j < additionalCategory.length; j++) {
          const item = additionalCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          value.warehouseManagementPrice = _item.warehouseManagementPrice;

          return;
        }
      }

      // 赋值
      value.warehouseManagementPrice = 0;
    }
  } else {
    // 不区分品类 -- 暂时默认为按件
    value.warehouseManagementPrice =
      getObjType(additionalCategory) === 'array' && additionalCategory.length > 0
        ? additionalCategory[0].warehouseManagementPrice || 0
        : 0;
  }
};

/** 仓储管理价格赋值 */
const handleAssignmentItemPriceWarehouseHandingPrice = (value, warehouse, template) => {
  if (!template || !template.warehouseIsAddFee || !template.warehouseIsManageFee) {
    value.warehouseHandlingPrice = 0;
    value.warehouseHandlingType = 1;
    return;
  }

  value.warehouseHandlingType = Number(template.warehousePricingType);

  const { additionalCategory } = warehouse;

  if (template.warehouseIsCategorySubjoin) {
    // 品类是否存在id
    if (!value.goodsId) value.warehouseHandlingPrice = 0;
    else {
      let _item: any = {};

      if (getObjType(additionalCategory) === 'array') {
        for (let j = 0; j < additionalCategory.length; j++) {
          const item = additionalCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          value.warehouseHandlingPrice = _item.operatePrice;

          return;
        }
      }

      // 赋值
      value.warehouseHandlingPrice = 0;
    }
  } else {
    // 不区分品类 -- 暂时默认为按件
    value.warehouseHandlingPrice =
      getObjType(additionalCategory) === 'array' && additionalCategory.length > 0
        ? additionalCategory[0].operatePrice || 0
        : 0;
  }
};

/** 仓储管理价格赋值 */
const handleAssignmentItemPriceWarehouseSortingPrice = (value, warehouse, template) => {
  if (!template || !template.warehouseIsAddFee || !template.warehouseIsManageFee) {
    value.warehouseSortingPrice = 0;
    value.warehouseSortingType = 1;
    return;
  }

  value.warehouseSortingType = Number(template.warehousePricingType);

  const { additionalCategory } = warehouse;

  if (template.warehouseIsCategorySubjoin) {
    // 品类是否存在id
    if (!value.goodsId) value.warehouseSortingPrice = 0;
    else {
      let _item: any = {};

      if (getObjType(additionalCategory) === 'array') {
        for (let j = 0; j < additionalCategory.length; j++) {
          const item = additionalCategory[j];

          if (item.categoryId !== value.goodsId) continue;
          _item = item;

          value.warehouseSortingPrice = _item.warehouseSortPrice;

          return;
        }
      }

      // 赋值
      value.warehouseSortingPrice = 0;
    }
  } else {
    // 不区分品类 -- 暂时默认为按件
    value.warehouseSortingPrice =
      getObjType(additionalCategory) === 'array' && additionalCategory.length > 0
        ? additionalCategory[0].warehouseSortPrice || 0
        : 0;
  }
};

/** 价格赋值
 * isOnload 是否为初始化价格赋值, 初始化不赋值干线单价以及计算价格
 */
const handleAssignmentItemPrice = (value, isOnload = false, chargeType?: number | undefined) => {
  // 处理品类费用
  const { pickup, template, trunkLine, warehouse, dispatch } = details.priceTemplate;

  // 干线
  if (!isOnload) {
    if (trunkLine && template) {
      // 如果品牌为金牌, 切模板选择为特殊计费则特殊处理
      if (isDisabled.value && !chargeType)
        handleSpecialBrandPrice(value, trunkLine, template, true);
      else handleAssignmentItemPriceTrunkline(value, trunkLine, template, chargeType);

      // 是否为区分品类
    } else {
      value.freightPrice = 0;
      value.price = 0;
    }
  }

  // 提货
  if (pickup && template) {
    handleAssignmentItemPricePickUp(value, pickup, template);
  } else value.pickupPrice = 0;

  // 配送
  if (dispatch && template) handleAssignmentItemPriceDispatch(value, dispatch, template);
  else value.deliveryPrice = 0;

  console.log('warehouse :>> ', warehouse);
  // 仓库
  if (warehouse && template) {
    // 仓储管理费
    handleAssignmentItemPriceWarehouseManagementPrice(value, warehouse, template);
    // 仓储操作费
    handleAssignmentItemPriceWarehouseHandingPrice(value, warehouse, template);
    // 仓储分拣费
    handleAssignmentItemPriceWarehouseSortingPrice(value, warehouse, template);
  } else {
    value.warehouseManagementPrice = 0;
    value.warehouseHandlingPrice = 0;
    value.warehouseSortingPrice = 0;
  }

  // 计算每行价格
  if (!isOnload) handleComputed(value, isOnload, chargeType);
};

/** 获取价格
 * isOnload -- 是否是初始化获取价格, 初始化不赋值干线单价和计算价格
 */
const handleFindPrice = async (isOnload = false) => {
  try {
    if (!details.query.brandId || !details.query.consigneeId) return;
    let startArea = [];
    let endArea = [];

    details.query.departure && (startArea = handleTranslation(...details.query.departure));
    details.query.destination && (endArea = handleTranslation(...details.query.destination));

    const submitData = {
      // 品牌
      brandId: details.query.brandId,
      // 收货方
      clientId: details.query.consigneeId,
      // 发货方
      sendOrgId: details.query.shipperId,
      // 发站
      startProvinceId: startArea[0],
      startCityId: startArea[1],
      startCountyId: startArea[2],
      // 到站
      endProvinceId: endArea[0],
      endCityId: endArea[1],
      endCountyId: endArea[2],
    };

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

    const res = await postFindArrPrice(submitData);
    const { code, data } = res.data;

    if (code !== 200) return;

    details.priceTemplate = data || {};

    // 赋值
    for (let i = 0; i < details.goodsList.length; i++) {
      handleAssignmentItemPrice(details.goodsList[i], isOnload);
    }
  } catch (error) {
    console.log('error :>> ', error);
  }
};

/** 选择货物 */
const handleChooseGoods = (item, val) => {
  // if (item.id)
  let message = '';
  for (let i = 0; i < details.goodsList.length; i++) {
    const value = details.goodsList[i];

    if (value.goodsId === val.goodsId) {
      message = '该货物已添加';
      break;
    }
  }

  if (message) {
    // item.goodsName = '';
    return ElMessage.warning(message);
  }

  item.goodsName = val.goodsName;
  item.goodsId = val.goodsId;
  item.confirmCostCategoryId = item.goodsId;
  item.confirmCostCategoryName = item.goodsName;
  item.confirmIncomeCategoryId = item.goodsId;
  item.confirmIncomeCategoryName = item.goodsName;
  handleAssignmentItemPrice(item);
  handleCloseSelcet();
};

/** 改单提交 */
const handleSubmitCause = () => {
  causeFormRef.value.validate(async valid => {
    if (!valid) return;

    const submitData = { ...details.submitData, ...details.causeForm };
    for (let i = 0; i < details.query.editWaybillReasonTypeList.length; i++) {
      const value = details.query.editWaybillReasonTypeList[i];

      if (value.dictKey !== details.causeForm.editResonCode) continue;

      submitData.editReson = value.dictValue;
      break;
    }

    try {
      details.loadingObj.submitLoadingBtn = true;
      details.popUpShow.causeVisited = false;

      const res = await postUpdateWaybill(submitData);
      const { code, msg } = res.data;
      if (code !== 200) return;
      if (msg) ElMessage.success(msg);

      back();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.submitLoadingBtn = false;
    }
  });
};

/** 打印 */
const handlePrint = async () => {
  try {
    details.loadingObj.pageLoading = true;

    const res = await postPrintBatch({
      ids: details.waybillId,
      tempId: 16,
    });

    const { code, data } = res.data;

    if (code !== 200 || !data || data.length === 0) return;

    let _html = '';

    if (getObjType(data) !== 'object') return;

    for (const key in data) {
      const element = data[key];

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

        let template = value.templateHtml;

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

        template = template.replace('第n页', `第${i + 1}页`);
        template = template.replace('共n页', `共${element.length}页`);
        // template = template.replaceAll('0.00', ``);

        _html += JSON.parse(JSON.stringify(template));
      }
    }

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

    details.html = _html;

    details.popUpShow.WaybillPrintTemplate = true;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

watch(
  () => $route.query,
  () => {
    if ($route.path !== '/waybill/CreateZeroOrder') return;
    const { id } = $route.query;
    console.log('id :>> ', id);
    let _id = !id ? '' : id;

    if (_id === details.pageId) return;
    details.pageId = _id;
    details.goodsList = [
      {
        /** 货物名称  */
        goodsName: '',
        /** 品类Id */
        goodsId: '',
        /** 货物品类 */
        waybillDetailList: '',
        /** 计费方式 */
        chargeType: 1,
        /** 系统维护 -- 干线计价方式 */
        systemChargeType: 1,
        /** 系统维护 -- 配送计价方式 */
        systemDeliveryChargeType: 1,
        /** 系统维护 -- 提货计价方式 */
        systemPickupChargeType: 1,
        /** 系统维护 -- 仓库计价方式 */
        systemWarehouseChargeType: 1,
        /** 件数 */
        num: 0,
        /** 重量(kg) */
        weight: 0,
        /** 体积(方) */
        volume: 0,
        /** 单价 */
        price: 0,
        /** 系统维护 -- 运费单价 */
        freightPrice: 0,
        /** 系统维护 -- 配送单价 */
        deliveryPrice: 0,
        /** 系统维护 -- 提货单价 */
        pickupPrice: 0,
        /** 运费小计 */
        subtotalFreight: 0,
        goodsListOptions: [],
      },
    ];
    initPageInfo();
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
$borderColor: var(--el-color-primary);
$borderType: 1px solid $borderColor;

.table_form {
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    height: 100% !important;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
    border-bottom: 1px solid $borderColor;
    border-radius: 0;
  }
}
:deep(.table_form .el-form-item) {
  flex: 1 !important;
  margin: 0 !important;
}

.form_top {
  margin-bottom: 10px;
}

.border-top {
  border-top: $borderType;
}

.table-row {
  width: 100%;
  display: flex;
  // border-top: 1px dashed  $borderColor;
  border-left: $borderType;
  border-bottom: none;
  box-sizing: border-box;

  .title {
    width: fit-content;
    flex: none;
    padding: 0 20px;
    font-size: 0.9rem;
    background: var(--el-color-primary);
    color: #fff;
  }

  .flex-a {
    display: flex;
    width: 100%;
    justify-content: space-around;
  }

  &:first-child {
    display: block;
    border-top: $borderType;
    border-left: $borderType;

    > div {
      width: 100%;
      border: none;
    }
  }

  &:last-child {
    display: block;
    border-bottom: $borderType;
    border-right: $borderType;
    box-sizing: border-box;

    > div {
      width: 100%;
      border: none;
    }
  }

  > div {
    flex: 1;
    padding: 5px;
    border-bottom: $borderType;
    border-right: $borderType;
    display: inline-flex;
    box-sizing: border-box;
  }
}

.border-left {
  border-left: $borderType;
}

.table-row-title {
  background: #f5f7fa;
  margin-right: 10px;
  padding: 10px;

  & + div {
    flex: 1;

    :deep(.el-form-item) {
      flex: 1;
      margin-right: 10px;
    }

    :deep(.el-row) {
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.table-row-title-item {
  display: flex;
  align-items: center;
  font-size: 14px;

  &::before {
    content: '';
    display: block;
    width: 2px;
    height: 25px;
    background-color: var(--el-color-primary);
    margin-right: 10px;
  }
}

: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;
}

.table_row_number {
  > div {
    flex-grow: 1;
    justify-content: center;
  }
}

.table_row_total {
  line-height: 32px;
  text-align: center;
  background: #efefef;
}

.flex-c {
  display: flex;
  align-items: center;
}

:deep(.el-select.m-2) {
  width: 100%;
}

:deep(.el-radio) {
  margin: 0;
}

:deep(.el-form-item__error) {
  z-index: 99;
}

.table-row-title-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

// 底部
.footer {
  height: 80px;
}

// 提交按钮容器
.submitDataContainer {
  width: 80%;
  position: fixed;
  bottom: 20px;
  z-index: 999;
  text-align: center;
}

.w100 {
  width: 100%;
}

.mt15 {
  margin-top: 15px;
}

.red {
  color: var(--token-simulation-red-base-62);
}

:deep(.el-divider__text.is-center) {
  font-size: 28px;
}

:deep(.el-form-item__label) {
  color: var(--el-color-primary);
  font-weight: bold;
}

.fwb {
  display: flex;
  align-items: center;
  font-weight: bold;
  color: var(--el-color-danger) !important;
  position: relative;

  &::before {
    content: '';
    margin-right: 10px;
    display: block;
    width: 2px;
    height: 1rem;
    background: #f00;
  }
}

.mt20 {
  margin-top: 20px;
}

.goodsNameRow {
  background: #fff;
  transition: all 0.3s;
  padding: 10px 0;

  &:hover {
    background: #f5f7fa;
  }
}

.is-error {
  :deep(.el-input__wrapper) {
    border-color: #f00 !important;
  }

  :deep(.el-input__inner) {
    color: #f00 !important;
  }
}

.mr10 {
  margin-right: 10px;
}
</style>
