<template>
  <div>
    <basic-container>
      <el-divider style="font-size: 28px">货物托运单</el-divider>
      <el-form
        ref="ruleFormRef"
        :inline="true"
        :rules="details.rules"
        :model="query"
        class="el-fr-d"
        label-width="100px"
      >
        <!-- 顶部 -->
        <div class="flex-c-sb form_top">
          <div>
            <div class="flex-c-sb">
              <div class="flex-c-c">
                <el-icon color="#172e60"><User /></el-icon>
                品牌:
                <span class="red">{{ query.brand }}</span>
              </div>
              <div class="flex-c-c">
                <el-icon color="#172e60"><Van /></el-icon>
                车次号:
                <span class="red">{{ query.trainNumber }}</span>
              </div>
            </div>
            <div class="mt10">
              <el-form-item class="mt10" label="运单号: " prop="waybillNo" label-width="80px">
                <div><el-input v-model="query.waybillNo" placeholder="运单号" clearable /></div>
              </el-form-item>
            </div>
          </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">{{ query.openOrderUserName }}</span>
            </div>
            <el-date-picker
              v-model="query.openOrderDate"
              prefix-icon="Calendar"
              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="destination">
            <div class="w100">
              <el-cascader
                pleceholder="请选择到站地址"
                :options="details.regionOptione"
                style="width: 100%"
                v-model="query.destination"
                :props="{
                  checkStrictly: true,
                }"
                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="destinationWarehouseNameChange"
              :remote-method="remoteMethod"
              :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">
          <el-form-item label="订单自编号:" class="el-times">
            <el-input
              v-model="details.query.orderCode"
              type="textarea"
              placeholder="订单自编号"
              disabled
            ></el-input>
            <el-button class="mt10" type="primary" @click="handleChooseOrder" icon="Plus"
              >选取订单</el-button
            >
          </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">
                  <SelectBox
                    :input="handleFindClientInfo(query.shipper, 'shipper')"
                    v-model="query.shipper"
                    placeholder="发货单位"
                    ref="shipper"
                  >
                    <el-table
                      :data="details.shipperOptions"
                      style="width: 100%"
                      @row-click="handleChooseShipper"
                      :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
                    :input="handleFindClientInfo(query.shipper, 'shipper')"
                    v-model="query.shipperName"
                    placeholder="发货人"
                    ref="shipperName"
                  >
                    <el-table
                      :data="details.shipperOptions"
                      style="width: 100%"
                      @row-click="handleChooseShipper"
                      :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
                    :input="handleFindClientInfo(query.shipper, 'shipper')"
                    v-model="query.shipperMobile"
                    placeholder="联系电话"
                    ref="shipperMobile"
                  >
                    <el-table
                      :data="details.shipperOptions"
                      style="width: 100%"
                      @row-click="handleChooseShipper"
                      :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 v-model="query.shipperAddress" placeholder="发货地址"></el-input>
                </el-form-item>
              </el-row>
            </div>
          </div>
          <div>
            <div class="flex-c table-row-title">收货方</div>
            <div>
              <el-row>
                <el-form-item label="发货单位:" prop="consignee">
                  <SelectBox
                    :input="handleFindClientInfo(query.consignee, 'consignee')"
                    v-model="query.consignee"
                    placeholder="收货人"
                    ref="consignee"
                  >
                    <el-table
                      :data="details.consignerOptions"
                      style="width: 100%"
                      @row-click="handleChooseConsigner"
                      :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
                    :input="handleFindClientInfo(query.consignee, 'consignee')"
                    v-model="query.consigneeName"
                    placeholder="收货人"
                    ref="consigneeName"
                  >
                    <el-table
                      :data="details.consignerOptions"
                      style="width: 100%"
                      @row-click="handleChooseConsigner"
                      :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
                    :input="handleFindClientInfo(query.consignee, 'consignee')"
                    v-model="query.consigneeMobile"
                    placeholder="联系电话"
                    ref="consigneeMobile"
                  >
                    <el-table
                      :data="details.consignerOptions"
                      style="width: 100%"
                      @row-click="handleChooseConsigner"
                      :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 v-model="query.consigneeAddress" placeholder="发货地址"></el-input>
                </el-form-item>
              </el-row>
            </div>
          </div>
        </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"
              >
                <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 className="goodsName" v-model="item.goodsName" placeholder="货物名称">
              暂无数据
            </SelectBox>
          </el-form-item>

          <el-form-item label="件数:" label-width="fit-content" prop="num" class="el-times">
            <el-input-number
              v-model="item.num"
              controls-position="right"
              :min="0"
              :max="info.maxNum + item.num - details.totalObj.totalCount"
              :precision="0"
              :step="1"
              @change="handleComputed(item)"
            />
          </el-form-item>

          <el-form-item label="体积(方):" label-width="fit-content" class="el-times">
            <el-input-number
              v-model="item.volume"
              controls-position="right"
              :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
              v-model="item.weight"
              controls-position="right"
              :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
              v-model="item.price"
              controls-position="right"
              :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
              v-model="item.subtotalFreight"
              controls-position="right"
              :precision="2"
              :min="0"
              :step="0.1"
              :disabled="item.price > 0 || Number(item.price) !== Number(item.price)"
            />
          </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 }}(最大数: <span class="red">{{ info.maxNum }}</span
            >)
          </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: 60%; flex: none">
            <div style="flex: 1">
              <div class="table-row-title" style="margin-bottom: 10px">
                <div class="table-row-title-item">
                  合计费用
                  <span class="red">{{ totalCost }}</span>
                </div>
              </div>
              <div>
                <el-form label-width="fit-content">
                  <el-row>
                    <el-form-item label="运费:">
                      <el-input
                        controls-position="right"
                        v-model="details.totalObj.totalFreight"
                        disabled
                      ></el-input>
                    </el-form-item>

                    <el-form-item label="送货费:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.deliveryFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="提货费:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.pickupFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="仓库管理费:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.warehouseManagementFee"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="仓储费:">
                      <el-input-number
                        controls-position="right"
                        :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
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.handlingFee"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="其它费用:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.otherFee"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="保价费:">
                      <el-input-number
                        controls-position="right"
                        v-model="query.insuranceFee"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                      ></el-input-number>
                    </el-form-item>
                    <el-form-item label="申明价值:">
                      <el-input-number
                        controls-position="right"
                        v-model="query.claimingValue"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                      ></el-input-number>
                    </el-form-item>
                  </el-row>
                </el-form>
              </div>
            </div>
          </div>

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

                    <el-form-item label="付款方式:" prop="payWay">
                      <el-select v-model="query.payWay" class="m-2" placeholder="付款方式">
                        <el-option
                          v-for="item in query.payWayList"
                          :key="item.dictValue"
                          :label="item.dictValue"
                          :value="item.dictKey"
                        />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="现付:">
                      <el-input-number
                        controls-position="right"
                        :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="到付:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.daoPay"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="月结:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.yuePay"
                      ></el-input-number>
                    </el-form-item>

                    <el-form-item label="回付:">
                      <el-input-number
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :step="0.1"
                        v-model="query.huiPay"
                      ></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
              v-model="query.thirdOperationFee"
              controls-position="right"
              :precision="0"
              :step="0.1"
            />
          </el-form-item>

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

          <el-form-item label="紧急度:" prop="urgency" label-width="fit-content" class="el-times">
            <el-select v-model="query.urgency" class="m-2" placeholder="紧急度">
              <el-option
                v-for="item in query.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
              v-model="query.receiptNum"
              controls-position="right"
              :precision="0"
              :step="1"
              :min="0"
            />
          </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 query.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 query.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 type="primary" icon="Position" @click="handleSubmit(ruleFormRef)"
              >提交</el-button
            >
            <el-button type="primary" icon="Refresh" @click="handleRefresh">重置</el-button>
            <el-button type="primary" icon="Close" @click="back">关闭</el-button>
          </div>
        </div>
      </el-form>
    </basic-container>

    <!-- 选取订单 -->
    <el-dialog
      class="el-dialog-columnList"
      title="选取订单"
      :visible.sync="details.popUpShow.columnListVisited"
      width="80%"
      v-model="details.popUpShow.columnListVisited"
    >
      <!-- 列表模块 -->
      <tablecmt
        :columnList="details.columnList"
        :tableData="data"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @btnCheck="btnsc"
        @selectCheck="selectsc"
        @selection="selectionChange"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '操作'">
            <el-button type="text" @click="handleShowPackageOrderList(slotProps.scope)">
              包明细
            </el-button>
          </template>
        </template>
      </tablecmt>

      <!-- 分页模块 -->
      <el-pagination
        align="right"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page.pageNum"
        :page-sizes="[30, 50, 80, 120]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <!--    <el-button type="primary" @click="ddd">导 出</el-button>-->
        <el-button type="primary" @click="handleChoose">确 认</el-button>
        <el-button @click="details.popUpShow.columnListVisited = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, getCurrentInstance } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters, useStore } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  computeNumber,
  deepClone,
  isNumer,
  setNodeHeight,
  getWinHeight,
} from '@/utils/util';
import { columnList, packageListColumnList } from '@/option/waybill/TemporaryStorageList';
import { getopenOrderAdvancePageList } from '@/api/waybill/TemporaryStorageList';
import { getLazyTreeAll } from '@/api/base/region';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import {
  postOpenOrderFindClientInfo,
  getOpenOrderAdvanceToWaybillInfo,
  postOpenOrderOpenWaybill,
  getOpenOrderAdvanceFindWarehouseList,
} from '@/api/distribution/CreateOrder.js';

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

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

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

