<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">
              <div><el-input v-model.trim="query.waybillNo" placeholder="运单号" clearable /></div>
            </el-form-item>

            <el-form-item class="mt10" label="品牌: " prop="waybillNo" label-width="80px">
              <el-select
                class="w100"
                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" type="datetime" placeholder="创建时间" />
          </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="destinationWarehouseName">
            <el-select
              class="w100"
              v-model="query.destinationWarehouseId"
              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="handleChooseShipper"
                      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="handleChooseShipper"
                      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);
                        }
                      "
                      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);
                        }
                      "
                      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();
                }
              "
              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();
                }
              "
            >
              <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.pickupVehicleType"
              filterable
              clearable
              placeholder="请选择车型"
              @change="
                () => {
                  details.query.pickupFee = 0;
                  handlePrice();
                }
              "
            >
              <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();
                }
              "
              :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.trunklineVehicleType"
              filterable
              clearable
              placeholder="请选择车型"
              @change="
                () => {
                  details.query.totalFreight = 0;
                  handlePrice();
                }
              "
            >
              <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">
            <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="handleComputed(item)"
                style="display: flex"
                :disabled="isDisabled"
              >
                <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"
              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
              :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
              :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
              :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
              :value-on-clear="0"
              :controls="false"
              v-model="item.price"
              :min="0"
              :precision="2"
              :step="0.1"
              @change="handleComputed(item)"
            />
          </el-form-item>

          <el-form-item label="运费小计:" label-width="fit-content" class="el-times">
            <el-input-number
              :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"></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
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.totalFreight"
                        :value-on-clear="0"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="送货费:">
                      <el-input-number
                        :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
                        :value-on-clear="0"
                        :disabled="!query.isPickUp"
                        :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
                        :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
                        :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
                        :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
                        :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
                        :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
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.claimingValue"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="回扣:">
                      <el-input-number
                        :value-on-clear="0"
                        :controls="false"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.rebate"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>

                  <el-row>
                    <el-form-item label="安装费:">
                      <el-input-number
                        :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
                      :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
                      :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
                      :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
                      :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
                        :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
              :value-on-clear="0"
              :controls="false"
              v-model="query.thirdOperationFee"
              :precision="0"
              :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
              :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"
      :visible.sync="details.popUpShow.titleVisited"
      width="30%"
      v-model="details.popUpShow.titleVisited"
    >
      <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" @click="handlePrint">打 印</el-button> -->
      </div>
    </el-dialog>

    <!-- 改单原因 -->
    <el-dialog
      title="修改信息"
      :center="true"
      :align-center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="details.popUpShow.causeVisited"
      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.remark" 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>
  </div>
</template>

<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 { 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 } from '@/utils/util.js';

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

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

