<template>
  <view class="page-scan-pick">
    <!-- 提货人信息 -->
    <view
      v-if="isSelfPickup === 0 && (stationAddress || stationUserName || stationUserMobile)"
      class="personal-inf"
    >
      <view class="personal-inf-wrapper">
        <view class="pick-addr line">
          <view class="title">
            <text>提</text>
            <text>货</text>
            <text>地</text>
            <text>点：</text>
          </view>
          <view class="detail">
            {{ stationAddress }}
          </view>
        </view>
        <view class="pick-people line">
          <view class="title">
            <text>提</text>
            <text>货</text>
            <text>人：</text>
          </view>
          <view class="detail">
            {{ stationUserName }}
          </view>
        </view>
        <view class="pick-people line">
          <view class="title">
            <text>提</text>
            <text>货</text>
            <text>人</text>
            <text>号</text>
            <text>码：</text>
          </view>
          <view class="detail">
            {{ stationUserMobile }}
          </view>
        </view>
      </view>
    </view>
    <!-- 商品信息 -->
    <view
      v-if="orderList && orderList.length"
      class="commodity-inf"
    >
      <view class="commodity-inf-wrapper">
        <view class="title">
          <!-- <view class="icon"><image src=""></image></view> -->
          <view class="icon">
            <image src="/static/images/icon/shop.png" />
          </view>
          <view class="font">
            {{ shopName }}
          </view>
        </view>
        <view class="prod-box">
          <view
            v-for="(item, key) in orderList"
            :key="key"
            class="item-cont"
          >
            <view class="prod-detail">
              <view class="prod-img">
                <image
                  v-if="!item.isPicError && item.pic"
                  :src="item.pic.indexOf('http') === -1 ? picDomain + item.pic : item.pic"
                  @error="onHandlePicError(item)"
                />
                <image
                  v-else
                  src="/static/images/icon/def.png"
                />
              </view>
              <view class="prod-inf">
                <view class="prod-title">
                  {{ item.spuName }}
                </view>
                <view class="brief">
                  <text
                    v-if="orderItems.length === 1 && item.giveawayOrderItemId"
                    class="gift-icon"
                  >
                    赠品
                  </text>
                  <text class="sku-name">
                    {{ item.skuName }}
                  </text>
                </view>
                <view>
                  <text class="num">
                    ×{{ item.count }}
                  </text>
                  <text
                    v-if="item.stationStatus === 1"
                    class="sku-type"
                  >
                    已核销
                  </text>
                </view>
              </view>
            </view>

            <!-- 组合 -->
            <view
              v-if="item.comboItemList && item.comboItemList.length"
              class="gift-prods"
            >
              <view
                v-for="comboItem in item.comboItemList"
                :key="comboItem.orderItemId"
                class="gift-item"
              >
                <text class="name">
                  【组合】{{ comboItem.spuName }}
                </text>
                <text class="num">
                  ×{{ comboItem.count }}
                </text>
              </view>
            </view>
            <!-- / 组合 -->

            <!-- 赠品：多个商品时展示 -->
            <view
              v-if="orderItems.length > 1 && item.giveawayList && item.giveawayList.length"
              class="gift-prods"
            >
              <view
                v-for="giftItem in item.giveawayList"
                :key="giftItem.orderItemId"
                class="gift-item"
              >
                <text class="name">
                  【赠品】{{ giftItem.spuName }}
                </text>
                <text class="num">
                  ×{{ giftItem.count }}
                </text>
              </view>
            </view>
            <!-- / 赠品 -->
          </view>
        </view>
        <view class="total-box">
          <view class="total">
            <text>共{{ productNums }}件商品，合计：</text>
            <text
              v-if="actualTotal"
              class="red"
            >
              ￥{{ actualTotal }}
            </text><text v-if="useScore&&actualTotal">
              +
            </text><text
              v-if="useScore"
              class="red"
            >
              {{ useScore }} 积分
            </text>
          </view>
        </view>
      </view>
    </view>
    <!-- 券码列表(虚拟商品核销) -->
    <view
      v-if="isSelfPickup === 1 && orderVirtualInfoList.length"
      class="virtual-goods-code"
    >
      <view class="code-tit">
        即将核销（{{ orderVirtualInfoList.length }}张）
      </view>
      <view class="code-list">
        <view class="code-item date weak">
          <view class="lf">
            有效期限：
          </view>
          <view class="rg">
            <text v-if="writeOffStart && !writeOffEnd">
              永久有效
            </text>
            <text v-if="writeOffStart && writeOffEnd">
              {{ writeOffStart }} 至 {{ writeOffEnd }}
            </text>
          </view>
        </view>
        <view class="code-item date weak">
          <view class="lf">
            核销次数：
          </view>
          <view class="rg">
            <text v-if="writeOffNum === -1">
              多次核销
            </text>
            <text v-if="writeOffNum === 1">
              单次核销
            </text>
            <text v-if="writeOffNum === 0">
              无需核销
            </text>
          </view>
        </view>
      </view>
      <view class="code-list code-box">
        <view
          v-for="(item,index) in orderVirtualInfoList"
          :key="index"
          class="code-item"
        >
          券码<text v-if="orderVirtualInfoList.length > 1">
            {{ index+1 }}
          </text>：
          <text>{{ item.writeOffCode }}</text>
        </view>
      </view>
    </view>
    <!-- 全部留言(虚拟商品核销) -->
    <view
      v-if="!isSelfPickup && virtualRemark && virtualRemark.length"
      class="virtual-goods-code"
    >
      <view class="code-tit">
        全部留言
      </view>
      <view class="code-list">
        <view
          v-for="(item,index) in virtualRemark"
          :key="index"
          class="code-item weak"
        >
          {{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;{{ item.value }}
        </view>
      </view>
    </view>
    <!-- 订单备注 -->
    <view
      v-if="remarks"
      class="order-remarks"
    >
      <text class="remarks-title">
        订单备注：
      </text>
      <text class="remarks-txt">
        {{ remarks }}
      </text>
    </view>
    <!-- 提货按钮 -->
    <view
      v-if="!requestPageError"
      :class="['pick-btn']"
      @tap="pickGood"
    >
      {{ isSelfPickup===0 ? '确认取件' : '确认核销' }}
    </view>
  </view>
</template>

<script setup>
const picDomain = import.meta.env.VITE_APP_RESOURCES_URL // 图片地址
let pickCode = '' // 提货码
const shopName = ref('') // 店铺名称
const status = ref('') // 订单状态1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败
let orderNumber = '' // 订单号
const stationUserName = ref('') // 提货人名字
const stationUserMobile = ref('') // 提货人号码
const stationAddress = ref('') // 提货地点
const productNums = ref(0)// 订单商品总件数
const actualTotal = ref(0)// 订单总价
const useScore = ref(0) // 积分
const orderList = ref([]) // 订单的商品列表
const remarks = ref('') // 订单备注
let pageType = 1 // 1扫码 2手动输入核销码
const isSelfPickup = ref(0) // 是否自提
const orderVirtualInfoList = ref([]) // 虚拟商品
const couponUsers = [] // 优惠券
const virtualRemark = ref([]) // 虚拟商品-全部留言
const writeOffStart = ref(null) // 核销有效期
const writeOffEnd = ref(null)
const writeOffNum = ref(0) // 核销次数 -1多次 1单次 0无需
const requestPageError = ref(true) // 是否成功请求页面数据
let timer = ''
const orderItems = ref([])
/* 生命周期函数--监听页面加载 */
onLoad((options) => {
  // 拿到扫码得到的提货码
  if (options.pickCode) {
    pickCode = options.pickCode
  } else {
    uni.showModal({
      title: '提示',
      content: '该提货码，没有对应订单',
      showCancel: false,
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/index/index'
          })
        }
      }
    })
    return
  }
  // 进入页面类型：1扫码进入 2输入核销码进入
  pageType = Number(options.pageType)
})
/* 生命周期函数--监听页面显示 */
onShow(() => {
  if (pickCode) {
    onGetPickGoodInf()
  }
})
/**
 * 获取核销码信息
 */