// 获取vuex
let useStores = useStore();

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,
    /** 申明价值 */
    claimingValue: 0,
    /** 支付方式 */
    payType: '',
    /** 付款方式 */
    payWay: '2',
    /** 现付 */
    xianPay: 0,
    /** 到付 */
    daoPay: 0,
    /** 月付 */
    yuePay: 0,
    /** 回付 */
    huiPay: 0,
    huilaiPay: 0,
    /** 三方操作费 */
    thirdOperationFee: 0,
    /** 送货方式 */
    deliveryWay: '1',
    /** 紧急度 */
    urgency: '1',
    /** 回单方式(多选) */
    receipt: '',
    /** 运输方式 */
    transportType: '',
    /** 开单人 */
    openOrderUserName: '',
    /** 回单数 */
    receiptNum: 0,
    /** 备注 */
    remark: '',
    /** 运单类型 */
    waybillType: 1,
  },
  /** 合计 */
  totalObj: {
    /** 总件数 */
    totalCount: computed(() => {
      return details.goodsList.reduce((curr, item) => {
        if (item.num) return curr + item.num;
        return curr;
      }, 0);
    }),
    /** 总重量 */
    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,
    },
  ],
  options: [],
  /** 到站地区数组 */
  regionOptione: [],
  /** 支付字典 */
  payOption: [
    {
      label: '现金',
      value: 1,
    },
    {
      label: '银行卡',
      value: 2,
    },
    {
      label: '微信',
      value: 3,
    },
    {
      label: '支付宝',
      value: 4,
    },
    {
      label: '支票',
      value: 5,
    },
    {
      label: '账本',
      value: 6,
    },
  ],
  /** 开单付款字典 */
  paymentOption: [
    {
      label: '现付',
      value: 1,
    },
    {
      label: '到付',
      value: 2,
    },
    {
      label: '月结',
      value: 3,
    },
    {
      label: '回付',
      value: 4,
    },
    {
      label: '内部结算',
      value: 5,
    },
    {
      label: '多笔付',
      value: 6,
    },
  ],
  /** 紧急度 */
  emergencyOption: [
    {
      label: '正常',
      value: 1,
    },
    {
      label: '急',
      value: 2,
    },
    {
      label: '特急',
      value: 3,
    },
    {
      label: '加急',
      value: 4,
    },
  ],
  /** 送货方式字典 */
  shippingOption: [
    {
      label: '自提',
      value: 1,
    },
    {
      label: '送货',
      value: 2,
    },
    {
      label: '送货上门',
      value: 3,
    },
    {
      label: '送货上门(有电梯)',
      value: 4,
    },
    {
      label: '送货上门(无电梯)',
      value: 5,
    },
    {
      label: '送货卸货',
      value: 6,
    },
    {
      label: '送货安装',
      value: 7,
    },
  ],
  /**  开单回单方式 */
  receiptOption: [
    {
      label: '签回单',
      value: 1,
    },
    {
      label: '打收条',
      value: 2,
    },
    {
      label: '签信封',
      value: 3,
    },
    {
      label: '签回单盖章',
      value: 4,
    },
    {
      label: '1份回单',
      value: 5,
    },
    {
      label: '2份回单',
      value: 6,
    },
    {
      label: '3份回单',
      value: 7,
    },
    {
      label: '4份回单',
      value: 8,
    },
    {
      label: '5份回单',
      value: 9,
    },
  ],
  /** 运输方式 */
  transportationOption: [
    {
      label: '公路快运',
      value: 1,
    },
    {
      label: '海运',
      value: 2,
    },
    {
      label: '卡车航班',
      value: 3,
    },
    {
      label: '空运',
      value: 4,
    },
    {
      label: '普通汽班',
      value: 5,
    },
    {
      label: '快递',
      value: 6,
    },
  ],
  /** 收货方 */
  consignerOptions: [],
  /** 发货方 */
  shipperOptions: [],
  /** 必填 */
  rules: {
    /** 发站仓名称 */
    departureWarehouseName: [
      {
        required: true,
        message: '请填写或选择发站仓',
        trigger: ['change', 'blur'],
      },
    ],
    /** 到站 */
    destination: [
      {
        required: true,
        message: '请填写或选择到站地',
        trigger: 'change',
      },
    ],
    /** 目的站名称 */
    destinationWarehouseName: [
      {
        required: true,
        message: '请选择目的仓',
        trigger: '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: 'blur',
      },
    ],
    /** 收货人电话 */
    consigneeMobile: [
      {
        required: true,
        message: '请选择或输入收货人电话',
        trigger: 'blur',
      },
    ],
    /** 付款方式 */
    payWay: [
      {
        required: true,
        message: '请选择付款方式',
        trigger: 'change',
      },
    ],
    /** 送货方式 */
    deliveryWay: [
      {
        required: true,
        message: '请选择送货方式',
        trigger: 'change',
      },
    ],
    /** 紧急度 */
    urgency: [
      {
        required: true,
        message: '请选择紧急度',
        trigger: 'change',
      },
    ],
  },
  /** 列表 */
  columnList,
  /** 列表数据 */
  data: [{}],
  /** 页面loading */
  loadingObj: {
    loading: false,
    /** 配载信息loading */
    stowageLoading: false,
    /** 收货方 */
    consignerLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 包明细 */
    columnListVisited: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  // 页面请求的问题
  form: {},
});