// 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: '',
    /** 货物号 */
    goodsCode: '',
    /** 发货单位id */
    shipperId: '',
    /** 发货单位 */
    shipper: '',
    /** 发货人 */
    shipperName: '',
    /** 发货人电话 */
    shipperMobile: '',
    /** 发货人地址 */
    shipperAddress: '',
    /** 收货单位id */
    consigneeId: '',
    /** 收货单位 */
    consignee: '',
    /** 收货人 */
    consigneeName: '',
    /** 收货人电话 */
    consigneeMobile: '',
    /** 收货人地址 */
    consigneeAddress: '',
    /** 货物品类 */
    waybillDetailList: [],
    /** 送货费 */
    deliveryFee: 0,
    /** 提货费 */
    pickupFee: 0,
    /** 仓库管理费 */
    warehouseManagementFee: 0,
    /** 仓储费 */
    storageFee: 0,
    /** 装卸费 */
    handlingFee: 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,
    /** 提货整车车型 */
    pickupVehicleType: '',
    /** 是否整车 -- 干线 */
    trunklineCompleteOrNot: 0,
    /** 干线整车车型 */
    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,
      /** 件数 */
      num: 0,
      /** 重量(kg) */
      weight: 0,
      /** 体积(方) */
      volume: 0,
      /** 单价 */
      price: 0,
      /** 运费小计 */
      subtotalFreight: 0,
      /** 货物名称list */
      goodsListOptions: [],
    },
  ],
  /** 仓库数组 */
  options: [],
  /** 品牌数组 */
  brandOptions: [],
  /** 到站地区数组 */
  regionOptione: [],
  /** 收货方 -- 收货单位 */
  consigneeOptions: [],
  /** 收货方 -- 收货人 */
  consigneeNameOptions: [],
  /** 收货方 -- 收货电话 */
  consigneeMobileOptions: [],
  /** 发货方 -- 收货单位 */
  shipperOptions: [],
  /** 收货方 -- 收货人 */
  shipperNameOptions: [],
  /** 收货方 -- 收货电话 */
  shipperMobileOptions: [],
  /** 必填 */
  rules: {
    /** 发站仓名称 */
    departureWarehouseName: [
      {
        required: true,
        message: '请填写或选择发站仓',
        trigger: ['change', 'blur'],
      },
    ],
    /** 发站 */
    departure: [
      {
        required: true,
        message: '请填写或选择发站地',
        trigger: ['change', 'blur'],
      },
    ],
    /** 到站 */
    destination: [
      {
        required: true,
        message: '请填写或选择到站地',
        trigger: ['change', 'blur'],
      },
    ],
    /** 目的站名称 */
    destinationWarehouseName: [
      {
        required: true,
        message: '请选择目的仓',
        trigger: ['change', 'blur'],
      },
    ],
    /** 发货单位 */
    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,
    /** 改单原因 */
    titleVisited: 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,
  },
  /** 列表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: [],
});

/** 是否禁用 */
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.otherFee || 0)
    .next('+', details.query.insuranceFee || 0)
    .next('+', details.query.rebate || 0)
    .next('+', details.query.installFee || 0)
    .next('+', details.query.claimingValue || 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(() => {});

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

  details.vehicleTypeArr = data || [];
});

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 });
      const { code, data } = res.data;
      if (code !== 200) return;

      details.query = { ...data, ...data.warehouseWaybill };
      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.createTime;
      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 = '1';
      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');
      }

      // 初始化goodsList
      if (data.warehouseWaybill.detailList.length === 0)
        details.goodsList = [
          {
            index: 0,
            /** 货物名称  */
            goodsName: '',
            /** 品类Id */
            goodsId: '',
            /** 计费方式 */
            chargeType: 1,
            /** 件数 */
            num: 0,
            /** 重量(kg) */
            weight: 0,
            /** 体积(方) */
            volume: 0,
            /** 单价 */
            price: 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.subtotalFreight = Number(val.subtotalFreight);

          val.goodsName = val.productName;

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

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

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

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

      const { arrPrice } = element;
      if (arrPrice && arrPrice.length > 0) {
        // 价格赋值
        for (let i = 0; i < details.priceArr.length; i++) {
          const value = details.priceArr[i];
          element[value.key] = 0;

          for (let index = 0; index < arrPrice.length; index++) {
            const item = arrPrice[index];

            if (item.itemName === value.name)
              element[value.key] = isNumber(item.cost) ? Number(item.cost) : 0;
          }
        }
      }

      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');

    handleFindPrice(false);
  } 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.info.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 = data.destinationArray || [];
    details.query.departure = 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 {
    return null;
  }
};

/** 新增 */
const handleAdd = () => {
  const _flag = details.goodsList.every(val => {
    // 件数和名称必填
    if (val.goodsName === '' || !val.num) {
      ElMessage({
        message: '请填写完整件数和名称',
        type: 'warning',
      });
      return false;
    }
    if (val.chargeType === 2 && val.volume === 0) {
      ElMessage({
        message: '请填写方数',
        type: 'warning',
      });
      return false;
    }
    if (val.chargeType === 3 && val.weight === 0) {
      ElMessage({
        message: '请填写重量',
        type: 'warning',
      });
      return false;
    }
    return true;
  });

  if (!_flag) return;

  details.goodsList.push({
    /** 货物名称  */
    goodsName: '',
    /** 品类Id */
    goodsId: '',
    /** 货物品类 */
    waybillDetailList: '',
    /** 计费方式 */
    chargeType: 1,
    /** 件数 */
    num: 0,
    /** 重量(kg) */
    weight: 0,
    /** 体积(方) */
    volume: 0,
    /** 单价 */
    price: 0,
    /** 运费小计 */
    subtotalFreight: 0,
    goodsListOptions: [],
  });
};

/** 移除 */
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 => {
  details.query.destinationWarehouseName = details.options.find(
    value => value.warehouseId === val
  ).warehouseName;
};

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

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

/** 计算行合计 */
const handleComputed = (row: any) => {
  const { template, trunkLine } = details.priceTemplate;

  if (Boolean(isDisabled.value && template && trunkLine))
    handleSpecialBrandPrice(row, trunkLine, template);

  details.query.goodsCode = '-' + details.totalObj.totalCount;
  if (row.chargeType === 1) row.subtotalFreight = computeNumber(row.num, '*', row.price).result;
  else if (row.chargeType === 2)
    row.subtotalFreight = computeNumber(row.volume, '*', row.price).result;
  else if (row.chargeType === 3)
    row.subtotalFreight = computeNumber(row.weight, '*', row.price).result;

  row.totalPickupPrice = computeNumber(row.num, '*', row.pickupPrice || 0).result;

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

  handlePrice();
};

/** 查询客户信息 */
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;

  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;

  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 = {};

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

      if (Number(value.vehicleType) !== Number(details.query.pickupVehicleType)) 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].totalPickupPrice || 0).result;
    }

    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.trunklineVehicleType)) 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).result;
    }

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

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

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

        // 重量
        case 4:
          details.query.totalFreight =
            template.minCost > details.totalObj.totalFreight
              ? _total + (template.additionalCost || 0)
              : _total;
          break;

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

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

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

  /** 处理提货费用 */
  handlePickUpPrice(pickup, template);
  /** 处理干线费用 */
  handleTrunkLinePrice(trunkLine, template);
  /** 处理配送费 */
  handleDispatchPrice(dispatch, template);
};

