<template>
  <!--pages/order-detail/order-detail.wxml-->
  <view class="container page-order-detail">
    <view class="order-detail">
      <!-- 订单状态 -->
      <view class="order-status">
        <view class="status-bg">
          <image src="/static/images/icon/status-bg.png" />
        </view>
        <view class="status-text">
          {{ ['','等待买家支付','等待商家发货','等待买家收货','订单已完成','订单已完成','订单已取消','正在拼团中','待使用'][status] }}
        </view>
        <view class="step">
          <view :class="['item',status===2 || status === 3 || (status === 6 && orderItems[0].refundSn) || status===4 || status===5|| status===8 ? 'active' : '']">
            <view class="select" />
            <view class="des">
              买家付款
            </view>
          </view>

          <view
            v-if="dvyType === 2"
            :class="['item',status===3 || status===4 || status===5 ? 'active' : '']"
          >
            <view class="select" />
            <view class="des">
              买家提货
            </view>
          </view>
          <view :class="['item',status===4||status===5 ? 'active' : '']">
            <view class="select" />
            <view class="des">
              交易完成
            </view>
          </view>
        </view>
      </view>
      <!-- 商品信息 -->
      <view class="prod-item">
        <!-- 店铺 -->
        <view class="shop-box">
          <view class="shop-icon">
            <image src="/static/images/icon/shop.png" />
          </view>
          <view class="shop-name">
            {{ shopName }}
          </view>
          <view
            v-if="refundStatus !==0"
            class="refund-sts"
          >
            <!-- refundStatus 订单退款状态 1.申请退款 2.退款完成 3.部分退款完成 4.退款失败 -->
            <text>{{ ['','退款中','退款完成','部分退款','退款关闭'][refundStatus] }}</text>
          </view>
        </view>
        <!-- /店铺 -->
        <view
          v-for="(item, spuId) in prodList"
          :key="spuId"
          class="prod-box"
        >
          <view
            class="item-cont"
            :data-prodid="item.spuId"
            @tap="onToProdPage"
          >
            <view class="prod-pic">
              <image
                v-if="item.pic"
                :src="item.pic.indexOf('http') === -1 ? picDomain + item.pic : item.pic"
                @error="item.pic = ''"
              />
              <image
                v-else
                src="/static/images/icon/def.png"
              />
            </view>
            <!-- 拼团商品展示icon -->
            <view class="prod-info">
              <view class="prodname">
                <view
                  v-if="orderType"
                  class="a-icon"
                >
                  {{ ['','拼团','秒杀','积分'][orderType] }}
                </view>
                <view class="text">
                  {{ item.spuName }}
                </view>
              </view>
              <view class="sku-name">
                <text
                  v-if="orderItems.length === 1 && item.giveawayOrderItemId"
                  class="gift-icon"
                >
                  赠品
                </text>
                <text>{{ item.skuName }}</text>
              </view>
              <view class="price-nums">
                <view class="prodprice">
                  <text
                    v-if="item.price"
                    class="symbol"
                  >
                    ￥
                  </text>
                  <text
                    v-if="item.price"
                    class="big-num"
                  >
                    {{ wxs.parsePrice(item.price)[0] }}
                  </text>
                  <text
                    v-if="item.price"
                    class="small-num"
                  >
                    .{{ wxs.parsePrice(item.price)[1] }}
                  </text>
                  <text
                    v-if="item.price && orderType===3"
                    class="small-num"
                  >
                    +
                  </text>
                  <text
                    v-if="orderType===3"
                    class="small-num"
                  >
                    {{ item.useScore }} 积分
                  </text>
                </view>
                <view class="number">
                  <text>{{ orderMold === 1 ? totalNum : item.count }}</text>件
                </view>
              </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="order-msg">
        <view class="msg-item">
          <view class="item">
            <text class="item-tit">
              订单编号：
            </text>
            <text class="item-txt">
              {{ orderNumber }}
            </text>
            <!--  #ifdef  APP-PLUS -->
            <text
              class="copy-btn"
              @tap="onCopyBtn"
            >
              复制
            </text>
          <!--  #endif -->
          </view>
          <view class="item">
            <text class="item-tit">
              下单时间：
            </text>
            <text class="item-txt">
              {{ createTime }}
            </text>
          </view>
        </view>
        <view class="msg-item">
          <view
            v-if="payType !== null"
            class="item"
          >
            <text class="item-tit">
              支付方式：
            </text>
            <text class="item-txt">
              {{ ['积分支付','微信支付','支付宝支付','微信支付','微信支付','微信支付','支付宝支付','支付宝支付','微信支付','余额支付','PayPal支付'][payType] }}
            </text>
          </view>
          <view class="item">
            <text class="item-tit">
              配送方式：
            </text>
            <text class="item-txt">
              {{ ['卖家配送','卖家配送','到店自提','无需快递'][dvyType] }}
            </text>
          </view>
          <!-- 全部留言（虚拟商品） -->
          <view
            v-if="orderMold === 1 && virtualRemarkList.length >= 0"
            class="item all-msg"
            @tap="onShowViewMsgPopup"
          >
            <view class="item-tit">
              全部留言：
            </view>
            <view
              class="item-txt"
              :class="{'pd': isExtraLong}"
            >
              <span
                v-for="(item, index) in virtualRemarkList"
                :key="index"
              >{{ item[0] }}&nbsp;&nbsp;&nbsp;&nbsp;{{ item[1] }}</span>
            </view>
            <view
              v-if="isExtraLong"
              class="more-msg"
            />
          </view>
        </view>
        <view
          v-if="remarks"
          class="msg-item"
        >
          <view class="item">
            <text class="item-tit remarks-tit">
              订单备注：
            </text>
            <text class="item-txt remarks-txt">
              {{ remarks }}
            </text>
          </view>
        </view>
      </view>

      <!-- 虚拟商品-券码情况 -->
      <view
        v-if="orderMold === 1"
        class="order-msg voucher-code-con"
      >
        <view class="msg-item">
          <view class="item">
            <view class="item-left">
              <!-- 待使用/未使用 (unusedCount待使用的核销券) -->
              <view
                v-if="unusedCount && status !== 6&&orderMold===1"
                class="txt strong"
              >
                {{ (isExpired?'已过期':'待使用') + '（' + unusedCount+'张）' }}
              </view>
              <!-- 确认收货(已完成) & 没有待核销的券码 -->
              <view
                v-if="status === 5 && !unusedCount&&orderMold===1"
                class="txt strong"
              >
                {{ '已使用（' + orderItems[0].count + '张）' }}
              </view>
              <!-- 退款成功 -->

              <!-- 优惠券待使用 -->
              <view
                v-if="orderMold===2&& status !== 5"
                class="txt strong"
              >
                {{ (isExpired?'已过期':'待使用') + '（' + couponUnusedCount+'张）' }}
              </view>
              <view
                v-if="status === 5 && orderMold === 1 && unusedCount"
                class="txt strong"
              >
                {{ '已使用（' + (virtualInfoList.length - couponUnusedCount) + '张）' }}
              </view>
              <view class="txt weak flex-item">
                <view class="lf">
                  有效期限：
                </view>
                <view class="rg">
                  <text v-if="writeOffStart && !writeOffEnd">
                    购买后长期有效
                  </text>
                  <text v-if="writeOffStart && writeOffEnd">
                    {{ writeOffStart }} 至 {{ writeOffEnd }}
                  </text>
                </view>
              </view>
              <view
                v-if="orderMold === 1"
                class="txt weak flex-item"
              >
                <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>
        </view>
        <!-- 券码列表 -->
        <view
          v-if="virtualInfoList && virtualInfoList.length"
          class="msg-item voucher-code-list"
        >
          <view
            v-for="(item, index) in virtualInfoList"
            :key="index"
            class="item"
            :class="{'used': item.isWriteOff === 1 || status === 6||item.status===2}"
          >
            <view class="code-row">
              <text>券码</text>
              <text v-if="virtualInfoList.length > 1">
                {{ index+1 }}
              </text>：
              <text class="code">
                {{ item.writeOffCode }}
              </text>
            </view>
            <view
              v-if="item.isWriteOff === 1||item.status===2"
              class="tips"
            >
              已使用
            </view>
            <view
              v-if="(item.isWriteOff === 0 && status !== 6)||item.status===1"
              class="copy-btn2"
              @tap="copyText(item.writeOffCode)"
            >
              复制
            </view>
          </view>
        </view>
      </view>

      <view class="order-msg payment">
        <view class="msg-item">
          <view class="item">
            <view class="item-tit">
              商品总额：
            </view>
            <view class="item-txt">
              ￥{{ wxs.parsePrice(productTotalAmount)[0] }}.{{ wxs.parsePrice(productTotalAmount)[1] }}
            </view>
          </view>
          <view
            v-if="transfee"
            class="item"
          >
            <view class="item-tit">
              运费：
            </view>
            <view class="item-txt">
              ￥{{ wxs.parsePrice(transfee)[0] }}.{{ wxs.parsePrice(transfee)[1] }}
            </view>
          </view>
          <view
            v-if="reduceAmount"
            class="item"
          >
            <view class="item-tit">
              <text
                v-if="orderType && orderType!==3"
                class="item-tit"
              >
                {{ orderType===1?'团购':'秒杀' }}
              </text>优惠：
            </view>
            <view class="item-txt">
              -￥{{ wxs.parsePrice(reduceAmount)[0] }}.{{ wxs.parsePrice(reduceAmount)[1] }}
            </view>
          </view>
          <view class="item price">
            <view class="item-tit">
              订单总额：
            </view>
            <view class="item-txt">
              <text
                v-if="actualTotal && actualTotal > 0"
                class="symbol"
              >
                ￥
              </text>
              <text
                v-if="actualTotal && actualTotal > 0"
                class="big-num"
              >
                {{ wxs.parsePrice(actualTotal)[0] }}
              </text>
              <text
                v-if="actualTotal && actualTotal > 0 || actualTotal > 0"
                class="small-num"
              >
                .{{ wxs.parsePrice(actualTotal)[1] }}
              </text>
              <text
                v-if="(actualTotal && actualTotal > 0) && (orderType===3 || orderScore > 0)"
                class="small-num"
              >
                +
              </text>
              <text
                v-if="orderType===3 || orderScore > 0"
                class="big-num"
              >
                {{ orderScore }} <text class="small-num">
                  积分
                </text>
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view
      class="popup-hide"
      :hidden="!showViewMsg"
    >
      <view class="popup-box virtual-goods-msg-pop">
        <view class="con-tit">
          <view class="tit-text">
            查看留言
          </view>
          <view
            class="close"
            @tap="onCloseMsgPopup"
          />
        </view>
        <view class="msg-pop-con">
          <view class="msg-list">
            <view
              v-for="(item, index) in virtualRemark"
              :key="index"
              class="msg-item"
            >
              <view class="item-con weak">
                {{ item.name }}
              </view>
              <view class="item-con">
                {{ item.value }}
              </view>
            </view>
          </view>
          <view class="pop-foot">
            <view
              class="foot-btn"
              @tap="onCloseMsgPopup"
            >
              我知道了
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
const wxs = number()
// 图片地址
const picDomain = import.meta.env.VITE_APP_RESOURCES_URL
/**
 * 生命周期函数--监听页面加载
 */