const info = ref<any>({});

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

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 totalCost = computed(() => {
  // let _num = 0;
  const _num = computeNumber(0, '+', details.totalObj.totalFreight)
    .next('+', details.query.deliveryFee)
    .next('+', details.query.pickupFee)
    .next('+', details.query.warehouseManagementFee)
    .next('+', details.query.storageFee)
    .next('+', details.query.handlingFee)
    .next('+', details.query.otherFee)
    .next('+', details.query.insuranceFee)
    .next('+', details.query.claimingValue).result;
  return _num;
});

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

onMounted(() => {});

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

/** 初始化获取暂存单转运单信息 */
const onLoad = async (idsArr = []) => {
  let ids = [];
  if (idsArr.length === 0) ids = JSON.parse($route.query.ids as any);
  else ids = idsArr;
  const res = await getOpenOrderAdvanceToWaybillInfo({ advanceIds: ids });
  const { code, data } = res.data;
  console.log('data :>> ', data);
  if (code !== 200) return;
  // 存储请求的数据
  info.value = deepClone(data);
  console.log('info.value :>> ', info.value === data);

  for (let key in data) {
    if (data[key]) details.query[key] = data[key];
  }

  details.goodsList = data.goodsList.map(val => {
    for (let valKey in val) {
      const _item = Number(val[valKey]);
      // 判断是否为数字并将字符串的数字转为数字
      if (isNumer(_item)) {
        val[valKey] = _item;
      }
    }
    // 计算运费小计
    handleComputed(val);

    // 计算件数最大值
    info.value.maxNum = 0;
    info.value.maxNum += val.num;
    console.log('val :>> ', val);
    return val;
  });
  if (data.defaultPayWay) {
    data.payWay = data.defaultPayWay;
  } else {
    details.query.payWay = data.payWayList.find(val => val.dictValue === '到付').dictKey || '2';
  }
  // instance.proxy.$forceUpdate();
};
onLoad();