/** 重置值 */
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 = [
    {
      index: 0,
      /** 货物名称  */
      goodsName: '',
      /** 品类Id */
      goodsId: '',
      /** 计费方式 */
      chargeType: 1,
      /** 件数 */
      num: 0,
      /** 重量(kg) */
      weight: 0,
      /** 体积(方) */
      volume: 0,
      /** 单价 */
      price: 0,
      /** 运费小计 */
      subtotalFreight: 0,
      /** 货物名称list */
      goodsListOptions: [],
    },
  ];
  initPageInfo();
};

/** 提交 */
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      try {
        details.loadingObj.submitLoadingBtn = true;

        // 检测货物名称和件数是否正确填写
        const _flag = details.goodsList.every(val => {
          if (!val.goodsName || !isNumber(val.num) || val.num === 0) return false;
          return true;
        });

        if (!_flag) {
          return ElMessage({
            type: 'warning',
            message: '请填写正确的货物名称和件数',
          });
        }

        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 _findeLocation = details.regionOptione
          .find(val => val.value === destination[0])
          .children.find(val => val.value === destination[1]);

        let _item: any = {};
        if (destination.length === 2) {
          _item = _findeLocation;
        } else {
          _item = _findeLocation.children.find(val => val.value === destination[2]);
        }

        submitData.destination = _item.label;
        submitData.destinationCode = _item.value;

        // 筛选发站
        const _findeDeparture = details.regionOptione
          .find(val => val.value === departure[0])
          .children.find(val => val.value === departure[1]);

        let _itemDeparture: any = {};
        if (_findeDeparture.length === 2) {
          _itemDeparture = _findeDeparture;
        } else {
          _itemDeparture = _findeDeparture.children.find(val => val.value === destination[2]);
        }

        submitData.departure = _findeDeparture.label;
        submitData.departureCode = _findeDeparture.value;

        // 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;
          console.log('submitData :>> ', submitData);
          res = await postOpenOrderOpenZeroWaybill(submitData);

          const { code, msg } = res.data;
          if (code !== 200) return;
          ElMessage({
            message: msg,
            type: 'success',
          });
          // 开启提示框, 是否继续开单
          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);

          // 记录提交参数
          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 {
        // 关闭页面laoding
        details.loadingObj.submitLoadingBtn = false;
      }
    } 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) => {
  const { pieceCategory, cubeCategory, weightCategory } = trunkLine;

  // 是否区分品类
  if (template.trunklineIsByCategory) {
    // 品类是否存在id
    if (!value.goodsId) 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;

          _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;
      else {
        value.chargeType = _item.chargeType;
        value.price = _item.price;
      }
    }
  } else {
    // 不区分品类
    switch (value.chargeType) {
      // 件
      case 1:
        value.price =
          getObjType(pieceCategory) === 'array' && pieceCategory.length > 0
            ? pieceCategory[0].price || 0
            : 0;
        break;

      // 方
      case 2:
        value.price =
          getObjType(cubeCategory) === 'array' && cubeCategory.length > 0
            ? cubeCategory[0].price || 0
            : 0;
        break;

      // 公斤
      case 3:
        value.price =
          getObjType(weightCategory) === 'array' && weightCategory.length > 0
            ? weightCategory[0].price || 0
            : 0;
        break;

      default:
        break;
    }
  }
};

/** 金牌 -- 干线特殊处理 */
const handleSpecialBrandPrice = (value, trunkLine, template) => {
  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) {
    value.chargeType = 1;

    value.price = 5;
  } else {
    value.chargeType = 2;

    const { cubeCategory } = trunkLine;

    // 是否区分品类
    if (template.trunklineIsByCategory) {
      // 品类是否存在id
      if (!value.goodsId) 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;
      }
    } else {
      // 不区分品类
      value.price =
        getObjType(cubeCategory) === 'array' && cubeCategory.length > 0
          ? cubeCategory[0].price || 0
          : 0;
    }
  }

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

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

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

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

  // 提货
  if (pickup && template) {
    const { pieceCategory } = pickup;
    // 是否区分品类
    if (template.pickupIsByCategory) {
      // 品类是否存在id
      if (!value.goodsId) value.pickupPrice = 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;

            _item.chargeType = 1;
            break;
          }
        }

        value.pickupPrice = _item.chargeType ? _item.price : 0;
      }
    } else {
      value.pickupPrice =
        getObjType(pieceCategory) === 'array' && pieceCategory.length > 0
          ? pieceCategory[0].price || 0
          : 0;
    }
  } else value.pickupPrice = 0;

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

/** 获取价格
 * 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;
  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;
    }
  });
};

watch(
  () => $route.query,
  () => {
    if ($route.path !== '/waybill/CreateZeroOrder') return;
    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;
}

// 页面字体大小
.avue-crud {
  font-size: 12px !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>
