<template>
  <view class="pt-24rpx">
    <u-navbar :custom-back="goJump">
      <view slot="right" class="flex items-center">
          <!-- #ifndef  MP-WEIXIN -->
        <view class="px-18rpx relative" @tap="$u.route(`/pages/web_view/index?url=${service}`)">
          <u-icon name="kefu-ermai" color="#000" size="48"></u-icon>
        </view>
        <!-- #endif -->
        <!-- #ifdef  MP-WEIXIN -->
        <button class="px-18rpx relative cu-btn" open-type="contact" hover-class="none">
          <u-icon name="kefu-ermai" color="#000" size="48"></u-icon>
        </button>
        <!-- #endif -->
      </view>
      <view class="text-center w-full pr-88rpx">
        <block v-if="detail.status >= 0">
          <view class="text-lg font-medium">{{ detail.status | payStatusText }}</view>
          <view class="text-xs" v-if="detail.status == 0">
            <u-count-down :timestamp="detail.expires_at" font-size="20" separator="zh" separator-size="20" @end="onCountEnd"></u-count-down>
          </view>
        </block>
        <view v-else class="text-lg font-medium">订单详情</view>
      </view>
    </u-navbar>
    <loading-view v-if="isFirstLoading"></loading-view>
    <block v-if="(detail.status == 2 || detail.status == 3 || detail.status == 9) && !!detail.consignee_address">
      <block v-if="detail.packages == null">
        <view class="bg-white rounded-xs flex h-200rpx items-center justify-center mb-24rpx"> 暂无物流信息 </view>
      </block>
      <block v-else>
        <view class="bg-white rounded-xs flex mb-24rpx" @tap="$u.route('/pages/my_package/index', { id: detail.id })">
          <view class="flex-1 py-base px-40rpx w-0">
            <!-- <view class="line-1 text-black text-36rpx font-medium">
              {{detail.packages.last_news?detail.packages.last_news:'暂无最新物流信息'}}
            </view> -->
            <view class="text-lg py-4rpx mt-18rpx">物流公司：{{ detail.packages.shipping_company }}</view>
            <view class="text-lg py-4rpx">物流单号：{{ detail.packages.shipping_number }}</view>
          </view>
          <view class="flex items-center">
            <view class="text-lg mr-10rpx">查看物流</view>
            <u-icon name="arrow-right" class="pr-30rpx" color="#808080" size="38"></u-icon>
          </view>
        </view>
      </block>
    </block>

    <view class="bg-white rounded-xs py-base px-40rpx" v-if="!!detail.consignee_address">
      <view class="flex items-center text-black">
        <text>{{ detail.consignee_zone }}</text>
      </view>
      <view class="text-xl text-black my-14rpx"> {{ detail.consignee_address }} </view>
      <view class="text-lg text-black"> {{ detail.consignee_name }} {{ detail.consignee_telephone }} </view>
    </view>
    <view class="bg-white rounded-xs mt-24rpx py-base px-40rpx">
      <!-- <view class="text-xl">商家名称</view> -->
      <block v-for="(item, index) in products" :key="item.id">
        <view @tap="$u.routeAuth('/pages/product_details/index', { skuId: item.sku_id })" class="mb-base">
          <view class="flex">
            <u-image border-radius="10" width="190rpx" height="190rpx" :src="item.cover" :lazy-load="true"></u-image>
            <view class="flex-1 ml-16rpx w-0 flex justify-between flex-col">
              <view>
                <view>
                  <view class="line-2">{{ item.name }}</view>
                </view>
                <view class="mt-10rpx">
                  <u-tag
                    v-for="spec in item.specs"
                    :key="spec"
                    size="mini"
                    :text="spec"
                    class="mr-6rpx"
                    shape="square"
                    color="#A6A6A6"
                    bg-color="transparent"
                    mode="dark"
                  />
                </view>
              </view>
              <view class="flex items-end">
                <view class="flex-1">
                  <view class="">
                    <view class="flex-1">￥{{ item.sell_price }}</view>
                  </view>
                  <view class="flex items-center" v-if="item.vip_price>0">
                    <view class="">￥{{ item.vip_price }}</view>
                    <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
                  </view>
                </view>
                <view class="text-lg"> x{{ item.quantity }} </view>
              </view>
            </view>
          </view>
        </view>
        <view class="flex mt-20rpx justify-end">
          <!-- 申请售后 -->
          <view
            v-if="item.can_after_sale"
            class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
            @tap="$u.route('/pages/apply_refund/index', { id: detail.id, goodsId: item.id })"
            >申请售后</view
          >
          <view
            v-if="!item.can_after_sale && item.has_after_sale"
            class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
            @tap="$u.route('/pageA/after_sale/index')"
            >售后详情</view
          >
        </view>
        <view class="my-20rpx" v-if="index != products.length - 1">
          <u-line color="#E5E5E5" />
        </view>
      </block>
      <view v-if="detail.note" class="bg-hex-F5F2F2 p-rowSm mt-base h-100rpx text-md text-hex-808080"> 售后说明：{{ detail.note }} </view>
      <view class="mt-20rpx">
        <view class="h-50rpx leading-50rpx flex justify-between" v-if="detail.total_points > 0">
          <text class="text-black">抵扣积分</text>
          <text>{{ detail.total_points }}</text>
        </view>
        <view class="h-50rpx leading-50rpx flex justify-between">
          <text class="text-black">商品金额</text>
          <text>￥{{ detail.products_total_amount }}</text>
        </view>
        <view class="h-50rpx leading-50rpx flex justify-between">
          <text class="text-black">运费</text>
          <text>￥{{ detail.shipping_fee }}</text>
        </view>
        <view class="h-50rpx leading-50rpx flex justify-between" v-if="detail.coupon_discount_amount > 0">
          <text class="text-black">优惠券</text>
          <text class="text-warning">-￥{{ detail.coupon_discount_amount }}</text>
        </view>
        <view class="h-50rpx leading-50rpx flex justify-between" v-if="detail.vip_discount_amount > 0">
          <text class="text-black">会员优惠</text>
          <text class="text-warning">-￥{{ detail.vip_discount_amount }}</text>
        </view>
        <view class="h-50rpx leading-50rpx flex justify-between" v-if="detail.bargain_amount > 0">
          <text class="text-black">砍价优惠</text>
          <text class="text-warning">-￥{{ detail.bargain_amount }}</text>
        </view>
      </view>
      <u-line color="#E5E5E5" />
      <view class="flex justify-end mt-base">
        <text class="text-lg text-black">实付金额：</text>
        <text class="text-warning text-xl">￥{{ detail.total_amount }}</text>
      </view>
    </view>

    <view class="bg-white rounded-xs mt-24rpx py-base px-40rpx">
      <view class="flex items-center justify-between">
        <view class="h-50rpx leading-50rpx text-md text-black">订单编号：{{ detail.sn }}</view>
        <view @tap="copy(detail.sn)" class="border border-hex-A6A6A6 rounded-full px-base py-6rpx">复制</view>
      </view>
      <view class="h-50rpx leading-50rpx text-md text-black" v-if="!!detail.pay_way">支付方式：{{ detail.pay_way | payment }}</view>
      <view class="h-50rpx leading-50rpx text-md text-black">下单时间：{{ detail.created_at }}</view>
      <view class="h-50rpx leading-50rpx text-md text-black" v-if="!!detail.pay_at">支付时间：{{ detail.pay_at }}</view>
    </view>

    <block v-if="detail.status != 10">
      <view class="h-120rpx"></view>
      <view class="fixed bg-white bottom-0 w-full px-40rpx">
        <view class="flex justify-end h-100rpx items-center">
          <view
            v-if="detail.status == 0 || detail.status == 1"
            @tap.stop="cancelOrder(detail.id)"
            class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
          >
            取消订单</view
          >
          <view
            v-if="detail.status == 0"
            class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
            @tap.stop="$u.routeAuth({ url: '/pages/confirm_payment/confirm_payment', params: { id: detail.id } })"
            >立即付款
          </view>
          <view
            v-if="detail.status == 3"
            class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
            @tap.stop="confirmReceipt(detail.id)"
            >确认收货</view
          >
          <!-- 已完成 -->
          <!-- <view v-if="detail.status==9"
                class="border border-hex-A6A6A6 rounded-full px-20rpx py-10rpx ml-base"
                @tap="$u.route('/pages/publish_evaluation/index', { id: detail.id })"
                >发表评价</view
              > -->
        </view>
      </view>
    </block>

    <!-- 取消订单弹窗 -->
    <cu-modal
      v-model="cancelShow"
      @confirm="canceConfirm"
      confirm-color="#378264"
      show-cancel-button
      content="是否取消该订单"
      confirmText="确认取消"
      cancelText="再想想"
    >
    </cu-modal>
    <!-- 确认收货弹窗 -->
    <cu-modal
      v-model="receiptShow"
      title="确认收货"
      @confirm="receiptConfirm"
      confirm-color="#378264"
      show-cancel-button
      content="是否确认收货？"
    ></cu-modal>
  </view>
