<template>
  <z-paging
    ref="pagingRef"
    v-model="pagingData"
    default-page-size="10"
    empty-view-text="这里还没有相关订单~"
    :paging-style="{'top': '0','background-color': '#f4f4f4'}"
    :loading-more-custom-style="{'padding-bottom': '5.13rem', 'marginTop': '-100rpx'}"
    loading-more-no-more-text="没有更多了，看看别的吧"
    @query="loadStationOrderData"
    @list-change="changeData"
  >
    <view class="Mall4j container page-station-order-list">
      <view
        class="station-order-list"
        :class="{ 'bigger-bottom': curAppType !== appType.H5 }"
      >
        <view class="main">
          <!-- 订单列表 -->
          <blockquote
            v-for="(item, shopIndex) in stationList"
            :key="shopIndex"
          >
            <view class="prod-item">
              <!-- 订单编号 -->
              <view class="order-num">
                <checkbox
                  color="#fff"
                  class="check"
                  :data-shopindex="shopIndex"
                  :checked="item.checked"
                  :disabled="item.orderMold===0 && !(item.status===2 || item.status===3)"
                  @tap="orderRadioChange(shopIndex,item.status)"
                />
                <text>订单编号：{{ item.orderId }}</text>
                <view class="order-state">
                  <text :class="['order-sts', { red: item.status < 5 }]">
                    {{
                      [
                        '',
                        '待付款',
                        '待提货',
                        '待核销',
                        '待评价',
                        '已完成',
                        '已取消',
                        '拼团中'
                      ][item.status]
                    }}
                  </text>
                  <view
                    v-if="item.status === 6"
                    class="clear-btn"
                  >
                    <image
                      src="@/package-user/static/images/clear-his.png"
                      class="clear-list-btn"
                      :data-ordernum="item.orderId"
                      @tap="delOrderList"
                    />
                  </view>
                </view>
              </view>
              <!-- 商品列表 -->
              <!-- 一个订单单个商品的显示 -->
              <blockquote
                v-for="(prod, index) in item.orderItems"
                :key="index"
              >
                <view
                  v-if="prod.returnMoneySts!==5"
                  class="item-cont"
                  :data-ordernum="item.orderNumber"
                  @tap="toOrderDetailPage(item.orderId,item.deliveryType)"
                >
                  <view class="prod-pic">
                    <img-show :src="prod.pic" />
                  </view>
                  <view class="prod-info">
                    <view class="info-top">
                      <view class="prodname">
                        {{ prod.spuName || '' }}
                      </view>
                      <view class="price-nums">
                        <text class="prodprice">
                          <text
                            v-if="item.actualTotal"
                            class="symbol"
                          >
                            ￥
                          </text>
                          <text
                            v-if="item.actualTotal"
                            class="big-num"
                          >
                            {{
                              wxs.parsePrice(prod.price)[0]
                            }}
                          </text>
                          <text
                            v-if="item.actualTotal"
                            class="small-num"
                          >
                            {{ '.' + wxs.parsePrice(prod.price)[1] }}
                          </text>
                        </text>
                      </view>
                    </view>
                    <view class="sku-count">
                      <view class="prod-info-cont">
                        {{ prod.skuName || '' }}
                      </view>
                      <view class="count">
                        ×{{ prod.count || '' }}
                      </view>
                    </view>
                    <view class="sign-box">
                      <view
                        v-if="item.orderType"
                        class="spell-group-icon"
                      >
                        <!-- orderType 订单类型(0普通订单 1团购订单 2秒杀订单) -->
                        {{
                          ['', '拼团', '秒杀', '积分'][item.orderType]
                        }}
                      </view>
                      <view class="spell-group-icon">
                        {{
                          item.orderMold === 1 ? '虚拟商品' : '自提商品'
                        }}
                      </view>
                    </view>
                  </view>
                </view>
              </blockquote>
              <view class="total-num">
                <view
                  class="prodcount"
                >
                  共{{
                    item.allCount
                  }}件商品 合计：
                </view>
                <view
                  class="prodprice"
                >
                  <text
                    v-if="item.actualTotal"
                    class="symbol"
                  >
                    ￥
                  </text>
                  <text
                    v-if="item.actualTotal"
                    class="num"
                  >
                    {{
                      wxs.parsePrice(item.actualTotal)[0]
                    }}
                  </text>
                  <text
                    v-if="item.actualTotal"
                    class="num"
                  >
                    {{ '.' + wxs.parsePrice(item.actualTotal)[1] }}
                  </text>
                  <text
                    v-if="item.actualTotal && (item.orderType===3 || item.orderScore)"
                    class="symbol"
                  >
                    +
                  </text>
                  <text
                    v-if="item.orderType===3 || item.orderScore"
                    class="num"
                  >
                    {{ item.orderScore }}
                  </text>
                  <text
                    v-if="item.orderType===3 || item.orderScore"
                    class="symbol"
                  >
                    积分
                  </text>
                </view>
              </view>
              <!-- end 商品列表 -->
            </view>
          </blockquote>
        </view>
      </view>
      <!-- 占位标签 -->
      <view style="height: 100rpx;" />
      <!-- 提交按钮 -->
      <view
        v-if="stationList.length"
        class="foot"
      >
        <view
          class="confirm"
          :class="{ grey: !orderNumbers.length }"
          @tap="confirmRemoval"
        >
          确认核销
        </view>
      </view>
    </view>
    <!-- end 订单列表 -->
  </z-paging>
