<template>
  <div class="card flex-column h-100 overflow-hidden">
    <split-div ref="splitRef">
      <template #top>
        <div class="header-filter">
          <div class="header-filter-form">
            <ElForm
              ref="searchFormRef"
              :model="searchForm"
              size="default"
              inline
              label-position="right"
              label-width="70px"
            >
              <ElFormItem>
                <el-select
                  v-model="searchForm.timeType"
                  clearable
                  style="width: 100px; margin-right: 5px"
                  placeholder="时间类型"
                >
                  <el-option
                    v-if="statusCode !== 6"
                    value="1"
                    label="创建时间"
                  ></el-option>
                  <el-option value="2" label="确认时间"></el-option>
                  <el-option
                    v-if="statusCode !== 6"
                    value="3"
                    label="完成时间"
                  ></el-option>
                  <el-option
                    v-if="statusCode === 6"
                    value="4"
                    label="发货时间"
                  ></el-option>
                </el-select>
                <el-date-picker
                  v-model="timeRange"
                  :default-time="[
                    new Date(0, 0, 0, 0, 0, 0),
                    new Date(0, 0, 0, 23, 59, 59),
                  ]"
                  placeholder="收货人"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="datetimerange"
                  :shortcuts="pickerOptions.shortcuts"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  clearable
                  style="width: 210px"
                >
                </el-date-picker>
              </ElFormItem>
              <ElFormItem label="SKU">
                <ElInput
                  v-model="searchForm.mainSku"
                  placeholder=" SKU"
                  clearable
                  style="width: 125px"
                  @blur="searchForm.mainSku = searchForm.mainSku.trim()"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="成品ID">
                <ElInput
                  v-model="searchForm.endProductId"
                  placeholder="请输入成品ID"
                  clearable
                  style="width: 125px"
                  @blur="
                    searchForm.endProductId = searchForm.endProductId.trim()
                  "
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="生产单号">
                <ElInput
                  v-model="searchForm.subOrderNumber"
                  placeholder="生产单号"
                  clearable
                  style="width: 125px"
                  @blur="
                    searchForm.subOrderNumber = searchForm.subOrderNumber.trim()
                  "
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="订单号">
                <ElInput
                  v-model="searchForm.orderNumber"
                  placeholder="订单号"
                  clearable
                  style="width: 125px"
                  @blur="searchForm.orderNumber = searchForm.orderNumber.trim()"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="店铺单号">
                <ElInput
                  v-model="searchForm.shopNumber"
                  placeholder="店铺单号"
                  clearable
                  style="width: 125px"
                  @blur="searchForm.shopNumber = searchForm.shopNumber.trim()"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="内部标签">
                <ElInput
                  v-model="searchForm.internalMemo"
                  placeholder="内部标签"
                  clearable
                  style="width: 125px"
                  @blur="
                    searchForm.internalMemo = searchForm.internalMemo.trim()
                  "
                ></ElInput>
              </ElFormItem>
              <ElFormItem v-if="statusCode === 6" label="物流跟踪号">
                <ElInput
                  v-model="searchForm.logisticsTracking"
                  placeholder="物流跟踪号"
                  clearable
                  style="width: 125px"
                  @blur="
                    searchForm.logisticsTracking =
                      searchForm.logisticsTracking.trim()
                  "
                ></ElInput>
              </ElFormItem>
              <ElFormItem v-if="statusCode === 6" label="发货单号">
                <ElInput
                  v-model="searchForm.billNumber"
                  placeholder="发货单号"
                  clearable
                  style="width: 125px"
                  @blur="searchForm.billNumber = searchForm.billNumber.trim()"
                ></ElInput>
              </ElFormItem>
              <ElFormItem v-if="statusCode === 6" label="收货人">
                <ElInput
                  v-model="searchForm.lanshouName"
                  placeholder="收货人"
                  clearable
                  style="width: 125px"
                ></ElInput>
              </ElFormItem>
              <ElFormItem label="排序方式">
                <el-select
                  v-model="searchForm.order"
                  clearable
                  style="width: 125px"
                  placeholder="排序类型"
                >
                  <el-option value="desc" label="按创建时间从新到旧"></el-option>
                  <el-option value="asc" label="按创建时间从旧到新"></el-option>
                </el-select>
              </ElFormItem>
              <ElFormItem>
                <ElButton ref="searchBtnRef" type="primary" @click="search"
                  >查询</ElButton
                >
              </ElFormItem>
              <!--              <ElFormItem>-->
              <!--                <ElButton @click="resetSearchForm">重置</ElButton>-->
              <!--              </ElFormItem>-->
              <ElFormItem v-if="statusCode === 2">
                <ElButton type="success" @click="confirmProduce"
                  >确认生产</ElButton
                >
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 4"
              >
                <ElButton
                  :disabled="
                    selection.find((item) => item.manuscriptStatus !== 30)
                  "
                  type="warning"
                  is-dark
                  @click="downloadManuscript"
                  >下载稿件</ElButton
                >
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 4"
              >
                <ElButton
                  :disabled="
                    selection.find((item) => item.manuscriptStatus !== 30) ||
                    selection.length !== 1
                  "
                  type="success"
                  is-dark
                  @click="reGenerateManuscript"
                  >重新打包稿件
                </ElButton>
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 4"
              >
                <ElButton
                  :disabled="
                    selection.find((item) => item.manuscriptStatus !== 30) ||
                    selection.length !== 1
                  "
                  type="warning"
                  is-dark
                  @click="reCreateManuscript"
                  >重新生成稿件
                </ElButton>
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 4"
              >
                <ElButton
                  :loading="btnLoading"
                  type="primary"
                  dark
                  @click="printManuscript"
                  >打印生产单</ElButton
                >
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 7"
              >
                <ElButton type="success" dark @click="exportManuscript"
                  >导出生产单</ElButton
                >
              </ElFormItem>
              <ElFormItem>
                <ElButton type="warning" @click="addInternalTag"
                  >添加内部标签</ElButton
                >
              </ElFormItem>
              <ElFormItem
                v-if="statusCode === 2 || statusCode === 3 || statusCode === 4"
              >
                <ElButton type="primary" @click="refreshProduct"
                  >刷新商品信息</ElButton
                >
              </ElFormItem>
              <ElFormItem v-if="statusCode === 3 || statusCode === 4">
                <ElButton type="success" @click="confirmDelivery"
                  >发货</ElButton
                >
              </ElFormItem>
              <ElFormItem v-if="statusCode === 6">
                <ElButton type="success" @click="confirmCheck">质检</ElButton>
              </ElFormItem>
            </ElForm>
          </div>
          <div class="header-filter-tab">
            <div class="tabs">
              <div
                v-for="item in tabsNav"
                :key="item.statusCode"
                class="tabs-node"
                :class="
                  item.statusCode === statusCode ? 'tabs-node_active' : ''
                "
                @click="changeTab(item)"
              >
                <span class="tabs-node_label">{{ item.statusName }}</span>
                <span class="tabs-node_count">{{ `(${item.quantity})` }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #bottom>
        <div class="order-content flex-1 flex-column overflow-hidden">
          <div
            ref="tableWrapperRef"
            v-loading="loading"
            element-loading-text="加载中..."
            class="order-list flex-1 overflow-hidden"
            @contextmenu.prevent="handleContextMenu"
          >
            <ElTable
              v-show="statusCode !== 6"
              ref="tableRef"
              :data="tableData"
              :span-method="arraySpanMethod"
              default-expand-all
              border
              style="width: 100%; height: 100%"
              @selection-change="handleSelectionChange"
            >
              <ElTableColumn type="selection" width="50"></ElTableColumn>
              <ElTableColumn type="expand" width="1">
                <template #default="{ row }">
                  <div v-if="row.productList" class="table-expand">
                    <div
                      class="order-list-expand"
                      :style="{ width: `${thOrderDetailWidth + 50}px` }"
                    >
                      <ProductInfo
                        :row="row"
                        :is-pod="false"
                        :status="statusCode"
                      >
                        <template #operation="{ productItem }">
                          <div class="operation-item" title="添加备注">
                            <el-icon
                              class="icon"
                              style="color: #e6a23c"
                              @click="handleUpdateRemark(productItem)"
                              ><EditPen
                            /></el-icon>
                          </div>
                          <div
                            v-if="
                              (statusCode === 3 ||
                                statusCode === 4 ||
                                statusCode === 2) &&
                              (productItem.shipmentNum === 0 ||
                                productItem.num !==
                                  (productItem.shipmentNum || 0) -
                                    (productItem.notPassNum || 0))
                            "
                            class="operation-item"
                          >
                            <el-button
                              type="primary"
                              size="small"
                              @click="
                                handleAgainGenerated(
                                  productItem.subOrderNumber || '',
                                )
                              "
                              >重新生成</el-button
                            >
                          </div>
                          <div
                            v-if="
                              (statusCode === 3 ||
                                statusCode === 4 ||
                                statusCode === 2) &&
                              (productItem.shipmentNum === 0 ||
                                productItem.num !==
                                  (productItem.shipmentNum || 0) -
                                    (productItem.notPassNum || 0))
                            "
                            class="operation-item"
                          >
                            <el-button
                              type="success"
                              size="small"
                              @click="downloadManuscriptBySubOrder(productItem)"
                              >下载稿件</el-button
                            >
                          </div></template
                        ></ProductInfo
                      >
                      <template v-if="row.productList.length > 2">
                        <div class="order-list-expand_more">
                          <span @click="openAll(row)">
                            <template v-if="!row.moreable">
                              展开全部<strong style="color: red"
                                >({{ row.productList.length }})</strong
                              >条商品信息<el-icon style="vertical-align: middle"
                                ><ArrowDown /></el-icon
                            ></template>
                            <template v-else>
                              收起商品信息<el-icon
                                style="vertical-align: middle"
                                ><ArrowUp
                              /></el-icon>
                            </template>
                          </span>
                        </div>
                      </template>
                    </div>
                    <div class="order-actual-payment">
                      <div class="order-actual-payment_info">
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >商品价:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.productAmount
                          }}</span>
                        </div>

                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >小计:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.totalAmount || '--'
                          }}</span>
                        </div>
                        <div
                          v-if="row.totolBuyNumber"
                          class="order-list-expand_item_info_title"
                        >
                          <span class="order-list-expand_item_value"
                            >共{{ row.totolBuyNumber }}件</span
                          >
                        </div>
                      </div>
                    </div>
                    <div class="order-memo">
                      <div class="order-memo-info">
                        <div
                          v-for="memo in row.internalMemoList || []"
                          :key="memo.id"
                          class="order-memo-item"
                        >
                          <div
                            v-if="memo.operatorEmployeeName"
                            class="order-memo-item__name"
                          >
                            <span>{{ memo.operatorEmployeeName || '' }}</span>
                          </div>
                          <div
                            v-if="memo.operatorTime"
                            class="order-memo-item__time"
                          >
                            <span>{{ memo.operatorTime || '' }}</span>
                          </div>
                          <div
                            v-if="memo.content"
                            class="order-memo-item__content"
                          >
                            <span>{{ memo.content || '' }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="order-time">
                      <div class="order-time_info">
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >创建时间:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.createTime || '--'
                          }}</span>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >确认时间:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.startStockingTime || '--'
                          }}</span>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >完成时间:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.finishTime || '--'
                          }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="order-operate">
                      <div class="order-operate_info">
                        <div class="order-list-expand_item_info_title">
                          <ElButton
                            text
                            type="primary"
                            @click="openDetail(row.id)"
                            >查看详情
                          </ElButton>
                        </div>
                        <div
                          v-if="statusCode !== 2 && statusCode !== 3"
                          class="order-list-expand_item_info_title"
                        >
                          <ElButton
                            text
                            type="primary"
                            @click="openShipment(row.id)"
                            >查看发货单
                          </ElButton>
                        </div>

                        <div class="order-list-expand_item_info_title">
                          <ElButton text type="primary" @click="openLog(row.id)"
                            >操作日志
                          </ElButton>
                        </div>
                        <div
                          v-if="statusCode === 1 || statusCode === 3"
                          class="order-list-expand_item_info_title"
                        >
                          <ElButton
                            text
                            type="danger"
                            @click="cancelOrder(row.id)"
                            >取消
                          </ElButton>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </ElTableColumn>
              <ElTableColumn
                label="订单详情"
                header-align="center"
                show-overflow-tooltip
                class-name="th-order-detail"
                min-width="800"
              >
                <template #default="scope">
                  <div class="order-detail">
                    <div
                      :title="scope.row.orderNumber"
                      class="order-detail_item"
                    >
                      <span class="label">订单号:</span>
                      <span class="value">{{ scope.row.orderNumber }}</span>
                    </div>
                    <div
                      :title="scope.row.erpOrderNumber"
                      class="order-detail_item"
                    >
                      <span class="label">第三方订单号:</span>
                      <span class="value" :title="scope.row.erpOrderNumber">{{
                        scope.row.erpOrderNumber || '--'
                      }}</span>
                    </div>
                    <div
                      :title="scope.row.manuscriptStatusStr"
                      class="order-detail_item"
                    >
                      <span class="label">稿件状态:</span>
                      <span
                        class="value"
                        :title="scope.row.manuscriptStatusStr"
                        >{{ scope.row.manuscriptStatusStr || '--' }}</span
                      >
                    </div>

                    <div
                      :title="scope.row.lanshouName"
                      class="order-detail_item"
                    >
                      <span class="label">收货人:</span>
                      <span class="value">{{ scope.row.lanshouName }}</span>
                    </div>
                    <div
                      :title="scope.row.lanshouPhone"
                      class="order-detail_item"
                    >
                      <span class="label">电话:</span>
                      <span class="value">{{ scope.row.lanshouPhone }}</span>
                    </div>
                    <div
                      :title="scope.row.lanshouAddress"
                      class="order-detail_item"
                    >
                      <span class="label">收货地址:</span>
                      <span class="value" :title="scope.row.lanshouAddress">{{
                        scope.row.lanshouRegion + scope.row.lanshouAddress
                      }}</span>
                    </div>
                    <div
                      v-if="scope.row.shipmentUid"
                      :title="scope.row.shipmentUid"
                      class="order-detail_item"
                    >
                      <span class="label">提货码:</span>
                      <span class="value" :title="scope.row.shipmentUid">{{
                        scope.row.shipmentUid
                      }}</span>
                    </div>
                    <div
                      :title="scope.row.lanshouPost"
                      class="order-detail_item"
                    >
                      <span class="label">邮编:</span>
                      <span class="value">{{ scope.row.lanshouPost }}</span>
                    </div>
                  </div>
                </template>
              </ElTableColumn>
              <ElTableColumn
                label="实付款"
                show-overflow-tooltip
                width="280"
                header-align="center"
              ></ElTableColumn>
              <ElTableColumn
                label="内部标签"
                show-overflow-tooltip
                width="280"
                header-align="center"
              ></ElTableColumn>
              <ElTableColumn
                label="时间"
                show-overflow-tooltip
                width="280"
                header-align="center"
              ></ElTableColumn>
              <ElTableColumn label="操作" width="100" header-align="center">
              </ElTableColumn>
            </ElTable>
            <ElTable
              v-show="statusCode === 6"
              ref="tableQaRef"
              :data="tableData"
              :span-method="arraySpanMethod"
              default-expand-all
              border
              style="width: 100%; height: 100%"
              @selection-change="handleSelectionChange"
            >
              <ElTableColumn type="selection" width="50"></ElTableColumn>
              <ElTableColumn
                label="发货单号"
                width="280"
                show-overflow-tooltip
                prop="billNumber"
                header-align="center"
              ></ElTableColumn>
              <ElTableColumn label="发货单信息" header-align="center">
                <template #default="{ row }">
                  <div
                    v-if="row.detailList"
                    class="table-expand"
                    style="margin-right: -14px"
                  >
                    <div
                      style="flex: 1; flex-shrink: 0"
                      class="order-list-expand"
                    >
                      <ProductInfoInspected :row="row" :status="statusCode" />
                      <template v-if="row.detailList.length > 2">
                        <div class="order-list-expand_more">
                          <span @click="openAll(row)">
                            <template v-if="!row.moreable">
                              展开全部<strong style="color: red"
                                >({{ row.detailList.length }})</strong
                              >条商品信息<el-icon style="vertical-align: middle"
                                ><ArrowDown /></el-icon
                            ></template>
                            <template v-else>
                              收起商品信息<el-icon
                                style="vertical-align: middle"
                                ><ArrowUp
                              /></el-icon>
                            </template>
                          </span>
                        </div>
                      </template>
                    </div>
                    <div class="order-actual-payment">
                      <div class="order-actual-payment_info">
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >订单号:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.orderNumber
                          }}</span>
                          <el-icon
                            class="icon"
                            @click="copy(row.orderNumber || '')"
                          >
                            <DocumentCopy />
                          </el-icon>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >发货方式:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.shippingWay === 1 ? '送货上门' : '快递'
                          }}</span>
                        </div>
                        <div
                          v-if="row.shippingWay !== 1"
                          class="order-list-expand_item_info_title"
                        >
                          <span class="order-list-expand_item_label"
                            >物流名称:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.carriageName
                          }}</span>
                        </div>
                        <div
                          v-if="row.shippingWay === 2"
                          class="order-list-expand_item_info_title"
                        >
                          <span class="order-list-expand_item_label"
                            >物流跟踪号:</span
                          >
                          <span
                            style="color: red"
                            class="order-list-expand_item_value"
                            >{{ row.logisticsTracking }}</span
                          >
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >发货时间:</span
                          >
                          <span
                            style="color: red"
                            class="order-list-expand_item_value"
                            >{{ row.createTime || '--' }}</span
                          >
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >确认时间:</span
                          >
                          <span
                            style="color: red"
                            class="order-list-expand_item_value"
                            >{{
                              row.order ? row.order.startStockingTime : ''
                            }}</span
                          >
                        </div>

                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >收货人:</span
                          >
                          <span
                            style="color: red"
                            class="order-list-expand_item_value"
                            >{{ row.lanshouName || '--' }}</span
                          >
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >收货人电话:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.lanshouPhone || '--'
                          }}</span>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >邮编:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.lanshouPost || '--'
                          }}</span>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >收货地址:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.lanshouRegion + row.lanshouAddress
                          }}</span>
                        </div>
                        <div class="order-list-expand_item_info_title">
                          <span class="order-list-expand_item_label"
                            >提货码:</span
                          >
                          <span class="order-list-expand_item_value">{{
                            row.shipmentUid
                          }}</span>
                        </div>
                      </div>
                    </div>
                    <div class="order-operate">
                      <div class="order-operate_info">
                        <div class="order-list-expand_item_info_title">
                          <ElButton
                            text
                            type="primary"
                            @click="openLog(row.orderId)"
                            >操作日志
                          </ElButton>
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </ElTableColumn>
              <ElTableColumn
                show-overflow-tooltip
                label="发货单详情"
                width="280"
                header-align="center"
              >
              </ElTableColumn>
              <ElTableColumn label="操作" width="100" header-align="center">
              </ElTableColumn>
            </ElTable>
          </div>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[100, 200, 300, 400, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin: 10px auto 10px; text-align: right"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>
    </split-div>
  </div>
  <el-dialog
    v-model="shipmentVisible"
    title="发货"
    :close-on-click-modal="false"
    width="1600px"
    top="6vh"
    @opened="onShipmentDialogOpened"
  >
    <div class="header-search">
      <el-input
        ref="inputRef"
        v-model="productionOrderNumber"
        clearable
        size="large"
        placeholder="请输入生产单号"
        @keydown.enter="searchShipmentByOrderNumber"
      />
      <el-button
        type="primary"
        size="large"
        @click="searchShipmentByOrderNumber"
        >查询
      </el-button>
    </div>
    <Shipment
      ref="shipmentOrderRef"
      v-loading="shipmentLoading"
      :order-list="orderList"
      :current-row="currentRow"
      @change-current-row="onChangeCurrentRow"
    />
    <div class="shipment-logistics-info margin-top-20">
      <ElForm ref="shipmentFormRef" :model="shipmentForm" :rules="rules">
        <ElRow :gutter="20">
          <ElCol :span="6">
            <ElFormItem label="发货方式" prop="shippingWay">
              <ElSelect
                v-model="shipmentForm.shippingWay"
                clearable
                placeholder="请选择"
                style="width: 100%"
              >
                <ElOption label="送货上门" value="1"></ElOption>
                <ElOption label="快递" value="2"></ElOption>
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="shipmentForm.shippingWay === '2'" :span="6">
            <ElFormItem label="物流名称" prop="carriageName">
              <ElSelect
                v-model="shipmentForm.carriageName"
                filterable
                placeholder="请输入关键字"
                clearable
                style="width: 100%"
              >
                <ElOption
                  v-for="item in logisticsCompanyList"
                  :key="item.id"
                  :value="item.name"
                ></ElOption>
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="shipmentForm.shippingWay === '2'" :span="6">
            <ElFormItem label="物流跟踪号" prop="logisticsTracking">
              <ElInput
                v-model="shipmentForm.logisticsTracking"
                placeholder="请输入物流跟踪号"
                clearable
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="shipmentForm.shippingWay === '2'" :span="6">
            <ElFormItem label="物流费用" prop="carriageAmount">
              <ElInput
                v-model="shipmentForm.carriageAmount"
                clearable
                placeholder="请输入物流费用"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="shipmentVisible = false"
          >取消
        </el-button>
        <el-button size="large" type="primary" @click="saveShipment"
          >发货
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="sendOrderVisible"
    title="查看发货单"
    width="1300px"
    class="send-order-dialog"
    :close-on-click-modal="false"
  >
    <SendOrder :order-list="sendOrderList" />
  </el-dialog>
  <el-dialog
    v-model="logVisible"
    title="操作日志"
    width="1000px"
    :close-on-click-modal="false"
  >
    <LogList :log-list="logList" />
  </el-dialog>
  <el-dialog
    v-model="quarantineVisible"
    title="质检"
    width="80%"
    :close-on-click-modal="false"
    @opened="onQaDialogOpened"
    @close="onClose"
  >
    <div class="header-search">
      <el-input
        v-model="shipmentUid"
        style="width: 300px"
        placeholder="请输入提货码"
        size="large"
        clearable
      />
      <el-input
        ref="qaInputRef"
        v-model="qaCode"
        clearable
        size="large"
        placeholder="请输入生产单号"
        @keyup.enter="searchQaByOrderNumber"
      />
      <el-button type="primary" size="large" @click="searchQaByOrderNumber"
        >查询
      </el-button>
    </div>
    <Quarantine :quarantine="quarantine" />
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="quarantineVisible = false"
          >取消
        </el-button>
        <el-button size="large" type="primary" @click="() => toSaveQuarantine()"
          >质检完成
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 设置备注 -->
  <el-dialog v-model="dialogVisible" title="设置备注" width="30%">
    <el-input v-model="inputValue" clearable placeholder="请输入备注" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRemark">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <ElDrawer
    v-model="orderDetailDialogVisible"
    title="生产订单详情"
    direction="rtl"
    size="40%"
    :close-on-click-modal="false"
  >
    <OrderDetail :order-detail-data="orderDetailData" />
  </ElDrawer>
  <RightClickMenu
    ref="rightMenuRef"
    :show-copy-shop-number="true"
    :show-copy-count="false"
    :show-copy-sub-shop-number="true"
    @on-change="rightChange"
  />
</template>
<script setup lang="ts">
import Shipment from './Shipment.vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import type {
  SearchForm,
  SpanMethodProps,
  Tab,
  OrderData,
  ShipmentForm,
  LogisticsData,
  SendOrderData,
  LogListData,
  ProductList,
} from '@/types/api/order'
import { nextTick, onMounted, reactive, ref } from 'vue'
import useElTableColumnWidth from '@/utils/hooks/useElTableColumnWidth'
import {
  ArrowDown,
  ArrowUp,
  DocumentCopy,
  EditPen,
} from '@element-plus/icons-vue'
import usePageList from '@/utils/hooks/usePageList'
import {
  getOrderList,
  getOrderTabData,
  confirmProductionOrder,
  printOrder,
  exportOrder,
  addInternalTagApi,
  backEndCommentsApi,
  regenerateSingle,
  loadSendOutList,
  getLogList,
  getOrderDetail,
  cancelOrderApi,
  reGenerateScriptUrlApi,
  refreshProductInfo,
  reCreateScriptUrlApi,
  downloadOrder,
} from '@/api/order'
import { showConfirm } from '@/utils/ui'
import { useValue } from '@/utils/hooks/useValue'
import { filePath } from '@/api/axios'
import { getLogisticsCompanyList } from '@/api/common'
import type { FormRules } from 'element-plus'
import ProductInfo from './ProductInfo.vue'
import ProductInfoInspected from './ProductInfoInspected.vue'
import SendOrder from './SendOrder.vue'
import LogList from '@/components/LogList.vue'
import OrderDetail from './OrderDetail.vue'
import useShipment from './hook/useShipment'
import useQuarantine from './hook/useQuarantine'
import Quarantine from './Quarantine.vue'
import RightClickMenu from '@/components/RightClickMenu.vue'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'