</template>

<script>
import uniCopy from '@/utils/uni-copy';
export default {
  data() {
    return {
      //  service:process.env.VUE_APP_SERVICE,
      id: '',
      detail: {},
      cancelShow: false,
      receiptShow: false,
      isFirstLoading: true,
    };
  },
  onLoad({ id }) {
    this.id = id;
    setTimeout(()=>{
      if(!this.isLogin){
        this.$u.route({
            type:'redirectTo',
            url:`/pages/login/index?redirec=${encodeURIComponent(`/pages/order_details/index?id=${id}`)}`
          })
      }else{
         this.getDetail();
      }
    },300)
  },
  onShow() {
    if(this.isLogin){
        this.getDetail();
    }
  },
  computed: {
    service() {
      const clien = process.env.VUE_APP_SERVICE;
      const user = this.$store.getters.user ?? {};
      const phone = user?.phone;
      const name = user?.nickname ?? phone ?? '访客';
      return `${clien}?u_cust_name=${name}&u_cust_phone=${phone}&u_cust_id=${phone}`;
    },
    products() {
      return this.detail?.products ?? [];
    },
  },
  methods: {
    //判断是否有页面栈，如果没有返回首页，否则返回上一页
    goJump(){
       const pages = getCurrentPages() 
      const prevPage = pages[pages.length - 2]
      if(prevPage){
        uni.navigateBack({})
      }else{
        uni.switchTab({
          url:'/pages/index/index'
        })
      }
    },
    //复制
    copy(val) {
      uniCopy({
        content: val ?? '',
        success: (res) => {
          this.$u.toast(res);
        },
        error: (e) => {
          this.$u.toast(e);
        },
      });
    },
    onCountEnd() {
      this.getDetail();
    },
    async getDetail() {
      const resData = await this.$api.get(`/v1/order/orders/${this.id}`);
      this.detail = resData;
      this.isFirstLoading = false;
    },
    //取消订单
    cancelOrder(id) {
      this.cancelShow = true;
    },
    async canceConfirm() {
      try {
        await this.$api.post(
          `/v1/order/orders/${this.id}/cancel`,
          {},
          {
            custom: {
              loading: true,
            },
          },
        );
        this.getDetail(this.id);
        this.$u.toast(' 订单取消成功');
      } catch (err) {}
    },
    //确认收货
    confirmReceipt(id) {
      this.receiptShow = true;
    },
    async receiptConfirm() {
      try {
        await this.$api.post(
          `/v1/order/orders/${this.id}/confirm`,
          {},
          {
            custom: {
              loading: true,
            },
          },
        );
        this.getDetail(this.id);
        this.$u.toast('确认收货成功');
      } catch (err) {}
    },
  },
};
</script>
<style lang="scss" scoped>
.shadow {
  box-shadow: 0px -4rpx 10rpx rgba(0, 0, 0, 0.11);
}
</style>