const refundStatus = ref(0) // 退款状态
onLoad((options) => {
  onLoadOrderDetail(options.orderNum)
  refundStatus.value = options.refundStatus
})

// 跳转商品详情页
const onToProdPage = (e) => {
  const prodid = e.currentTarget.dataset.prodid

  if (orderType.value === 3) {
    uni.navigateTo({
      url: '/pages/convertProdDet/convertProdDet?prodid=' + prodid
    })
  } else {
    uni.navigateTo({
      url: '/pages/prod/prod?prodid=' + prodid
    })
  }
}

/**
 * 加载订单数据
 */
const orderItems = ref([])
const remarks = ref('')
const actualTotal = ref(0)
const couponUnusedCount = ref(0)
const orderNumber = ref('')
const orderScore = ref(0) // 整单使用积分
const createTime = ref('')
const status = ref(0) // 订单状态 0全部 1待支付 2待发货 3待收货 4待评价 5已完成 6已取消 7拼团中
const productTotalAmount = ref('')
const transfee = ref('')
const reduceAmount = ref('')
const orderType = ref(0)
const shopName = ref('') // 店铺名称
const dvyType = ref(1) // 配送类型 1:快递 2:自提 3：无需快递
const payType = ref('') // 支付方式
const orderMold = ref('') // 订单类型 1虚拟商品
const virtualRemark = ref([]) // 留言
const virtualInfoList = ref([]) // 券码
const writeOffNum = ref(0)
const writeOffStart = ref(null)
const writeOffEnd = ref(null)
const totalNum = ref(null) // 已核销的商品总件数
const prodList = ref([]) // 商品列表
const onLoadOrderDetail = (orderNum) => {
  uni.showLoading() // 加载订单详情
  http.request({
    url: '/mall4cloud_order/my_order/order_detail',
    method: 'GET',
    data: {
      orderId: orderNum
    }
  }).then(({ data }) => {
    uni.hideLoading()
    // const couponUnusedCount = 0
    // data.couponUserList?.forEach(el => {
    //   el.status === 1 ? couponUnusedCount++ : null
    // })
    orderNumber.value = orderNum
    actualTotal.value = data.actualTotal
    remarks.value = data.remarks // 实际支付总额（商品总额+运费)
    orderItems.value = data.orderItems
    createTime.value = data.createTime
    status.value = data.status
    productTotalAmount.value = data.total
    transfee.value = data.transfee // 所有商品总额
    reduceAmount.value = data.reduceAmount // 运费
    orderType.value = data.orderType
    orderScore.value = data.orderScore // 整单使用积分
    shopName.value = data.shopName
    dvyType.value = data.deliveryType // 配送类型 1:快递 2:自提 3：无需快递
    payType.value = data.payType // 支付方式
    orderMold.value = data.orderMold // 订单类型 1虚拟商品
    virtualInfoList.value = data.virtualInfoList // 券码
    virtualRemark.value = data.orderItems[0].virtualRemark ? JSON.parse(data.orderItems[0].virtualRemark) : [] // 留言
    writeOffNum.value = data.writeOffNum // 核销次数 -1多次 0无需核销 1单次核销
    writeOffStart.value = data.writeOffStart // 核销有效期开始时间
    writeOffEnd.value = data.writeOffEnd // 核销有效期结束时间（仅有开始时间没有结束时间标识长期有效）
    totalNum.value = data.totalNum

    if (data.deliveryType === 2) {
      onLoadStationDetail(orderNum)
    }

    // 虚拟商品留言处理
    onHandlevirtualRemark()

    // 虚拟商品-待使用的券总数
    onHandleUnusedVirtualCode(data.virtualInfoList)

    prodList.value = data.orderItems
    // 赠品：单个商品时
    if (data.orderItems.length === 1 &&
             data.orderItems[0].giveawayList &&
             data.orderItems[0].giveawayList.length) {
      prodList.value = [...data.orderItems, ...data.orderItems[0].giveawayList]
    }
  }).catch(err => {
    uni.hideLoading()
    uni.showModal({
      title: '提示',
      content: err.data,
      showCancel: false,
      confirmText: '确定',
      success: (err) => {
        if (err.confirm) {
          uni.redirectTo({
            url: '/pages/order-list/order-list'
          })
        }
      }
    })
  })
}

