<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <div class="page-order">
    <div class="screening-conditions">
      <el-form
        :inline="true"
        :model="searchForm"
        @submit.prevent
        @keyup.enter="onGetDataList(true)"
      >
        <div class="search">
          <el-form-item :label="$t('order.order.number') + '：'">
            <el-input
              v-model="searchForm.orderId"
              class="input-text-algin"
              :placeholder="$t('order.order.pleaseEnter') + $t('order.order.number')"
              maxlength="19"
              oninput="value=value.replace(/[^0-9]/g,'')"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <div class="input-row">
              <el-select
                v-model="consigneeKey"
                @change="onChangeConsigneeKey"
              >
                <el-option
                  v-for="item in consigneeKeyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="searchForm.consigneeOrMobile"
                :placeholder="$t('order.order.pleaseEnter') + consigneeKeyOption[consigneeKey].label"
                maxlength="100"
                clearable
              />
            </div>
          </el-form-item>
          <el-form-item>
            <div class="input-row">
              <el-select
                v-model="spuKey"
                @change="onChangeSpuKey"
              >
                <el-option
                  v-for="item in spuKeyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="searchForm.spuNameOrSkuCode"
                :placeholder="$t('order.order.pleaseEnter') + spuKeyOption[spuKey].label"
                maxlength="100"
                clearable
              />
            </div>
          </el-form-item>
          <el-form-item>
            <div class="input-row">
              <el-select
                v-model="shopKey"
                @change="onChangeShopKey"
              >
                <el-option
                  v-for="item in shopKeyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="searchForm.commodityNameOrCode"
                :placeholder="$t('order.order.pleaseEnter') + shopKeyOption[shopKey].label"
                maxlength="100"
                clearable
              />
            </div>
          </el-form-item>
          <el-form-item :label="$t('order.order.status') + '：'">
            <el-select
              v-model="status"
              clearable
              :placeholder="$t('order.order.statusMsg')"
              style="width: 199px;"
              @change="onChangeOrderStatus"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 下单时间 -->
          <el-form-item :label="$t('order.order.createTime') + '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :range-separator="$t('date.tip')"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :default-time="defaultTime"
            />
            <el-button
              style="margin-left: 12px;"
              plain
              @click="onSetDateRange(1)"
            >
              {{
                $t("date.t")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(2)"
            >
              {{
                $t("date.y")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(3)"
            >
              {{
                $t("date.n")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(4)"
            >
              {{
                $t("date.m")
              }}
            </el-button>
          </el-form-item>
        </div>
        <div class="operation-box">
          <el-form-item>
            <!-- 搜索 -->
            <el-button
              type="primary"
              @click="onSearch()"
            >
              {{ $t("table.search") }}
            </el-button>
            <!-- 重置 -->
            <el-button
              plain
              @click="onClear()"
            >
              {{ $t("table.clear") }}
            </el-button>
            <!-- 导出 -->
            <el-button
              v-permission="['order:order:sold']"
              plain
              @click="onGetSoldExcel()"
            >
              {{ $t("table.export") }}
            </el-button>
            <!-- 批量发货 -->
            <el-button
              v-permission="['order:delivery:getExcel']"
              plain
              @click="onUploadSpu"
            >
              {{ $t("order.order.bulkShipment") }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main">
      <div class="content">
        <!-- 导航 -->
        <div class="status-nav clearfix">
          <ul class="nav-list clearfix">
            <li
              :class="['nav-item', sts === 0 ? 'selected' : '']"
              @click="onSelectNav(0)"
            >
              {{ $t("date.a") }}
            </li>
            <li
              :class="['nav-item', sts === 2 ? 'selected' : '']"
              @click="onSelectNav(2)"
            >
              {{ $t("order.order.toBeShipped") }}
            </li>
            <li
              :class="['nav-item', sts === 3 ? 'selected' : '']"
              @click="onSelectNav(3)"
            >
              {{ $t("order.order.pendingReceipt") }}
            </li>
            <li
              :class="['nav-item', sts === 5 ? 'selected' : '']"
              @click="onSelectNav(5)"
            >
              {{ $t("order.order.successfulTransaction") }}
            </li>
            <li
              :class="['nav-item', sts === 6 ? 'selected' : '']"
              @click="onSelectNav(6)"
            >
              {{ $t("order.order.transactionFailed") }}
            </li>
          </ul>
        </div>

        <!-- 列标题 -->
        <div :class="['tit', showHeadScroll ? (sidebarOpenState?'fixed-top fixed-top-w1':'fixed-top fixed-top-w2') : '']">
          <el-row style="width: 100%">
            <el-col :span="5">
              <span class="item product">{{ $t("constant.product") }}</span>
            </el-col>
            <el-col
              :span="5"
              class="transaction-price"
            >
              <span class="item">{{ $t("order.order.transaQuantity") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{
                $t("order.order.actualPaymentAmount")
              }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.commissionMerchant") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.buyerConsignee") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.orderStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.afterSalesStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("table.actions") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="order in dataList"
          :key="order.orderId"
          class="prod"
          style="margin-bottom: 15px"
        >
          <div class="prod-tit">
            <span>{{ $t("order.order.number") }}:{{ order.orderId }}</span>
            <span>{{ $t("order.order.createTime") }}:{{ order.createTime }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%;">
              <el-col
                :span="10"
                style="height: 100%"
              >
                <order-prod-card
                  :order="order"
                />
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="price-block">
                    <span
                      v-if="order.actualTotal"
                      class="totalprice"
                    >{{ formatPrice(order.actualTotal, 1).toFixed(2)
                    }}{{ $t("constant.dollar") }}</span>
                    <span
                      v-if="order.actualTotal && order.orderScore"
                      class="totalprice"
                    >&nbsp;+&nbsp;</span>
                    <span
                      v-if="order.orderScore"
                      class="totalprice"
                    >{{ order.orderScore
                    }}{{ $t("order.order.integral") }}</span>
                    <br v-if="order.freightAmount">
                    <span
                      v-if="order.freightAmount"
                      class="totalprice"
                    >&nbsp;
                      {{ $t("order.order.freightAmount") + '：￥' + onHandlerPrice(order.freightAmount) }}
                    </span>
                    <span
                      v-if="order.platformFreeFreightAmount"
                      class="totalprice"
                    >
                    &nbsp;
                      {{ $t("order.order.platformFreeFreightAmount") + '：￥' + formatPrice(order.platformFreeFreightAmount, 1).toFixed(2) }}
                    </span>
                    <br>
                    <span>{{ $t("order.order.total") }}{{ order.allCount
                    }}{{ $t("constant.piece") }}</span>
                    <br>
                    <!-- 修改金额 -->
                    <el-button
                      v-if="order.status === 1"
                      v-permission="['order:order:amount']"
                      link
                      type="primary"
                      @click="onEditAmount(order)"
                    >
                      {{ $t("order.order.modifyTheAmount") }}
                    </el-button>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.shopName }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.shopMobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.consignee }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.mobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span>
                    <span
                      v-if="order.status === 1"
                      type="danger"
                    >{{ $t("pay.obligation") }}</span>
                    <span
                      v-else-if="order.status === 2"
                      type="danger"
                    >{{ $t("order.order.toBeShipped") }}</span>
                    <span
                      v-else-if="order.status === 3"
                      type="danger"
                    >{{ $t("order.order.pendingReceipt") }}</span>
                    <span
                      v-else-if="order.status === 7"
                      type="danger"
                    >{{ $t("group.waitGroup") }}</span>
                    <span
                      v-else-if="order.status === 5"
                      type="danger"
                    >{{ $t("order.order.successfulTransaction") }}</span>
                    <span
                      v-else-if="order.status === 6"
                    >{{
                      $t("order.order.transactionFailed")
                    }}</span>
                  </span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="order.refundStatus === 1"
                    type="danger"
                  >{{ $t("order.order.refundApplication") }}</span>
                  <span
                    v-else-if="order.refundStatus === 2"
                    type="danger"
                  >{{ $t("order.order.refundsuccessfully") }}</span>
                  <span
                    v-else-if="order.refundStatus === 3"
                    type="danger"
                  >{{ $t("order.order.partialRefundSucc") }}</span>
                  <span
                    v-else-if="order.refundStatus === 4"
                    type="danger"
                  >{{ $t("order.order.refundFailed") }}</span>
                  <span
                    v-else
                    type="danger"
                  >{{
                    $t("order.order.noAfterSales")
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <el-button
                      v-permission="['order:order:info']"
                      link
                      type="primary"
                      @click="onJumpOrderInfo(order.orderId)"
                    >
                      {{ $t("order.order.seeDetails") }}
                    </el-button>
                    <el-button
                      v-if="
                        order.status === 3 &&
                          (!order.refundStatus || order.refundStatus > 2) &&
                          order.deliveryType === 1 && order.updateOrViewDeliveryInfo === 1
                      "
                      v-permission="['order:order:logistics']"
                      link
                      type="primary"
                      @click="onReviseLogistics(order.orderId)"
                    >
                      {{ $t("order.order.modifyLogistics") }}
                    </el-button>
                    <el-button
                      v-if="order.status === 2 && order.deliveryType !== 2"
                      v-permission="['order:order:delivery']"
                      link
                      type="primary"
                      @click="onChangeOrder(order)"
                    >
                      {{ $t("order.order.delivery") }}
                    </el-button>
                    <el-button
                      v-if="order.status === 2 && order.deliveryType === 2"
                      link
                      type="primary"
                      @click="onStationOrder(order)"
                    >
                      {{ $t("order.order.pickUp") }}
                    </el-button>
                    <el-button
                      v-if="order.refundStatus && order.supplierHandleStatus > -1"
                      v-permission="['order:order:refund']"
                      link
                      type="primary"
                      @click="onJumpRefundOrder(order.orderId)"
                    >
                      {{ $t("order.order.refundInformation") }}
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t("order.order.noData") }}
        </div>
      </div>
    </div>
    <!-- 分页条 -->
    <pagination
      v-show="page.total > 0"
      v-model:page="page.pageNum"
      v-model:limit="page.pageSize"
      style="text-align: right"
      :total="page.total"
      @pagination="onGetDataList(false)"
    />
    <!-- 弹窗 -->
    <order-station
      v-if="orderStationVisible"
      ref="orderStationRef"
      @refresh-order-station-data-list="onGetDataList"
    />
    <order-amount-update
      v-if="orderAmountUpdateVisible"
      ref="orderAmountUpdateRef"
      @refresh-order-amount-update="onGetDataList"
    />
    <order-delivery-update
      v-if="devyVisible"
      ref="orderDeliveryUpdateRef"
      @refresh-order-delivery-update="onGetDataList"
    />
    <!-- 修改物流 -->
    <el-dialog
      v-model="logVisible"
      :title="$t('order.order.modifyLogistics')"
      :close-on-click-modal="false"
      width="50%"
    >
      <div
        v-if="isReviseLog"
        v-loading="isLogLoading"
        class="revise-log"
      >
        <div class="change-logistics">
          <div class="warning">
            {{ $t("order.order.ifModifyTheLog") }}
          </div>
          <div class="log-list">
            <div
              v-for="(logItem, index) in logisticsInfo"
              :key="index"
              class="item"
            >
              <div class="i-tit">
                <div class="big">
                  {{ $t("order.order.package") }}{{ index + 1 }}
                </div>
                <div class="text">
                  {{ $t("order.order.total") }} {{ logItem.allCount }}
                  {{ $t("constant.piece") }}{{ $t("constant.product") }}
                </div>
              </div>
              <div class="goods-box">
                <div
                  v-for="(
                    orderItem, curIndex
                  ) in logItem.orderItems"
                  :key="curIndex"
                  class="item"
                >
                  <div class="img">
                    <ImgShow :src="orderItem.supplierImgUrl" />
                    <div class="number">
                      ×{{ orderItem.count }}
                    </div>
                  </div>
                  <div class="name">
                    {{ orderItem.supplierSpuName }}
                  </div>
                </div>
                <el-form
                  ref="logDataFormRef"
                  :model="logDataForm"
                  label-width="95px"
                  @submit.prevent
                  @keyup.enter="onSubmitLogDataForm()"
                >
                  <!--发货方式-->
                  <el-form-item
                    :label="$t('order.order.deliveryMethod') + '：'"
                    style="text-align: left;"
                  >
                    <el-radio-group v-model="logItem.tempDeliveryType">
                      <el-radio
                        :label="1"
                        disabled
                      >
                        {{
                          $t("order.order.ordinaryExpress")
                        }}
                      </el-radio>
                      <el-radio
                        :label="3"
                        disabled
                      >
                        {{
                          $t("order.order.noNeedRequired")
                        }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <!--配送方式 线上 线下-->
                  <el-form-item
                    v-if="logItem.tempDeliveryType === 1"
                    :label="$t('order.order.delType') + '：'"
                    style="text-align: left;"
                  >
                    <el-radio-group v-model="logItem.deliveryType">
                      <el-radio
                        :label="0"
                        disabled
                      >
                        {{
                          $t("order.order.onlineDelivery")
                        }}
                      </el-radio>
                      <el-radio
                        :label="1"
                        disabled
                      >
                        {{
                          $t("order.order.selfDelivery")
                        }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <div
                    v-if="logItem.deliveryType === 1"
                    class="info-int"
                  >
                    <!-- 快递公司 -->
                    <el-form-item
                      :label="$t('order.order.courierCompany') + '：'"
                      class="form-item"
                      style="text-align: left;"
                    >
                      <div class="con">
                        <el-select
                          v-model="logItem.deliveryCompanyId"
                          class="int-frame"
                        >
                          <el-option
                            v-for="item in logDataForm.names"
                            :key="item.deliveryCompanyId"
                            :label="item.name"
                            :value="item.deliveryCompanyId"
                          />
                        </el-select>
                      </div>
                    </el-form-item>
                    <!-- 快递单号 -->
                    <el-form-item
                      :label="$t('order.order.trackingNumber') + '：'"
                      class="form-item"
                    >
                      <el-input
                        v-model="logItem.deliveryNo"
                        controls-position="right"
                        :min="0"
                        :class="['int-frame', errorNum === 1 ? 'errortip' : '']"
                      />
                    </el-form-item>
                  </div>
                  <div
                    v-if="logItem.deliveryType === 0"
                    class="info-int"
                  >
                    <el-form-item
                      :label="$t('order.order.courierCompany') + '：'"
                      class="form-item"
                      style="text-align: left;"
                    >
                      <div
                        v-if="logVisible"
                        class="con"
                      >
                        {{ deliveryCompanyType[logItem.deliveryCompanyId - 1].label }}
                      </div>
                    </el-form-item>
                    <el-form-item
                      :label="$t('order.order.trackingNumber') + '：'"
                      class="form-item"
                    >
                      {{ logItem.deliveryNo }}
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="!isReviseLog"
          class="change-logistics"
        >
          <div class="warning">
            {{ $t("order.order.ifModifyTheLog") }}
          </div>
          <el-table
            class="log-info-table"
            :data="confirmList"
          >
            <el-table-column
              property="deliveryCompanyIdName"
              :label="$t('order.order.packageName')"
              width="220"
              style="text-align: left"
            />
            <el-table-column
              property="allCount"
              :label="$t('order.order.amountOfGoods')"
              width="140"
            />
            <el-table-column
              property="delMethod"
              :label="$t('order.order.deliveryMethod')"
              width="140"
            />
            <el-table-column
              property="name"
              :label="$t('order.order.logisticsCompany')"
              width="170"
            />
            <el-table-column
              property="deliveryNo"
              :label="$t('order.order.trackingNumber')"
            />
          </el-table>
        </div>
        <div
          v-if="isReviseLog"
          class="dialog-footer"
        >
          <!-- 取消 -->
          <el-button
            plain
            @click="logVisible = false"
          >
            {{
              $t("table.cancel")
            }}
          </el-button>
          <!-- 保存 -->
          <el-button
            type="primary"
            @click="onSubmitLogDataForm()"
          >
            {{
              $t("order.order.save")
            }}
          </el-button>
        </div>
        <div
          v-if="!isReviseLog"
          class="dialog-footer"
        >
          <el-button
            plain
            @click="onBackToRevise()"
          >
            {{
              $t("order.order.backToModify")
            }}
          </el-button>
          <el-button
            type="primary"
            @click="onConfirmRevise()"
          >
            {{
              $t("order.order.confirmTheChanges")
            }}
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- /修改物流弹窗 -->
    <order-upload
      v-if="uploadVisible"
      ref="spuUploadRef"
      :param="searchForm"
      @refresh-data-list1="onGetWaitingConsignmentExcel"
    />
  </div>
</template>

<script setup>
import OrderAmountUpdate from './components/order-amount-update.vue'
import OrderDeliveryUpdate from './components/order-delivery-update.vue'
import OrderStation from './components/order-station.vue'
import OrderUpload from './components/order-upload.vue'
import Pagination from '@/components/Pagination/index.vue'
import moment from 'moment'
import * as api from '@/api/order/order'
import * as deliveryCompanyApi from '@/api/delivery/delivery-company'
import { formatPrice } from '@/utils/index'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import OrderProdCard from './components/order-prod-card/index.vue'

const logisticsInfo = reactive([]) // 包裹列表
const logDataForm = reactive({
  deliveryCompanyId: '', // 当前物流公司id
  deliveryNo: '', // 物流单号
  names: [] // 物流公司列表
})
const confirmList = reactive([]) // 确认修改信息
const searchForm = reactive({
  orderId: '',
  spuName: '',
  stationName: '',
  orderType: '',
  payType: '',
  deliveryType: '',
  consignee: '',
  mobile: '',
  refundStatus: '',
  startTime: '',
  endTime: '',
  consigneeOrMobile: '',
  spuNameOrSkuCode: '',
  commodityNameOrCode: ''
})
const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
const dataList = reactive([])
const page = reactive({
  pageSize: 10,
  pageNum: 1,
  total: 0, // 一共多少条数据
  pages: 0 // 一共多少页
})
const deliveryCompanyType = [{
  value: 1,
  label: '顺丰速运'
}, {
  value: 2,
  label: '京东快递'
}, {
  value: 3,
  label: '圆通速递'
}, {
  value: 4,
  label: '韵达快递'
}, {
  value: 5,
  label: '中通快递'
}, {
  value: 6,
  label: '申通快递'
}, {
  value: 7,
  label: '百世快递'
}, {
  value: 8,
  label: 'EMS'
}]

// 侧边栏显隐状态
const appStore = useAppStore()
const sidebarOpenState = computed(() => {
  return appStore.sidebar.opened
})

const options = computed(() => {
  return [
    {
      value: 2,
      label: $t('order.order.toBeShipped')
    },
    {
      value: 3,
      label: $t('order.order.pendingReceipt')
    },
    {
      value: 5,
      label: $t('order.order.successfulTransaction')
    },
    {
      value: 6,
      label: $t('order.order.transactionFailed')
    }
  ]
})

const consigneeKeyOption = computed(() => {
  return [
    { value: 0, label: $t('order.order.consignee') },
    { value: 1, label: $t('order.order.consigneePhone') }
  ]
})

const spuKeyOption = computed(() => {
  return [
    { value: 0, label: $t('order.order.spuName') },
    { value: 1, label: $t('order.order.sku') }
  ]
})

const shopKeyOption = computed(() => {
  return [
    { value: 0, label: $t('order.order.commodityCondition') },
    { value: 1, label: $t('order.order.productCode') }
  ]
})

const fromChat = ref(null)
const route = useRoute()

onMounted(() => {
  // 获取首页跳转传递的参数
  if (route.query.orderNumber) {
    fromChat.value = useRoute().query.orderNumber
  }
  if (route.query.orderStatus) {
    onSelectNav(route.query.orderStatus)
  } else {
    onGetDataList()
  }
  onGetLogisticsList()
  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)
})

onUnmounted(() => {
  // 页面销毁时移除监听
  window.removeEventListener('scroll', onScrollToTop)
})

/**
 * 收货人/收货人手机号
 */
const onChangeConsigneeKey = () => {
  searchForm.consigneeOrMobile = ''
}

/**
 * 商品名称/suk编码
 */
const onChangeSpuKey = () => {
  searchForm.spuNameOrSkuCode = ''
}

/**
 * 代销卖家/代销编码
 */
const onChangeShopKey = () => {
  searchForm.commodityNameOrCode = ''
}

/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const onScrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 440 && dataList.length > 5
}

/**
 * 请求物流公司列表
 */
const onGetLogisticsList = () => {
  deliveryCompanyApi.list().then((data) => {
    logDataForm.names = data
  })
}

/**
 * 获取包裹物流信息
 */
const errorNum = ref(0)
const logVisible = ref(false)
const isLogLoading = ref(false)
const onReviseLogistics = (orderId) => {
  logVisible.value = !logVisible.value
  isLogLoading.value = true
  logDataForm.deliveryCompanyId = ''
  logDataForm.deliveryNo = ''
  logDataForm.names = []
  logisticsInfo.length = 0
  onGetLogisticsList()
  api.getOrderDeliveries({
    orderId
  }).then(data => {
    logisticsInfo.push(...data)
    logisticsInfo.forEach((el, index) => {
      el.tempDeliveryType = el.deliveryType === 1 || el.deliveryType === 0 ? 1 : el.deliveryType
      el.newDeliveryNo = el.deliveryNo
      el.newDeliveryCompanyId = el.deliveryCompanyId
      el.deliveryCompanyIdName = $t('order.order.package') + Number(index + 1)
      confirmList.length = 0
    })
    isLogLoading.value = false
  })
  errorNum.value = 0
}

const spuUploadRef = ref()
const uploadVisible = ref(false)
const onUploadSpu = () => {
  searchForm.startTime = dateRange.value === null ? null : dateRange.value[0]
  searchForm.endTime = dateRange.value === null ? null : dateRange.value[1]
  uploadVisible.value = true
  nextTick(() => {
    spuUploadRef.value?.init()
  })
}

const onGetWaitingConsignmentExcel = () => {
  onGetDataList()
}

// 提交修改物流信息
const onSubmitLogDataForm = () => {
  let flag = true
  confirmList.length = 0
  logisticsInfo.forEach((el) => {
    if (el.deliveryType === 3 || el.deliveryType === 0) {
      return
    }
    if (!flag) {
      return false
    }
    const reg = /^[a-zA-Z0-9]{4,30}$/
    if (el.deliveryNo.length === 0) {
      ElMessage({
        message: $t('order.order.logEmpty'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
    } else if (!reg.test(el.deliveryNo)) {
      ElMessage({
        message: $t('order.order.checkDeliveryNo'),
        type: 'warning'
      })
      flag = false
      errorNum.value = 1
    } else {
      errorNum.value = 0
      if ((el.newDeliveryNo.length !== 0 && el.newDeliveryNo !== el.deliveryNo) || (el.newDeliveryCompanyId !== el.deliveryCompanyId)) {
        confirmList.push(el)
        confirmList.forEach((el) => {
          el.delMethod = $t('order.order.logistics')
          // el.packageName = "包裹" + Number(index+1)
          logDataForm.names.forEach((name) => {
            if (el.deliveryCompanyId === name.deliveryCompanyId) {
              el.name = name.name
            }
          })
        })
      }
    }
  })
  if (errorNum.value === 1) {
    return
  } else if (confirmList.length === 0) {
    ElMessage({
      message: $t('order.order.noLogIsChanged'),
      type: 'warning'
    })
    flag = false
  }
  if (flag) {
    onConfirmRevise()
  }
}

/**
 * 确认修改物流信息
 */
const isReviseLog = ref(true)
const onConfirmRevise = () => {
  api.updateOrderDeliveries(confirmList).then(() => {
    ElMessage({
      message: $t('table.actionSuccess'),
      type: 'success'
    })
    logDataForm.deliveryCompanyId = ''
    logDataForm.deliveryNo = ''
    logDataForm.names = []
    logisticsInfo.length = 0
    isReviseLog.value = true
    logVisible.value = false
  })
}

/**
 * 返回修改（物流信息）
 */
const onBackToRevise = () => {
  isReviseLog.value = true
  // 清空确认列表
  confirmList.length = 0
}

/**
 * 获取数据列表
 */
const consigneeKey = ref(0)
const dataListLoading = ref(false)
const shopKey = ref(0)
const spuKey = ref(0)
const status = ref(null)
const sts = ref(0)
let tempSearchForm = null
const onGetDataList = (newdata = false) => {
  if (newdata || !tempSearchForm) {
    tempSearchForm = {
      pageNum: page.pageNum,
      pageSize: page.pageSize,
      orderId: fromChat.value === 1 ? searchForm.orderId : fromChat.value,
      consignee: !consigneeKey.value ? searchForm.consigneeOrMobile : undefined,
      mobile: consigneeKey.value ? searchForm.consigneeOrMobile : undefined,
      spuName: !spuKey.value ? searchForm.spuNameOrSkuCode : undefined,
      partyCodes: spuKey.value ? searchForm.spuNameOrSkuCode : undefined,
      shopName: !shopKey.value ? searchForm.commodityNameOrCode : undefined,
      spuCodes: shopKey.value ? searchForm.commodityNameOrCode : undefined,
      orderType: searchForm.orderType,
      payType: searchForm.payType,
      status: status.value,
      deliveryType: searchForm.deliveryType,
      refundStatus: searchForm.refundStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    }
  } else {
    tempSearchForm.status = status.value
    tempSearchForm.pageNum = page.pageNum
    tempSearchForm.pageSize = page.pageSize
    tempSearchForm = { ...tempSearchForm }
  }
  dataListLoading.value = true
  api.page(Object.assign(tempSearchForm)).then(data => {
    dataList.length = 0
    dataList.push(...data.list)
    page.total = data.total
    page.pages = data.pages
    sts.value = !status.value ? 0 : status.value
    dataListLoading.value = false
    fromChat.value = 1
  })
}

/**
 * 导航选择状态
 */
const onSelectNav = (val) => {
  sts.value = parseInt(val)
  status.value = sts.value === 0 ? null : parseInt(val)
  page.pageNum = 1
  onGetDataList(false)
}

const onChangeOrderStatus = (val) => {
  status.value = val
}

/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = (val) => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}

/**
 * 查看订单详情
 */
const router = useRouter()
const onJumpOrderInfo = (val) => {
  router.push(`/order/order-manage/order-info?orderId=${val}`)
}

// 退款路由跳转
const onJumpRefundOrder = (val) => {
  router.push({
    path: '/order/order-manage/refund-order',
    query: { orderId: val }
  })
}

// 清空按钮
const onClear = () => {
  searchForm.orderId = ''
  searchForm.consigneeOrMobile = ''
  searchForm.spuNameOrSkuCode = ''
  searchForm.commodityNameOrCode = ''
  dateRange.value = []
  status.value = null
}

// 搜索查询
const onSearch = () => {
  page.pageNum = 1
  onGetDataList(true)
}

/**
 * 更改订单金额
 */
const orderAmountUpdateRef = ref()
const orderAmountUpdateVisible = ref(false)
const onEditAmount = (order) => {
  orderAmountUpdateVisible.value = true
  nextTick(() => {
    orderAmountUpdateRef.value?.init(order)
  })
}

/**
 * 发货
 */
const devyVisible = ref(false)
const orderDeliveryUpdateRef = ref()
const onChangeOrder = (order) => {
  devyVisible.value = true
  nextTick(() => {
    orderDeliveryUpdateRef.value?.init(order)
  })
}

/**
 * 提货
 */
const orderStationRef = ref()
const orderStationVisible = ref(false)
const onStationOrder = (order) => {
  orderStationVisible.value = true
  nextTick(() => {
    orderStationRef.value?.init(order)
  })
}

const onGetSoldExcel = () => {
  if (!dateRange.value || dateRange.value.length < 2) {
    ElMessage.error($t('order.order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm($t('table.sureToExport'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    api.soldExcel({
      orderId: fromChat.value === 1 ? searchForm.orderId : fromChat.value,
      consignee: !consigneeKey.value ? searchForm.consigneeOrMobile : undefined,
      mobile: consigneeKey.value ? searchForm.consigneeOrMobile : undefined,
      spuName: !spuKey.value ? searchForm.spuNameOrSkuCode : undefined,
      partyCodes: spuKey.value ? searchForm.spuNameOrSkuCode : undefined,
      shopName: !shopKey.value ? searchForm.commodityNameOrCode : undefined,
      spuCodes: shopKey.value ? searchForm.commodityNameOrCode : undefined,
      orderType: searchForm.orderType,
      payType: searchForm.payType,
      status: status.value,
      deliveryType: searchForm.deliveryType,
      stationName: searchForm.stationName,
      refundStatus: searchForm.refundStatus,
      startTime: dateRange.value === null ? null : dateRange.value[0], // 开始时间
      endTime: dateRange.value === null ? null : dateRange.value[1] // 结束时间
    }).then((data) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('order.order.orderInfCollationXls')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch((e) => {
      ElMessage.error(e)
    })
  })
}

/**
 * 精度运算-价格过滤
 */
const onHandlerPrice = (val) => {
  if (val == null) {
    return ''
  }
  return new Big(val).div(100).toFixed(2)
}
</script>

<style lang="scss" scoped>
@use "./index.scss";
</style>