const [searchForm] = useValue<SearchForm>({
  mainSku: '',
  endProductId: '',
  timeType: '',
  logisticsTracking: '',
  lanshouName: '',
  billNumber: '',
  shopNumber: '',
  orderNumber: '',
  internalMemo: '',
  subOrderNumber: '',
  order: 'asc',
})
const tabsNav = ref<Tab[]>([])
const splitRef = ref<InstanceType<typeof SplitDiv>>()
const btnLoading = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const inputValue = ref<string>('')
const remarkId = ref<number>(0)
function getStartTime() {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}-${month}-${day} 00:00:00`
}
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => {
        const start = new Date(new Date(getStartTime()).getTime())
        const end = new Date()
        return [start, end]
      },
    },
    {
      text: '昨天',
      value: () => {
        const start = new Date()
        const end = new Date(new Date(getStartTime()).getTime() - 1)
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 1 + 1)
        return [start, end]
      },
    },
    {
      text: '最近7天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        return [start, end]
      },
    },
    {
      text: '最近14天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 13)
        return [start, end]
      },
    },
    {
      text: '最近30天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
        return [start, end]
      },
    },
    {
      text: '本星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay,
        )
        return [start, end]
      },
    },
    {
      text: '上星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        end.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay - 1,
        )
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 7 + 1)
        return [start, end]
      },
    },
    {
      text: '这个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDate = new Date().getDate() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDate,
        )
        return [start, end]
      },
    },
    {
      text: '上个月',
      value: () => {
        const date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()
        const end = new Date(
          new Date(`${year}-${month + 1}-1 00:00:00`).getTime() - 1,
        )
        if (month === 0) {
          month = 12
          year = year - 1
        }
        const start = new Date(
          new Date(`${year}-${month}-1 00:00:00`).getTime(),
        )
        return [start, end]
      },
    },
    {
      text: '历史',
      value: () => {
        return ['', '']
      },
    },
  ],
}
const statusCode = ref(2)
const selection = ref<OrderData[]>([])
const timeRange = ref<string[]>([])
const logisticsCompanyList = ref<LogisticsData[]>([])
const rules = reactive<FormRules<ShipmentForm>>({
  shippingWay: [
    {
      required: true,
      message: '请选择物流方式',
    },
  ],
  carriageName: [
    {
      required: true,
      message: '请选择物流公司',
    },
  ],
  carriageAmount: [
    {
      required: true,
      message: '请输入物流费用',
    },
  ],
  logisticsTracking: [
    {
      required: true,
      message: '请输入物流跟踪号',
    },
  ],
})

// 分页查询
const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getOrderList(
      {
        ...searchForm.value,
        status: statusCode.value,
        timeType:
          timeRange.value && timeRange.value.length > 0
            ? searchForm.value.timeType
            : null,
        startTime:
          searchForm.value.timeType === ''
            ? null
            : timeRange.value && timeRange.value.length > 0
            ? timeRange.value[0]
            : null,
        endTime:
          searchForm.value.timeType === ''
            ? null
            : timeRange.value && timeRange.value.length > 0
            ? timeRange.value[1]
            : null,
      },
      page,
      pageSize,
    ).then((res) => res.data),
})

const [tableWrapperRef, thOrderDetailWidth] = useElTableColumnWidth(
  'table th.th-order-detail',
)
// 发货
const {
  shipmentFormRef,
  productionOrderNumber,
  shipmentVisible,
  inputRef,
  shipmentForm,
  currentRow,
  shipmentLoading,
  orderList,
  shipmentOrderRef,
  searchShipmentByOrderNumber,
  saveShipment,
  confirmDelivery,
  onShipmentDialogOpened,
} = useShipment(() => {
  loadTabData()
  search()
})
const quarantine = useQuarantine()

// 质检
const {
  quarantineVisible,
  qaInputRef,
  qaCode,
  shipmentUid,
  searchQaByOrderNumber,
  toSaveQuarantine,
  confirmCheck,
  onQaDialogOpened,
} = quarantine
onMounted(() => {
  loadTabData()
  getLogisticsList()
})
const onClose = () => {
  loadTabData()
  search()
}
// 获取物流公司
const getLogisticsList = async () => {
  try {
    const res = await getLogisticsCompanyList()
    logisticsCompanyList.value = res.data
  } catch (error) {
    //showError(error)
  }
}
const downloadManuscriptBySubOrder = async (item: ProductList) => {
  try {
    const res = await downloadOrder(item.id)
    window.open(filePath + res.message)
  } catch (e) {
    //showError(e)
  }
}
const sendOrderList = ref<SendOrderData[]>([])
const sendOrderVisible = ref(false)
// 获取发货单列表
const openShipment = async (id: number) => {
  try {
    const res = await loadSendOutList(id)
    sendOrderList.value = res.data
    sendOrderVisible.value = true
  } catch (error) {
    // showError(error)
  }
}
const arraySpanMethod = ({ columnIndex }: SpanMethodProps) => {
  if (columnIndex === 0 || columnIndex === 1) {
    return [1, 1]
  } else {
    return [1, 6]
  }
}
const changeTab = (item: Tab) => {
  statusCode.value = item.statusCode
  searchForm.value.timeType = ''
  search()
  nextTick(() => {
    splitRef.value!.domResize()
  })
}
const handleUpdateRemark = (data: ProductList) => {
  dialogVisible.value = true
  inputValue.value = data.remark || ''
  remarkId.value = data.id
}
// 重新生成
const handleAgainGenerated = async (id: number | string) => {
  try {
    const res = await regenerateSingle(id)
    search()
    ElMessage({
      message: res.message,
      type: 'success',
      offset: window.innerHeight / 2,
    })
  } catch (e) {
    ElMessage({
      message: '提交失败，请重试',
      type: 'error',
      offset: window.innerHeight / 2,
    })
  }
}
const submitRemark = async () => {
  try {
    const res = await backEndCommentsApi(remarkId.value, inputValue.value)
    search()
    dialogVisible.value = false
    inputValue.value = ''
    ElMessage({
      message: res.message,
      type: 'success',
      offset: window.innerHeight / 2,
    })
  } catch (e) {
    ElMessage({
      message: '提交失败，请重试',
      type: 'error',
      offset: window.innerHeight / 2,
    })
    dialogVisible.value = true
  }
}
const copy = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}
const openAll = (row: OrderData) => {
  row.moreable = !row.moreable
}
const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data
  } catch (error) {
    // showError(error)
  }
}
const handleSelectionChange = (s: OrderData[]) => {
  selection.value = s
}
// 确认生产
const confirmProduce = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  try {
    await showConfirm('是否确认生产', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  const ids = selection.value.map((item) => item.id)
  try {
    const res = await confirmProductionOrder(ids)
    search()
    await loadTabData()
    ElMessage.success(res.message)
  } catch (e) {
    // showError(e)
  }
}
// 下载稿件
const downloadManuscript = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const manuscriptUrl = []
  for (const item of selection.value) {
    if (item.manuscriptStatus !== 30) {
      return ElMessage({
        message: '请选择稿件下载已完成的订单',
        type: 'warning',
        offset: window.innerHeight / 2,
      })
    } else {
      manuscriptUrl.push(item.manuscriptUrl)
    }
  }

  try {
    await showConfirm('是否确认下载', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  manuscriptUrl.forEach((path) => {
    window.open(filePath + path)
  })
}
// 重新打包稿件
const reGenerateManuscript = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const ids = selection.value.map((item) => item.id)
  try {
    await showConfirm('是否重新打包稿件 ', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await reGenerateScriptUrlApi(ids)
    ElMessage.success(res.message)
    search()
  } catch (e) {
    // showError(e)
  }
}
//重新生成稿件
const reCreateManuscript = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  const ids = selection.value.map((item) => item.id)
  try {
    await showConfirm('是否重新生成稿件 ', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await reCreateScriptUrlApi(ids[0])
    ElMessage.success(res.message)
    search()
  } catch (e) {
    // showError(e)
  }
}
// 打印生产单
const printManuscript = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }

  const ids = selection.value.map((item) => item.id)
  try {
    await showConfirm('是否打印生产单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  btnLoading.value = true
  try {
    const res = await printOrder(ids)
    btnLoading.value = false
    window.open(filePath + res.message)
  } catch (e) {
    //showError(e)
    btnLoading.value = false
  }
}
// 导出生产单
const exportManuscript = async () => {
  try {
    const res = await exportOrder({
      ids: selection.value.map((el) => el.id),
      status: statusCode.value,
    })
    window.open(filePath + res.message)
  } catch (e) {
    // showError(e)
  }
}
const refreshProduct = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  try {
    await showConfirm('是否刷新商品信息', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await refreshProductInfo(selection.value.map((el) => el.id))
    ElMessage({
      message: res.message,
      type: 'success',
      offset: window.innerHeight / 2,
    })
    loadTabData()
    search()
  } catch (e) {
    // showError(e)
  }
}
// 添加内部便签
const addInternalTag = async () => {
  if (selection.value.length === 0) {
    return ElMessage({
      message: '请选择订单',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  ElMessageBox.prompt('', '添加内部便签', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入内部便签',
    inputPattern: /.+/,
    inputErrorMessage: '内部便签不能为空',
  }).then(async ({ value }) => {
    try {
      const res = await addInternalTagApi(
        selection.value.map((item) => item.id),
        value,
      )
      ElMessage.success(res.message)
      loadTabData()
      search()
    } catch (e) {
      // showError(e)
    }
  })
}
const orderDetailDialogVisible = ref(false)
const orderDetailData = ref<OrderData>({} as OrderData)
// 查看详情
const openDetail = async (id: number) => {
  try {
    const res = await getOrderDetail(id)
    orderDetailData.value = res.data
    orderDetailDialogVisible.value = true
  } catch (e) {
    //showError(e)
  }
}
const logVisible = ref(false)
const logList = ref<LogListData[]>([])
// 操作日志
const openLog = async (id: number) => {
  try {
    const res = await getLogList(id)
    logList.value = res.data
    logVisible.value = true
  } catch (e) {
    // showError(e)
  }
}
// 取消
const cancelOrder = async (id: number) => {
  try {
    await showConfirm('是否确认取消', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await cancelOrderApi(id)
    ElMessage({
      message: res.message,
      type: 'success',
      offset: window.innerHeight / 2,
    })
    loadTabData()
    search()
  } catch (e) {
    // showError(e)
  }
}
const rightMenuRef = ref()
const handleContextMenu = (e: MouseEvent) => {
  rightMenuRef.value?.setPosition({
    x: e.clientX,
    y: e.clientY,
    cardItem: e.clientY,
    el: e,
  })
}
const tableQaRef = ref()
const tableRef = ref()
const rightChange = (key: string) => {
  if (key === 'select-all') {
    if (statusCode.value === 6) {
      tableQaRef.value?.toggleAllSelection()
    } else {
      tableRef.value?.toggleAllSelection()
    }
  } else if (key === 'cancel-select') {
    if (statusCode.value === 6) {
      tableQaRef.value?.clearSelection()
    } else {
      tableRef.value?.clearSelection()
    }
  } else if (key === 'copy_shopNumber') {
    let shopNumberList: string[] = []
    if (statusCode.value === 6) {
      shopNumberList = tableData.value
        .map((item) => item.detailList)
        .flat()
        .map((e) => e?.shopNumber)
        .filter((shopNumber): shopNumber is string => shopNumber !== undefined)
    } else {
      shopNumberList = tableData.value
        .map((item) => item.productList)
        .flat()
        .map((e) => e?.shopNumber)
        .filter((shopNumber): shopNumber is string => shopNumber !== undefined)
    }
    copy(shopNumberList.join(','))
  } else if (key === 'copy_code') {
    let subOrderNumber: string[] = []
    if (statusCode.value === 6) {
      subOrderNumber = tableData.value
        .map((item) => item.detailList)
        .flat()
        .map((e) => e?.subOrderNumber)
        .filter(
          (subOrderNumber): subOrderNumber is string =>
            subOrderNumber !== undefined,
        )
    } else {
      subOrderNumber = tableData.value
        .map((item) => item.productList)
        .flat()
        .map((e) => e?.subOrderNumber)
        .filter(
          (subOrderNumber): subOrderNumber is string =>
            subOrderNumber !== undefined,
        )
    }
    copy(subOrderNumber.join(','))
  }
}
const onChangeCurrentRow = (item: ProductList) => {
  currentRow.value = item
}

/**
 * @description: 页面添加回车监听
 */
const searchFormRef = ref()
const searchBtnRef = ref()

useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    search()
  },
})
</script>
<style lang="scss" scoped>
.header-filter-form {
  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

.header-filter-tab {
  margin-top: 10px;
}

.tabs {
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #f0f0f0;
  height: 42px;
}

.tabs-node {
  padding: 10px;
  font-size: 14px;
  color: #000;
  cursor: pointer;
  height: 40px;
}

.tabs-node:hover {
  color: #409eff;
}

.tabs-node.tabs-node_active {
  color: #409eff;
  border-bottom: 2px solid #409eff;
  font-weight: 600;
}

.order-content {
  margin-top: 10px;
  height: 100%;
}

.order-list {
  margin-top: 10px;
  flex: 1;

  :deep(.el-table__expand-icon > .el-icon) {
    display: none;
  }

  :deep(.el-table__row) {
    background-color: #f5f5f5;
  }

  :deep(.el-table__expanded-cell) {
    padding: 0;
  }
}

.order-detail {
  display: flex;
  font-size: 14px;
}

.order-detail_item {
  flex: 1;
  display: flex;
  align-items: center;

  .label {
    color: #aaa;
    margin-right: 6px;
  }

  .value {
    color: #000;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.table-expand {
  display: flex;
}

.order-operate {
  width: 100px;
}

.order-time {
  width: 280px;
  border-right: 1px solid #eee;
}

.order-memo {
  width: 280px;
  border-right: 1px solid #eee;
}

.order-time_info {
  padding: 20px;
  font-size: 14px;
}

.order-memo-info {
  padding: 20px;
  font-size: 14px;
}

.order-memo-item {
  display: flex;
  align-items: center;
  line-height: 26px;
}

.order-memo-item div:not(:last-child) {
  margin-right: 6px;
}

.order-actual-payment {
  width: 280px;
  border-right: 1px solid #eee;
}

.order-list-expand {
  border-right: 1px solid #eee;
  font-size: 14px;
  color: #606266;
  overflow: auto;
  max-height: 600px;
}

.order-list-expand_more {
  text-align: center;
  padding: 10px 0;

  span {
    cursor: pointer;
  }
}

.order-actual-payment_info {
  font-size: 14px;
  padding: 20px;
}

.order-operate_info {
  padding: 20px;

  :deep(.el-button) {
    padding: 0;
    font-size: 14px;
  }
}

.header-search {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  text-align: center;
}

.order-list-expand_item_info_title {
  line-height: 26px;
  display: flex;
  align-items: center;
}

.order-list-expand_item_label {
  margin-right: 6px;
}
</style>
<style>
.send-order-dialog .el-dialog__body {
  height: 600px;
  overflow: auto;
}
</style>
