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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <div class="page-purchase-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.purchaseNumber"
              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 :label="$t('order.order.consigneePhone') + '：'">
            <div class="input-row">
              <el-input
                v-model="searchForm.consigneeOrMobile"
                :placeholder="$t('order.order.pleaseEnter') + consigneeKeyOption[consigneeKey].label"
                maxlength="100"
                clearable
              />
            </div>
          </el-form-item>
          <!-- 商品名称 or Sku编码 -->
          <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>
          <!-- 代销卖家 or 代销商品编码 -->
          <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>
        </div>
        <div class="search">
          <!-- 订单状态 -->
          <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="onResetSearch()"
            >
              {{ $t("table.clear") }}
            </el-button>
            <!-- 导出 -->
            <el-button
              v-permission="['purchaseOrder:order:sold']"
              plain
              @click="onGetSoldExcel()"
            >
              {{ $t("table.export") }}
            </el-button>
            <!-- 批量发货 -->
            <el-button
              v-permission="['purchaseOrder: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 === -1 ? 'selected' : '']"
              @click="onSelectNav(-1)"
            >
              {{ $t("date.a") }}
            </li>
            <li
              :class="['nav-item', sts === 4 ? 'selected' : '']"
              @click="onSelectNav(4)"
            >
              {{ $t("order.order.pendingPayment") }}
            </li>
            <li
              :class="['nav-item', sts === 6 ? 'selected' : '']"
              @click="onSelectNav(6)"
            >
              {{ $t("product.pendingReview") }}
            </li>
            <li
              :class="['nav-item', sts === 1 ? 'selected' : '']"
              @click="onSelectNav(1)"
            >
              {{ $t("order.order.toBeShipped") }}
            </li>
            <li
              :class="['nav-item', sts === 2 ? 'selected' : '']"
              @click="onSelectNav(2)"
            >
              {{ $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 === 0 ? 'selected' : '']"
              @click="onSelectNav(0)"
            >
              {{ $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="4"
              class="column-title"
            >
              <span class="item">{{
                $t("order.order.actualPaymentAmount")
              }}</span>
            </el-col>
            <el-col
              :span="4"
              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.orderStatus") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("table.actions") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="order in dataList"
          :key="order.purchaseOrderId"
          class="prod"
          style="margin-bottom: 15px"
        >
          <div class="prod-tit">
            <span>{{ $t("order.order.number") }}:{{ order.purchaseOrderId }}</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%"
              >
                <div class="prod-item">
                  <div
                    v-for="orderItem in order.purchaseOrderItems"
                    :key="orderItem.orderItemId"
                    class="items name"
                  >
                    <div class="prod-image">
                      <ImgShow :src="orderItem.pic" />
                    </div>
                    <div class="prod-name">
                      <div class="prod-con">
                        <div class="prod-name-txt">
                          {{ orderItem.spuName + ' ' + (orderItem.skuName ? orderItem.skuName : '') }}
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>¥{{ onHandlerPrice(orderItem.purchasePrice) }}</span>
                      <span>{{ orderItem.purchaseStock }}{{ $t("constant.piece") }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="4"
                style="height: 100%"
              >
                <div class="item">
                  <div class="price-block">
                    <span
                      v-if="order.totalAmount"
                      class="totalprice"
                    >{{ onHandlerPrice(order.totalAmount)
                    }}{{ $t("constant.dollar") }}</span>
                    <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") + '：￥' + onHandlerPrice(order.platformFreeFreightAmount) }}
                    </span>
                    <br>
                    <span>{{ $t("order.order.total") }}{{ order.totalStock
                    }}{{ $t("constant.piece") }}</span>
                    <br>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="4"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <div class="buyer-name">
                      {{ order.shopName }}
                    </div>
                    <div class="buyer-phone">
                      {{ order.mobile }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <span>
                    <span
                      v-if="order.status === 1"
                      type="danger"
                    >{{ $t("order.order.toBeShipped") }}</span>
                    <span
                      v-else-if="order.status === 2"
                      type="danger"
                    >{{ $t("order.order.pendingReceipt") }}</span>
                    <span
                      v-else-if="order.status === 3"
                      type="danger"
                    >{{ $t("order.order.pendingReceipt") }}</span>
                    <span
                      v-else-if="order.status === 4"
                      type="danger"
                    >{{ $t("order.order.pendingPayment") }}</span>
                    <span
                      v-else-if="order.status === 6"
                      type="danger"
                    >{{ $t("product.pendingReview") }}</span>
                    <span
                      v-else-if="order.status === 5"
                      type="danger"
                    >{{ $t("order.order.successfulTransaction") }}</span>
                    <span
                      v-else-if="order.status === 0"
                    >{{
                      $t("order.order.transactionFailed")
                    }}</span>
                  </span>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <el-button
                      v-permission="['purchaseOrder:order:info']"
                      link
                      type="primary"
                      @click="onAddOrUpdate(order.purchaseOrderId)"
                    >
                      {{ $t("order.order.seeDetails") }}
                    </el-button>
                    <el-button
                      v-if="order.status === 1 && order.deliveryType !== 2"
                      v-permission="['purchaseOrder:order:delivery']"
                      link
                      type="primary"
                      @click="onChangeOrder(order)"
                    >
                      {{ $t("order.order.delivery") }}
                    </el-button>
                    <el-button
                      v-if="order.refundStatus"
                      v-permission="['purchaseOrder:order:refund']"
                      link
                      type="primary"
                      @click="onCheckRefund(order.purchaseNumber)"
                    >
                      {{ $t("order.order.refundInformation") }}
                    </el-button>
                    <el-button
                      v-if="order.status === 6"
                      link
                      type="primary"
                      @click="onUploadPay(order.purchaseOrderId)"
                    >
                      {{ $t("order.order.process") }}
                    </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-delivery-update
      v-if="devyVisible"
      ref="orderDeliveryUpdateRef"
      @refresh-order-delivery-update="onRefreshOrderDeliveryUpdate"
    />
    <order-upload
      v-if="uploadVisible"
      ref="spuUploadRef"
      :param="searchForm"
      @refresh-data-list1="onGetWaitingConsignmentExcel()"
    />
    <order-approve-payment
      v-if="paymentVisible"
      ref="paymentRef"
      @refresh-data-list="onRefreshOrderDeliveryUpdate"
    />
  </div>
</template>

<script setup>
import OrderDeliveryUpdate from './components/order-delivery-update.vue'
import Pagination from '@/components/Pagination/index.vue'
import OrderUpload from './components/order-upload.vue'
import orderApprovePayment from './components/order-approve-payment.vue'
import moment from 'moment'
import * as api from '@/api/order/purchase-order'
import Big from 'big.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索参数
const searchForm = reactive({
  purchaseNumber: '',
  consigneeOrMobile: '',
  spuNameOrSkuCode: '',
  commodityNameOrCode: '',
  spuName: '',
  orderType: '',
  payType: '',
  consignee: '',
  mobile: '',
  deliveryType: '',
  shopName: '',
  refundStatus: '',
  startTime: '',
  endTime: ''
})
// 日期
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 appStore = useAppStore()
const sidebarOpenState = computed(() => {
  return appStore.sidebar.opened
})

const options = computed(() => {
  return [
    {
      value: 4,
      label: $t('order.order.pendingPayment')
    },
    {
      value: 6,
      label: $t('product.pendingReview')
    },
    {
      value: 1,
      label: $t('order.order.toBeShipped')
    },
    {
      value: 2,
      label: $t('order.order.pendingReceipt')
    },
    {
      value: 5,
      label: $t('order.order.successfulTransaction')
    },
    {
      value: 0,
      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()
onMounted(() => {
  // 获取首页跳转传递的参数
  if (useRoute().query.purchaseNumber) {
    fromChat.value = useRoute().query.purchaseNumber
  }
  if (useRoute().query.orderStatus) {
    onSelectNav(useRoute().query.orderStatus)
  } else {
    onGetDataList()
  }
  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)
})

/**
 * 商品名称/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 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 paymentRef = ref()
const paymentVisible = ref(false)
const onUploadPay = (id) => {
  paymentVisible.value = true
  nextTick(() => {
    paymentRef.value?.init(id)
  })
}

/**
 * 批量发货回调
 */
const onGetWaitingConsignmentExcel = () => {
  onGetDataList()
}

/**
 * 获取数据列表
 */
const consigneeKey = ref(1)
const dataListLoading = ref(false)
const shopKey = ref(0)
const spuKey = ref(0)
const status = ref()
const sts = ref(-1)
let tempSearchForm = null
const onGetDataList = (newdata = false) => {
  if (newdata || !tempSearchForm) {
    tempSearchForm = {
      pageNum: page.pageNum,
      pageSize: page.pageSize,
      purchaseOrderId: fromChat.value === 1 ? searchForm.purchaseNumber : 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,
      status: status.value,
      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 => {
    page.total = data.total
    page.pages = data.pages
    dataList.length = 0
    dataList.push(...data.list)
    sts.value = !status.value && status.value !== 0 ? -1 : status.value
    dataListLoading.value = false
    fromChat.value = 1
  })
}

/**
 * 导航选择状态
 */
const onSelectNav = (val) => {
  sts.value = parseInt(val)
  status.value = sts.value === -1 ? 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 onAddOrUpdate = (val) => {
  router.push({
    path: '/order/order-manage/purchase-order-info',
    query: { purchaseNumber: val }
  })
}

/**
 * 查看退款
 */
const onCheckRefund = (val) => {
  router.push({
    path: '/order/order_manage/refund_order',
    query: { purchaseNumber: val }
  })
}

/**
 * 重置筛选表单
 */
const onResetSearch = () => {
  searchForm.purchaseNumber = ''
  searchForm.consigneeOrMobile = ''
  searchForm.spuNameOrSkuCode = ''
  searchForm.commodityNameOrCode = ''
  dateRange.value = []
  status.value = null
}

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

const onRefreshOrderDeliveryUpdate = () => {
  setTimeout(onGetDataList, 1000)
}

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

/**
 * 导出筛选的订单
 */
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({
      purchaseOrderId: fromChat.value === 1 ? searchForm.purchaseNumber : 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] // 结束时间
    }).then((data) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('order.order.purchaseOrderInfCollationXls')
      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>
