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

  https://www.mall4j.com/

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

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j component-order-item">
    <view class="order-time-status">
      <view class="time">
        <text class="title">
          {{ $t('xiaDanShiJian-0') }}
        </text>
        <text class="text">
          {{ orderInfo.createTime }}
        </text>
      </view>
      <view class="status">
        {{ ['', $t('daiFuKuan'), $t('daiFaHuo'), $t('daiShouHuo'), '', $t('jiaoYiChengGong'), $t('jiaoYiShiBai'), $t('daiChengTuan')][orderInfo.status] }}
      </view>
    </view>
    <view class="order-number">
      <view class="title">
        {{ $t('dingDanBianHao') }}
      </view>
      <view class="text">
        {{ orderInfo.orderNumber }}
      </view>
      <view
        class="copy"
        @tap="copy"
      >
        {{ $t('fuZhi') }}
      </view>
    </view>
    <view class="line" />
    <view class="prod-box">
      <view
        v-for="(prodItem, index) in orderInfo.orderItems"
        :key="index"
        class="prod-item"
      >
        <view class="prod-common">
          <view class="prod-img-image">
            <img-show :src="prodItem.pic" />
          </view>
          <view class="prod-info">
            <view class="prod-name-price">
              <view class="name">
                {{ prodItem.prodName }}
              </view>
              <view class="price">
                ￥<text class="price-big">
                  {{ parsePrice(prodItem.price)[0] }}
                </text>{{ '.' + parsePrice(prodItem.price)[1] }}
              </view>
            </view>
            <view class="prod-sku">
              <view
                v-if="prodItem.skuName"
                class="sku-name"
              >
                {{ prodItem.skuName }}
              </view>
              <view class="total">
                {{ '×' + prodItem.prodCount }}
              </view>
              <view
                v-if="orderInfo.status === 1"
                class="btn"
                @tap="editAmount(index)"
              >
                {{ $t('xiuGaiJinE') }}
              </view>
            </view>
            <view class="prod-stutus">
              <view
                v-if="orderInfo.orderType !== 0"
                class="prod-type-item"
              >
                {{ ['', $t('tuanGou'), $t('miaoSha')][orderInfo.orderType] }}
              </view>
              <view
                v-if="orderInfo.orderMold === 1"
                class="prod-type-item"
              >
                {{ $t('xuNi') }}
              </view>
              <view
                v-if="orderInfo.orderMold === 3"
                class="prod-type-item"
              >
                {{ $t('dianZiKaQuan') }}
              </view>
              <view
                v-if="prodItem.platformInterventionStatus && prodItem.platformInterventionStatus!==-1"
                class="prod-stutus-item"
              >
                <!-- 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功 -->
                {{
                  [
                    "",
                    $t('pingTaiJieRuZhong'),
                    $t('pingTaiJieRuZhong'),
                    $t('tuiKuanGuanBi'),
                    '',
                    $t('tuiKuanChengGong')
                  ][prodItem.platformInterventionStatus]
                }}
              </view>
              <view
                v-else-if="prodItem.returnMoneySts && prodItem.returnMoneySts > 0"
                class="prod-stutus-item"
              >
                {{ orderStatus[prodItem.returnMoneySts < 5 ? 1 : prodItem.returnMoneySts + ''] }}
              </view>
              <view
                v-if="orderInfo.dvyType === 2 || orderInfo.dvyType === 4"
                class="prod-stutus-item"
              >
                {{ orderInfo.dvyType === 2 ? $t('ziTi') : $t('tongChengPeiSong') }}
              </view>
              <view
                v-if="!!prodItem.preSellTime"
                class="rep-sell-timer"
                style="display: inline-block;"
              >
                <view
                  v-if="true"
                  class="prod-type-item"
                >
                  {{ $t('yuShou') }}
                </view>
                <text class="time-txt">
                  {{ $t('yuJiPreselltimeFaHuo').replace('[preSellTime]', preSellTimeShowHandler(prodItem.preSellTime)) }}
                </text>
              </view>
            </view>
          </view>
        </view>
        <!-- 组合 -->
        <view
          v-if="prodItem.comboList && prodItem.comboList.length > 0"
          class="prod-gift"
        >
          <combo-list
            :combo-list="prodItem.comboList"
          />
        </view>
        <!-- 赠品 -->
        <view
          v-if="prodItem.giveawayList && prodItem.giveawayList.length > 0"
          class="prod-gift"
        >
          <combo-list
            :combo-list="prodItem.giveawayList"
            :tag-name="`【${$t('zengPin')}】`"
          />
        </view>
      </view>
    </view>
    <view class="line bottom" />
    <view class="footer">
      <text class="footer-text">
        {{ $t('gongProductnumsJianShiShou').replace('[productNums]', orderInfo.productNums) }}<text v-if="orderInfo.actualTotal">
          ￥
        </text>
        <text
          v-if="orderInfo.actualTotal"
          class="price"
        >
          {{ orderInfo.actualTotal }}
        </text>
        <text
          v-if="orderInfo.actualTotal && orderInfo.score"
          :decode="true"
          class="price plus"
        >
          +
        </text>
        <text
          v-if="orderInfo.score"
          class="price"
        >
          {{ orderInfo.score }} {{ $t('jiFen-0') }}
        </text>
      </text>
      <view class="footer-btn">
        <view
          v-if="isAuthorities('order:get:info')"
          class="btn-default"
          @tap="orderDetail"
        >
          {{ $t('chaKanXiangQing') }}
        </view>
        <view
          v-if="isAuthorities('order:virtual:update') && (orderInfo.orderMold == 1 && (orderInfo.status === 3 || orderInfo.status === 5) && (!orderInfo.refundStatus || orderInfo.refundStatus > 2) && orderInfo.writeOffCodes && orderInfo.writeOffCodes.length > 0) && orderInfo.writeOffNum !== 0
            && orderInfo.writeOffStatus !== 1"
          class="btn-default btn-primary btn"
          @tap="pickUpGoods()"
        >
          {{ $t('heXiao') }}
        </view>
        <view
          v-if="isAuthorities('admin:station:orderItemsDelivery') && (orderInfo.status === 2 && orderInfo.dvyType === 2)"
          class="btn-default btn-primary btn"
          @tap="pickUpGoods()"
        >
          {{ $t('tiHuo') }}
        </view>
        <view
          v-if="isAuthorities('order:delivery:update') && (orderInfo.status === 3 && (!orderInfo.refundStatus || orderInfo.refundStatus > 2) &&
            orderInfo.isOnlineDelivery === 0)"
          class="btn-default btn-primary"
          @tap="editLogistics(orderInfo.orderNumber)"
        >
          {{ $t('xiuGaiWuLiu') }}
        </view>
        <view
          v-if="isAuthorities('order:delivery:orderItemsDelivery') && (orderInfo.status === 2 && orderInfo.dvyType !== 2 && orderInfo.orderMold !== 1)"
          class="btn-default btn-primary"
          @tap="toShipping"
        >
          {{ $t('quFaHuo') }}
        </view>
      </view>
    </view>
    <!-- 提货或核销弹窗 -->
    <uni-popup
      ref="pickUpPopupRef"
      background-color="#fff"
      :is-mask-click="false"
      class="pop-mask"
    >
      <view class="popup">
        <view class="title-box">
          <text class="title">
            {{ orderInfo.orderMold === 1 ? $t('dingDanHeXiao') : $t('dingDanTiHuo') }}
          </text>
          <view
            class="close"
            @tap="pickUpClose"
          />
        </view>
        <view class="input-con">
          <input
            v-model="writeOffCode"
            class="input"
            type="text"
            :placeholder="orderInfo.orderMold === 1 ? $t('qingShuRuHeXiaoMaHeXiao') : $t('qingShuRuTiHuoMaTiHuo')"
            placeholder-class="placeholder-class"
          >
        </view>
        <view
          class="btn"
          @tap="codeClick"
        >
          {{ orderInfo.orderMold === 1 ? $t('heXiao-0') : $t('tiHuo') }}
        </view>
        <view class="footer">
          {{ orderInfo.orderMold === 1 ? $t('buShuRuHeXiaoMaMoRenWeiWuXuXiaoYanZhiJieHeXiao') : $t('buShuRuTiHuoMaMoRenWeiWuXuXiaoYanZhiJieTiHuo') }}
        </view>
      </view>
    </uni-popup>
    <!-- 修改金额弹窗 -->
    <uni-popup
      ref="AmountPopupRef"
      background-color="#fff"
      :is-mask-click="false"
      class="pop-mask"
    >
      <view class="popup">
        <view class="title-box">
          <text class="title">
            {{ $t('dingDanGaiJia') }}
          </text>
          <view
            class="close"
            @tap="amountClose"
          />
        </view>
        <view class="input-con">
          <view class="input-left">
            {{ $t('yongHuZhiFuJine') }}
          </view>
          <input
            v-model="actualTotal"
            class="input"
            type="number"
            :placeholder="$t('dangQianActualtotalYuan').replace('[actualTotal]', orderInfo.orderItems[i].actualTotal)"
            placeholder-class="placeholder-class"
            :disabled="orderInfo.orderItems[i].actualTotal < 0.01 && orderInfo.orderItems[i].useScore > 0"
            @blur="changeAmountPopup(chageAmount, 'chageAmount')"
          >
        </view>
        <view
          v-if="orderInfo.orderMold !== 3 "
          class="input-con amount-input-con"
        >
          <view :class="['input-left', orderInfo.orderMold === 1 || orderInfo.orderMold === 3 || orderInfo.dvyType === 2 || orderInfo.platformFreeFreightAmount ? 'disabled' : '']">
            {{ $t('yunFeiJine') }}
          </view>
          <input
            v-model="freightAmount"
            class="input"
            type="number"
            :placeholder="freightAmountPlace"
            placeholder-class="placeholder-class"
            :disabled="orderInfo.orderMold === 1 || orderInfo.orderMold === 3 || orderInfo.dvyType === 2 || orderInfo.platformFreeFreightAmount"
            :placeholder-style="orderInfo.orderMold === 1 || orderInfo.orderMold === 3 || orderInfo.dvyType === 2 ? 'color:#dcdde1' : ''"
            @blur="changeAmountPopup(freightAmount, 'freightAmount')"
          >
        </view>
        <view
          class="btn"
          @tap="amountClick"
        >
          {{ $t('queRen') }}
        </view>
        <view class="footer amount-footer">
          {{ $t('xiuGaiDingDanJinehuiJianShaoYongHuZhiFuDeJineQingJinShenGengGai') }}
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import util from '@/utils/util'
import Big from 'big.js'
import ComboList from '@/components/combo-list/combo-list.vue'