// 虚拟商品-待使用的券总数
const unusedCount = ref(0)
const onHandleUnusedVirtualCode = (list) => {
  if (list && list.length) {
    let isnusedCount = 0
    list.forEach(el => {
      if (el.isWriteOff === 0) {
        isnusedCount = isnusedCount + 1
      }
    })
    unusedCount.value = isnusedCount
  }
}

/**
 * 加载订单详情自提信息
 */
const onLoadStationDetail = (orderNum) => {
  uni.showLoading() // 加载订单详情
  http.request({
    url: '/mall4cloud_order/my_station_order/station_detail',
    method: 'GET',
    data: {
      orderId: orderNum
    }
  }).then(() => {
    uni.hideLoading()
  })
}

// 虚拟商品-留言列表处理
const virtualRemarkList = ref([])
const isExtraLong = ref() // 虚拟商品留言是否超长
let virtualRemarks = []
const onHandlevirtualRemark = () => {
  if (virtualRemark.value && virtualRemark.value.length) {
    // 过滤掉没有填写的留言
    console.log(virtualRemark.value)
    virtualRemark.value = virtualRemark.value.filter(el => el.value)
    const isVirtualRemarkList = []
    // 如果留言总数大于3条，先展示前一条（完整留言在弹窗中展示）
    if (virtualRemark.value.length > 3) {
      const list = JSON.parse(JSON.stringify(virtualRemark.value))
      virtualRemarks = list.splice(0, 1)
      isExtraLong.value = true
    } else {
      virtualRemarks = virtualRemark.value
      isExtraLong.value = false
    }
    // 全部留言拼接
    virtualRemarks.forEach((el) => {
      isVirtualRemarkList.push([el.name, el.value])
    })
    if (isExtraLong.value) {
      virtualRemarkList.value = isVirtualRemarkList.push('......')
    } else {
      virtualRemarkList.value = isVirtualRemarkList
    }
  }
}

// 查看留言弹窗
const showViewMsg = ref() // 查看全部留言弹窗
const onShowViewMsgPopup = () => {
  if (isExtraLong.value) {
    showViewMsg.value = true
  }
}
const onCloseMsgPopup = () => {
  showViewMsg.value = false
}

// #ifdef  APP-PLUS
/**
 * 一键复制事件
 */
// 设置系统剪贴板的内容。
const onCopyBtn = () => {
  // 除了h5以外都可用的复制方法
  uni.setClipboardData({
    data: orderNumber.value,
    success: function () {
      uni.showToast({
        title: '复制成功',
        icon: 'none',
        duration: 1000
      })
    }
  })
}
// #endif

</script>
<style lang="scss" scoped>
@import "./order-detail.scss";
</style>