const onGetPickGoodInf = () => {
  uni.showLoading()
  http.request({
    url: '/mall4cloud_order/station/get_station_order_by_code',
    method: 'GET',
    data: {
      code: pickCode
    }
  }).then(({ data }) => {
    if (Object.keys(data).length > 0) {
      // 自提
      if (data.orderSelfStationVO) {
        stationUserName.value = data.orderSelfStationVO.stationUserName
        stationUserMobile.value = data.orderSelfStationVO.stationUserMobile
        stationAddress.value = data.orderSelfStationVO.stationAddress
        isSelfPickup.value = 0
      }
      // 虚拟商品核销
      if (data.orderVirtualInfoList) {
        isSelfPickup.value = 1
        orderVirtualInfoList.value = data.orderVirtualInfoList
        virtualRemark.value = data.virtualRemark ? JSON.parse(data.virtualRemark) : []
        writeOffStart.value = data.writeOffStart
        writeOffEnd.value = data.writeOffEnd
        writeOffNum.value = parseInt(data.writeOffNum)
        if (virtualRemark.value && virtualRemark.value.length) {
          virtualRemark.value = virtualRemark.value.filter(el => el.value)
        }
        // 处理从输入核销码页面输入订单号进入的情况
        if (!orderVirtualInfoList.value.find(el => el.writeOffCode === pickCode) && pickCode === data.orderNumber && pageType === 2) {
          pageType = 1
        }
      }
      data.orderItems.forEach(item => {
        useScore.value += item.useScore
      })
      shopName.value = data.shopName
      status.value = data.status
      orderNumber = data.orderId
      productNums.value = data.allCount
      actualTotal.value = data.actualTotal / 100
      orderItems.value = data.orderItems
      remarks.value = data.remarks
      requestPageError.value = false

      orderList.value = data.orderItems
      // 处理单个商品时，有赠品的商品列表
      if (data.orderItems && data.orderItems.length === 1 && data.orderItems[0].giveawayList && data.orderItems[0].giveawayList.length
      ) {
        orderList.value = [...data.orderItems, ...data.orderItems[0].giveawayList]
      }
    } else {
      requestPageError.value = true
      uni.showModal({
        title: '提示',
        content: '没有该货物信息，请确认登录账号是否正确',
        showCancel: false,
        confirmText: '确定',
        success: (data) => {
          if (data.confirm) {
            uni.redirectTo({
              url: '/pages/index/index'
            })
          }
        }
      })
    }
    uni.hideLoading()
  }).catch(err => {
    uni.hideLoading()
    requestPageError.value = true
    uni.showModal({
      title: '提示',
      content: err.msg,
      showCancel: false,
      confirmText: '确定',
      success: (err) => {
        if (err.confirm) {
          uni.redirectTo({
            url: '/pages/index/index'
          })
        }
      }
    })
  })
}