const { isAuthorities } = util

const emit = defineEmits(['refresh', 'updata:orderInfo'])
const props = defineProps({
  orderInfo: {
    type: Object,
    default () {
      return {}
    }
  }
})

const Data = reactive({
  writeOffCode: '', // 核销码
  chageAmount: null, // 减少订单金额
  freightAmount: '', // 运费
  actualTotal: null, // 实际支付
  dataList: [], // 修改金额参数
  i: 0, // 修改金额的当前索引
  dataForm: {}, // 提货数据
  orderStatus: { 1: $t('tuiKuanShenQingZhong'), 5: $t('tuiKuanChengGong'), 6: $t('shangJiaJuJue'), 7: $t('maiJiaCheHuiShenQing'), '-1': $t('tuiKuanGuanBi') },
  isSubmit: false
})

const { writeOffCode, chageAmount, freightAmount, i, orderStatus, actualTotal } = toRefs(Data)

const freightAmountPlace = computed(() => {
  if (props.orderInfo.platformFreeFreightAmount) {
    return $t('dangQianActualtotalYuan').replace('[actualTotal]', '0.00')
  } else {
    return $t('qingShuRuYunFeiJineDangQianFreightamountYuan').replace('[freightAmount]', props.orderInfo.freightAmount)
  }
})