</template>

<script setup>
import { AppType } from '@/utils/constant'
import number from '@/wxs/number'

const wxs = number()

const appType = ref(AppType)
// 当前设备类型
const curAppType = ref(uni.getStorageSync('cloudAppType'))

let shopId = 0
let stationId = 0
const stationList = ref([])
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  // options = { ...$Route.query }
  if (options.shopId) {
    shopId = decodeURI(options.shopId)
  }
  if (options.stationId) {
    stationId = decodeURI(options.stationId)
  }
  stationList.value = []
})

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: shopId ? '商家需核销订单列表' : '自提点订单列表'
  })
})

/**
 * 用户点击右上角分享(勿删)
 */
onShareAppMessage(() => {})

let timer = ''
/**
 * 生命周期函数--监听页面卸载
 */
onUnload(() => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
})

const orderNumbers = ref([]) // 选中的订单
const pagingData = ref([])
const pagingRef = ref([])
/**
 * 加载自提点订单数据
 */
const loadStationOrderData = (pageNum, pageSize) => {
  let url
  let data
  if (shopId) {
    url = '/p/my_station_order/get_order_by_shopId'
    data = { shopId }
  } else {
    url = '/tmerclub_order/my_station_order/get_order_by_station_id'
    data = { stationId }
  }
  http.request({
    url,
    method: 'GET',
    data: {
      ...data,
      pageNum,
      pageSize
    }
  }).then(({ list }) => {
    pagingRef.value.complete(list)
  }).catch(() => {
    uni.showModal({
      title: '提示',
      content: '未查询到相关自提点，请重试',
      confirmText: '确定',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          uni.switchTab({
            url: '/pages/my/my'
          })
        }
      }
    })
    // 清空列表
    stationList.value = []
    // 清空选中的订单编号
    orderNumbers.value = []
  })
}

const changeData = (list) => {
  stationList.value = list
  stationList.value.forEach((item) => {
    item.checked = false
  })
}

/**
 * 查看订单详情
 */
const toOrderDetailPage = (orderId, deliveryType) => {
  uni.navigateTo({
    url: '/package-user/pages/order-detail/order-detail?orderId=' + orderId + '&deliveryType=' + deliveryType
  })
}

/**
 * 订单选择
 */
const orderRadioChange = (shopIndexPar, status) => {
  if (stationList.value[shopIndexPar].orderMold === 0 && !(status === 2 || status === 3)) {
    return
  }
  const stationListPar = stationList.value
  stationListPar[shopIndexPar].checked = !stationListPar[shopIndexPar].checked
  const orderNumbersPar = []
  stationListPar.forEach((el) => {
    if (el.checked) {
      orderNumbersPar.push(el.orderId)
    }
  })
  orderNumbers.value = orderNumbersPar
}

/**
 * 一键核销（整单）
 */
const confirmRemoval = () => {
  const orderNumbersPar = orderNumbers.value
  if (!orderNumbersPar || !orderNumbersPar.length) {
    uni.showToast({
      title: '请选择需要核销的订单',
      icon: 'none',
      duration: 1500
    })
    return
  }
  const data = shopId ? { shopId: Number(shopId) } : { stationId: Number(stationId) }
  uni.showModal({
    title: '提示',
    content: '是否确认核销?',
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        http.request({
          url: '/tmerclub_order/my_station_order/order_station_by_order_id',
          method: 'PUT',
          data: {
            orderIds: orderNumbersPar,
            ...data
          }
        }).then(() => {
          uni.showToast({
            title: '核销成功！',
            icon: 'none',
            duration: 1500
          })
          // 清空选中的订单编号
          orderNumbers.value = []
          stationList.value = []
          timer = setTimeout(() => {
            pagingRef.value.reload()
          }, 1500)
        }).catch((err) => {
          uni.showToast({
            title: err.msg || 'Error',
            icon: 'none'
          })
          if (err.msg.indexOf('卡券不存在或者已核销') !== -1) {
            // 清空选中的订单编号
            orderNumbers.value = []
            timer = setTimeout(() => {
              pagingRef.value.reload()
            }, 1000)
          }
        })
      }
    }
  })
}

</script>

<style lang="scss" scoped>
@use "station-order-list";
</style>