/** 新增 */
const handleAdd = () => {
  if (info.value.maxNum <= details.totalObj.totalCount) {
    ElMessage({
      message: '件数已用完, 无法再新增',
      type: 'warning',
    });
    return;
  }

  const _flag = details.goodsList.every(val => {
    // 件数和名称必填
    if (val.goodsName === '' || !val.num) {
      ElMessage({
        message: '请填写完整件数和名称',
        type: 'warning',
      });
      return false;
    }
    if (val.chargeType === 2 && val.weight === 0) {
      ElMessage({
        message: '请填写重量',
        type: 'warning',
      });
      return false;
    }
    if (val.chargeType === 3 && val.price === 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,
  });
};

/** 请求订单数据 */
const initOrderList = async (params = {}) => {
  try {
    details.form.freezeStatus = '0';
    const res = await getopenOrderAdvancePageList(details.page, { ...details.form, ...params });
    // 获取暂存单列表
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    details.page.total = data.total;
  } catch (error) {
  } finally {
    return null;
  }
};

/** 开启订单列表 */
const handleChooseOrder = async () => {
  try {
    details.popUpShow.columnListVisited = true;
    // 开启列表loading动画
    details.loadingObj.loading = true;

    await initOrderList();

    nextTick(() => {
      const _node = document.querySelector('.el-dialog-columnList .maboxhi');
      setNodeHeight(_node, '600px');
    });

    // return res.data;
  } catch (error) {
  } finally {
    // 开启列表loading动画
    details.loadingObj.loading = false;
  }
};

/** 选择订单 */
const handleChoose = () => {
  try {
    if (details.selectionList.length === 0) {
      return ElMessage({
        type: 'warning',
        message: '请选择一条数据',
      });
    }

    const _dealerName = details.selectionList[0].dealerName;
    const _flag = details.selectionList.every(item => _dealerName === item.dealerName);

    if (!_flag) {
      return ElMessage({
        type: 'warning',
        message: '请选择统一商场开单',
      });
    }

    const ids = details.selectionList.map(val => val.id);
    // 请求页面数据
    onLoad(ids);
    details.popUpShow.columnListVisited = false;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
  }
};

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

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

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

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

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

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

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

/** 查看包明细 */
const handleShowPackageOrderList = ({ row }) => {
  $router.push({
    path: '/waybill/orderPackageListDetails?name=包明细',
    query: {
      id: row.id,
      name: `订单 -- ${row.orderCode} 包明细`,
    },
  });
};

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

/** 查询目的仓 */
let _ant1 = null;
const remoteMethod = val => {
  if (_ant1) clearTimeout(_ant1);
  _ant1 = setTimeout(async () => {
    if (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;
      }
    }
    clearTimeout(_ant1);
  }, 1000);
};

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