/**
 * 确认核销
 */
const pickGood = () => {
  if (requestPageError.value) {
    return
  }
  let title = ''
  // 1、自提商品购买后取货前状态是status==2
  // 2、虚拟商品购买后核销前状态是status==3(确认收货即状态5已完成，未核销的券码仍然可以核销)
  if ((isSelfPickup.value === 0 && status.value === 2) || (isSelfPickup.value === 1 && (status.value === 3 || status.value === 5 || status.value === 8)) || (isSelfPickup.value === 2 && couponUsers[0].status.value === 1)) {
    const url = isSelfPickup.value === 0 ? '/mall4cloud_order/station/order_station_by_order_id' : '/mall4cloud_order/station/order_write_off_by_order_id'
    const code = isSelfPickup.value === 0 ? orderNumber : { orderId: orderNumber }
    // 虚拟商品输入核销码核销单个券码时再传writeOffCode，扫码进入无需传writeOffCode
    if (pageType === 2 && isSelfPickup.value !== 0) {
      code.writeOffCode = pickCode
    }
    uni.showModal({
      title: '提示',
      content: !isSelfPickup.value ? '是否确认取件' : '是否确认核销',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          uni.showLoading()
          http.request({
            url,
            method: 'PUT',
            data: code
          }).then(() => {
            uni.showToast({
              title: isSelfPickup.value === 0 ? '取件成功' : '核销成功',
              icon: 'success'
            })
            timer = setTimeout(() => {
              uni.redirectTo({
                url: '/pages/index/index'
              })
            }, 800)
            uni.hideLoading()
          }).catch(err => {
            uni.showToast({
              title: err.data.msg,
              icon: 'none'
            })
            uni.hideLoading()
          })
        }
      }
    })
  } else {
    if (status.value === 1) {
      title = !isSelfPickup.value ? '订单待支付,请支付后再来取货' : '订单待支付,请先完成支付'
    } else if ((!isSelfPickup.value && (status.value === 3 || status.value === 5)) || status.value === 4 || (isSelfPickup.value === 2 && couponUsers[0].status.value === 2)) {
      title = !isSelfPickup.value ? '订单已取货' : '订单已核销'
    } else if (status.value === 6) {
      title = '订单已取消'
    } else if (status.value === 7) {
      title = '订单未成团，不支持核销'
    }
    uni.showModal({
      title: '提示',
      content: title,
      showCancel: false,
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          uni.redirectTo({
            url: '/pages/index/index'
          })
        }
      }
    })
  }
}

/**
 * 图片加载失败时显示默认图片
 */
const onHandlePicError = (item) => {
  item.isPicError = true
}

onUnload(() => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
})
</script>

<style lang="scss" scoped>
@import "./scan-pick.scss";

</style>