const orderDetail = () => {
  uni.navigateTo({
    url: `/package-order/pages/order-detail/order-detail?orderNumber=${props.orderInfo.orderNumber}`
  })
}

const toShipping = () => {
  uni.removeStorageSync('bbcSelectedDelivery')
  uni.navigateTo({
    url: `/package-order/pages/order-shipping/order-shipping?orderNumber=${props.orderInfo.orderNumber}`
  })
}

// 复制文本
const copy = () => {
  util.uniCopy({
    content: props.orderInfo.orderNumber,
    success: (res) => {
      uni.showToast({
        title: res,
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}

const pickUpPopupRef = ref()
// 打开提货或核销弹窗
const pickUpGoods = () => {
  pickUpPopupRef.value.open()
  if (props.orderInfo.orderMold !== 1) {
    // 提货数据
    http.request({
      url: '/admin/station/getOrderItemAndStationInfo',
      method: 'get',
      data: {
        orderNumber: props.orderInfo.orderNumber
      }
    }).then(({ data }) => {
      Data.dataForm = data
    })
  }
}

// 关闭提货或核销弹窗
const pickUpClose = () => {
  pickUpPopupRef.value.close()
}

const changeAmountPopup = (value, type) => {
  if (!value) {
    value = '0'
  }
  if (value < 0.01 && value && type === 'freightAmount') {
    Data[type] = 0.01
  }
  if (type === 'chageAmount') { // 修改用户支付金额
    if (Data.actualTotal) {
      if (Data.actualTotal < 0) {
        Data.actualTotal = 0
      }
      value = new Big(props.orderInfo.orderItems[Data.i].actualTotal).minus(Data.actualTotal).round(2).toString()
    }
  }
  const re = /([0-9]+\.[0-9]{2})[0-9]*/
  Data[type] = value.replace(re, '$1')
}

// 确认提货或核销
const codeClick = () => {
  Data.writeOffCode = Data.writeOffCode.trim()
  if ((Data.writeOffCode !== Data.dataForm.stationCode && Data.writeOffCode) && props.orderInfo.orderMold !== 1) {
    uni.showToast({
      title: $t('tiHuoMaCuoWuQingShuRuZhengQueDeTiHuoMa'),
      icon: 'none'
    })
    return
  }
  // 核销
  const params = {
    url: '/admin/station/orderWriteOffByOrderNumber',
    method: 'put',
    data: {
      orderNumber: props.orderInfo.orderNumber,
      writeOffCode: Data.writeOffCode
    }
  }
  // 提货
  if (props.orderInfo.orderMold !== 1) {
    params.url = '/admin/station/changeStatusAndOrderStation'
    params.data = {
      orderNumber: Data.dataForm.orderNumber,
      stationId: Data.dataForm.stationId
    }
  }
  http.request(params).then(() => {
    uni.showToast({
      title: $t('caoZuoChengGong-0'),
      icon: 'none',
      success: () => {
        Data.writeOffCode = ''
        pickUpPopupRef.value.close()
        setTimeout(() => {
          emit('refresh')
        }, 500)
      }
    })
  })
}

// 修改物流信息
const editLogistics = (orderNumber) => {
  uni.navigateTo({
    url: `/package-order/pages/modify-logistics/modify-logistics?orderNumber=${orderNumber}`
  })
}

const AmountPopupRef = ref()
// 打开修改金额弹窗
const editAmount = (index) => {
  Data.i = index
  Data.actualTotal = props.orderInfo.orderItems[Data.i].actualTotal
  Data.freightAmount = props.orderInfo.freightAmount || ''
  Data.chageAmount = '0'
  AmountPopupRef.value.open()
}

// 关闭修改金额弹窗
const amountClose = () => {
  Data.isSubmit = false
  AmountPopupRef.value.close()
}

// 确认修改金额
const amountClick = () => {
  if (Data.isSubmit) {
    return
  }
  if (!Data.chageAmount) {
    uni.showToast({
      title: $t('xiuGaiJinebuNengWeiKong'),
      icon: 'none'
    })
    return
  }
  if (Data.freightAmount < 0) {
    uni.showToast({
      title: $t('shuRuDeJinebiXuDaYu_0'),
      icon: 'none'
    })
    return
  }
  if ((props.orderInfo.orderItems[Data.i].actualTotal - parseFloat(Data.chageAmount)) < 0) {
    uni.showToast({
      title: $t('dingDanJinebiXuDaYu_0'),
      icon: 'none'
    })
    return
  }
  Data.isSubmit = true
  Data.dataList = props.orderInfo.orderItems
  Data.dataList[Data.i].chageAmount = Data.chageAmount
  http.request({
    url: '/order/order/changeAmount',
    method: 'put',
    data: {
      orderId: props.orderInfo.orderId,
      orderItems: Data.dataList,
      orderNumber: props.orderInfo.orderNumber,
      freightAmount: Data.freightAmount ? Data.freightAmount : props.orderInfo.freightAmount
    }
  }).then(() => {
    uni.showToast({
      title: $t('xiuGaiJinechengGong'),
      icon: 'none',
      success: () => {
        AmountPopupRef.value.close()
        Data.chageAmount = null
        Data.freightAmount = ''
        setTimeout(() => {
          Data.isSubmit = false
          emit('refresh')
        }, 500)
      }
    })
  }).catch(() => {
    Data.isSubmit = false
  })
}

const parsePrice = (price) => {
  if (price.toString().indexOf('.') > -1) {
    return price.toString().split('.')
  }
  return [price]
}
/**
 * 预售时间显示为 'MM-DD'
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  const timerArr = val.slice(0, -8).trim().split('-')
  return timerArr[1] + '-' + timerArr[2]
}
</script>

<style lang="scss" scoped>
.component-order-item {
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  line-height: 34rpx;
  margin-bottom: 20rpx;

  .price {
    font-size: 24rpx;
    font-weight: bold;
  }

  .price.plus {
    padding: 0 10rpx;
    font-weight: normal;
  }

  .order-time-status {
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;

    .time {
      .title {
        color: #999999;
      }
    }

    .status {
      color: #082ba6;
    }
  }

  .order-number {
    margin-top: 10rpx;
    display: flex;
    align-items: center;
    font-size: 24rpx;
    line-height: 34rpx;

    .title {
      color: #999999;
    }

    .copy {
      margin-left: 10rpx;
      width: 72rpx;
      height: 32rpx;
      background: #ffffff;
      border: 2rpx solid #dddddd;
      opacity: 1;
      text-align: center;
      border-radius: 20rpx;
      font-size: 20rpx;
    }
  }

  .line {
    margin-top: 30rpx;
    margin-bottom: 28rpx;
    border-bottom: 2rpx dashed #dddddd;
  }

  .line.bottom {
    margin-bottom: 30rpx;
  }

  .prod-box {
    display: flex;
    flex-direction: column;

    .prod-item {
      display: flex;
      margin-bottom: 10px;
      flex-direction: column;

      .prod-common {
        display: flex;

        .prod-img-image {
          width: 140rpx;
          height: 140rpx;
          border-radius: 10rpx;
        }

        .prod-info {
          display: flex;
          flex-direction: column;
          margin-left: 16rpx;
          width: 530rpx;

          .prod-name-price {
            display: flex;
            justify-content: space-between;
            line-height: 40rpx;

            .name {
              font-size: 28rpx;
              width: 358rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .price-big {
              font-size: 32rpx;
            }
          }

          .prod-sku {
            display: flex;
            justify-content: space-between;
            font-size: 24rpx;
            color: #999999;
            line-height: 32rpx;
            margin-top: 10rpx;

            .sku-name {
              max-width: 60%;
            }

            .btn {
              display: inline-block;
              font-size: 20rpx;
              color: #082ba6;
              margin-left: 10rpx;
            }
            .total{
              margin-left: auto;
            }
          }

          .prod-stutus {
            .prod-stutus-item {
              display: inline-block;
              margin-top: 18rpx;
              margin-right: 10rpx;
              padding: 2rpx 6rpx;
              font-size: 20rpx;
              line-height: 14px;
              background-color: #ECF0FF;
              color: #082ba6;
              // border: 2rpx solid #ECF0FF;
              border-radius: 4rpx;
            }

            .prod-type-item {
              display: inline-block;
              margin-top: 18rpx;
              margin-right: 10rpx;
              line-height: 14px;
              padding: 2rpx 6rpx;
              font-size: 20rpx;
              color: #fff;
              background-color: #082ba6;
              // border: 2rpx solid #082ba6;
              border-radius: 4rpx;
            }
            .rep-sell-timer {
              .time-txt{
                font-size: 20rpx;
                color: #082ba6;
              }
            }
          }
        }

        &:last-child {
          margin-bottom: 0;
        }
      }

      .prod-gift {
        padding: 10rpx 0 0 135rpx;
      }
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .footer-text {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 24rpx;
    }

    .footer-btn {
      display: flex;
      justify-content: flex-end;

      .btn-default {
        display: inline-block;
        font-size: 24rpx;
        padding: 14rpx 28rpx 12rpx;
        border: 2rpx solid #dddddd;
        border-radius: 32rpx;
      }

      .btn-primary {
        border: 2rpx solid #082ba6;
        color: #082ba6;
      }

      .btn-default+.btn-default {
        margin-left: 20rpx;
      }

      .btn {
        text-align: center;
        width: 96rpx;
      }
    }
  }

  .pop-mask {
    .popup {
      width: 590rpx;
      .title-box {
        position: relative;
        height: 138rpx;

        .title {
          position: absolute;
          top: 30rpx;
          left: 50%;
          transform: translate(-50%, 0);
          font-size: 28rpx;
          font-weight: bold;
        }

        .close {
          position: absolute;
          top: 30rpx;
          right: 0;
          transform: translate(-50%, 0);
          width: 36rpx;
          height: 36rpx;
          line-height: 32rpx;
          background-color: #F5F5F5;
          border-radius: 50%;
          font-size: 20rpx;
          text-align: center;
          color: #999999;
        }

        .close::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 14rpx;
          height: 14rpx;
          background: url(~@/static/images/close.png) no-repeat;
          background-size: 14rpx 14rpx;
        }
      }

      .input-con {
        margin: auto;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
        height: 64rpx;
        width: 100%;
        border-radius: 4rpx;
        box-sizing: border-box;

        :deep(.placeholder-class) {
          font-size: 28rpx;
        }

        .input {
          background: #F7F8FA;
          height: 64rpx;
          font-size: 24rpx;
          width: 100%;
          padding-left: 20rpx;
        }

        :deep(.placeholder-class) {
          color: #999999;
        }
      }

      .input-left {
        font-size: 28rpx;
        font-weight: 400;
        flex-basis: auto;
        white-space: nowrap;
        &.disabled {
          color: #999;
        }
      }

      .amount-input-con {
        margin-top: 30rpx;
      }

      .btn {
        background: #082BA6;
        margin: 40rpx auto auto;
        width: calc(100% - 60rpx);
        height: 70rpx;
        text-align: center;
        font-size: 26rpx;
        color: #FFFFFF;
        padding: 14rpx 28rpx 12rpx;
        border: 2rpx solid #dddddd;
        border-radius: 70rpx;
        box-sizing: border-box;
      }

      .footer {
        display: flex;
        font-size: 24rpx;
        color: #999999;
        justify-content: center;
        margin: 28rpx 0 60rpx 0;
      }

      .amount-footer {
        margin-top: 20rpx;
      }

      :deep(.modify-logistics) {
        .logistics {
          margin-top: 0;
        }
      }
    }
  }

  ::v-deep(.uni-popup__wrapper) {
    border-radius: 10rpx;
  }
}
</style>