/** 计算行合计 */
const handleComputed = (row: any) => {
  // if (!row.price) return;
  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.subtotalFreight = 1;
};

let _ant = null;
/** 查询客户信息 */
const handleFindClientInfo = (value, type) => {
  if (_ant) clearTimeout(_ant);
  _ant = setTimeout(async () => {
    if (value) {
      try {
        details.loadingObj.consignerLoading = true;
        const res = await postOpenOrderFindClientInfo({ clientName: value });
        const { code, data } = res.data;
        if (code !== 200) return;
        if (type === 'consignee') {
          details.consignerOptions = data || [];
        } else {
          details.shipperOptions = data || [];
        }
      } catch (error) {
      } finally {
        details.loadingObj.consignerLoading = false;
      }
    }
    clearTimeout(_ant);
  }, 1000);
};

/** 客户选择 */
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;
  shipperNodeList.forEach(val => val.value.handleClose());
};

/** 收货客户选择 */
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;
  consigneeNodeList.forEach(val => val.value.handleClose());
};

/** 返回上一个页面 */
function back() {
  useStores.commit('DEL_TAG_CURRENT');
  $router.back('-1');
}

/** 重置数据 */
const handleRefresh = () => {
  for (let key in details.query) {
    const _value = details.query[key];
    const _type = Object.prototype.toString.call(_value);
    if (_type === '[object String]' || _type === '[object Undefined]' || _type === '[object Null]')
      details.query[key] = '';
    else if (_type === '[object Number]') {
      details.query[key] = 0;
    } else if (_type === '[object Array]') details.query[key] = [];
  }

  console.log('details.info :>> ', info.value.goodsList === details.goodsList);

  for (let key in info.value) {
    details.query[key] = info.value[key];
  }

  const _cloneGoodsList = deepClone(info.value.goodsList);

  details.goodsList = _cloneGoodsList.map(val => {
    handleComputed(val);
    return val;
  });
};

const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      // 检测货物名称和件数是否正确填写
      const _flag = details.goodsList.every(val => {
        console.log('val :>> ', val);
        if (!val.goodsName || !isNumer(val.num) || val.num === 0) return false;
        return true;
      });

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

      console.log('submit!');
      const submitData = {
        ...details.query,
        waybillDetailList: details.goodsList,
        advanceIds: info.value.advanceIds,
        ...details.totalObj,
        huilaiPay: 1,
      };

      const { destination } = submitData;

      if (destination.length === 1) {
        return ElMessage({ message: '请选择正确到站地址', type: 'warning' });
      }
      // 筛选到站
      const _findeLocation = details.regionOptione
        .find(val => val.value === destination[0])
        .children.find(val => val.value === destination[1]);
      if (destination.length === 2) {
        submitData.destination = _findeLocation.label;
      } else {
        submitData.destination = _findeLocation.children.find(
          val => val.value === destination[2]
        ).label;
      }
      submitData.goodsName = submitData.waybillDetailList.map(val => val.goodsName).join(',');
      submitData.waybillType = 1;
      if (typeof submitData.receipt === 'object') submitData.receipt = submitData.receipt.join(',');
      console.log('submitData :>> ', submitData);
      const res = await postOpenOrderOpenWaybill(submitData);
      const { code } = res.data;
      if (code !== 200) return;
      back();
      console.log('res :>> ', res);
    } else {
      console.log('error submit!');
      return false;
    }
  });
};
</script>

<style scoped lang="scss">
$borderColor: #172e60;
: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;
}

// 页面字体大小
.avue-crud {
  font-size: 12px !important;
}

.form_top {
  margin-bottom: 10px;
}

.border-top {
  border-top: 1px solid $borderColor;
}

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

  &:first-child {
    display: block;
    border-top: 1px solid $borderColor;
    border-left: 1px solid $borderColor;

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

  &:last-child {
    display: block;
    border-bottom: 1px solid $borderColor;
    border-right: 1px solid $borderColor;
    box-sizing: border-box;

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

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

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

.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-form-item) {
  flex: 1;
  margin: 0;
}

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

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

// 底部
.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;
}
</style>
