<template>
<view class="dt-page">
  <template v-if="emptyType==0">
      
    <view class="hd-wrap">
      <view class="order-state">{{ orders.statusTxt }}</view>
      <view v-if="orders.status==orderState.waitForPay" class="order-state-tips">
        <text>请在</text>
        <view class="time-wrap">
          <DtTimer :start="orders.expireDate" @timeover='onTimer' />
          
        </view>
        <text>内完成支付，超时订单自动取消</text>
      </view>
      <view v-else-if="orders.status==orderState.waitForDelive" class="order-state-tips">已成功支付，等待商品发货</view>
      <view v-else-if="orders.status==orderState.waitForReview" class="order-state-tips">订单审核中，请耐心等候</view>
      <view v-else-if="orders.status==orderState.waitForReceive" class="order-state-tips">商品已发货，等待收货</view>
      <view v-else-if="orders.status==orderState.waitForAppraise" class="order-state-tips">商品已发货，等待评价</view>
      <view v-else-if="orders.status==orderState.finished" class="order-state-tips">欢迎再次购买</view>
      <view v-else-if="orders.status==orderState.refunded" class="order-state-tips">订单已退款，欢迎再次购买</view>
      <view v-else-if="orders.status==orderState.refunding" class="order-state-tips">订单退款中，请耐心等待商家处理</view>
      <view v-else-if="orders.status==orderState.failRefund" class="order-state-tips">订单退款失败，如有疑问请联系商家</view>
      <view v-else-if="orders.status==orderState.cancel" class="order-state-tips">订单已取消，欢迎再次购买</view>
      <view v-else-if="orders.status==orderState.waitRefundReview" class="order-state-tips">退货审核中，请耐心等候</view>
      
    </view>

    <DtContractor :name="receiver.consignee" :mobile="receiver.phone" :addr="receiver.addr" />

    <view class="order-item-wrap">
      <DtOrderItem :isTimer="false" :isFootShow="false" :dataDetail="orders" @tapbtn="onTapBtn" />
    </view>

    <view class="detail-item">
      <view class="title">买家留言</view>
      <view class="value">
        <input class="input-box" :value="orders.memo" type="text" placeholder="暂无留言" disabled />
      </view>
    </view>

    <view class="order-detail-wrap">
      <view class="detail-item">
        <view class="title">下单时间</view>
        <view class="value">{{orders.createdDate|dateFormat('yyyy-MM-dd hh:mm:ss')}}</view>
      </view>
      <view class="detail-item">
        <view class="title">收货方式</view>
        <view class="value">送货上门</view>
      </view>
      <view class="detail-item">
        <view class="title">付款方式</view>
        <view class="value">在线支付</view>
      </view>
      <view class="line"></view>

      <view class="detail-item">
        <view class="title">商品总额</view>
        <view class="value">￥{{orders.price}}</view>
      </view>
     <!-- <view class="detail-item">
        <view class="title">
          <text>会员折扣</text>
          <view class="card">铂金卡</view>
        </view>
        <view class="value">-￥20.00</view>
      </view> -->
      <view class="detail-item">
        <view class="title">优惠券</view>
        <view class="value">-￥{{orders.couponDiscount}}</view>
      </view>
      <view class="detail-item">
        <view class="title">运费</view>
        <view class="value">￥{{orders.freight}}</view>
      </view>
    </view>

    <view class="detail-item">
      <view class="title">实付金额</view>
      <view class="value">
        <text class="dt-color-error">￥{{orders.amount}}</text>
      </view>
    </view>

	<view v-if="orderShippings != null && orderShippings.length > 0" class="order-detail-wrap" style="margin-bottom: 20upx;">
		<text class="detail-item-title">快递信息</text>
		<view v-if="item.trackingNo != null" class="detail-item" v-for="(item, index) in orderShippings" :key="index">
			<view class="title">{{item.deliveryCorp}}</view>
			<view class="value" style="margin-left: 40upx;">
				<text @click="copyOrderShipping(item.trackingNo)" class="value">{{ item.trackingNo }}</text>
				<text @click="copyOrderShipping(item.trackingNo)" class="copy">复制</text>
			</view>
		</view>
	</view>
			
    <FootToolbar bgColor="#fff">
      <view slot="main" class="btn-wrap">
        <!-- 待支付 -->
        <block v-if="orders.status == orderState.waitForPay">
          <button class="btn-base btn-plain" hover-class="button-hover-scale" @tap="cancelOrder">取消订单</button>
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
          <button class="btn-base btn-primary" hover-class="button-hover-scale" @tap="payOrder">立即支付</button>
        </block>
        <!-- 待发货, 虽然是取消订单的文字按钮，但执行的是申请售后（退货） -->
        <block v-else-if="orders.status == orderState.waitForDelive">
          <button class="btn-base btn-plain" hover-class="button-hover-scale" @tap="refund">取消订单</button>
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
        </block>
        <!-- 待收货 -->
        <block v-else-if="orders.status == orderState.waitForReceive">
			<button class="btn-base btn-plain" hover-class="button-hover-scale" @tap="refund_choose">申请售后</button>
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
          <button class="btn-base btn-primary" hover-class="button-hover-scale" @tap="receiveOrder">确认收货</button>
        </block>
        <!-- 待评价 -->
        <block v-else-if="orders.status == orderState.waitForAppraise">
			<button class="btn-base btn-plain" hover-class="button-hover-scale" @tap="refund_choose">申请售后</button>
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
          <button class="btn-base btn-primary" 
            hover-class="button-hover-scale"
            @tap.stop="tapAppraise">评价商品</button>
        </block>
		<!-- 已完成 -->
		<block v-else-if="orders.status == orderState.finished">
			<button class="btn-base btn-plain" hover-class="button-hover-scale" @tap="refund_choose">申请售后</button>
			<button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
			<button class="btn-base btn-primary" hover-class="button-hover-scale" @tap="tapBuy">再次购买</button>
		</block>
        <!-- 已取消 -->
        <block v-else-if="orders.status == orderState.cancel">
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
          <button class="btn-base btn-primary" hover-class="button-hover-scale" @tap="tapBuy">再次购买</button>
        </block>
        
        <!-- 其他 orderState.waitRefundReview, orderState.finished -->
        <block v-else>
          <button class="btn-base btn-primary btn-primary-plain" hover-class="button-hover-scale" @tap="tapCall">商家电话</button>
        </block>
      </view>
    </FootToolbar>

  </template>
  <DtEmpty :type="emptyType" />
</view>
</template>

<script>
import DtTimer from '../comps/dt_timer.vue'
import DtContractor from '../comps/dt_contractor.vue'
import DtOrderItem from '../comps/dt_order_item.vue'
import DtEmpty from '../comps/dt_empty.vue'
import FootToolbar from '../comps/foot_toolbar.vue'
export default {
  components: {
    DtTimer,
    DtContractor,
    DtOrderItem,
    DtEmpty,
    FootToolbar
  },
  data() {
    return {
      dataDetail: {
        status: 'PENDING_PAYMENT',
        time: '19:23',
        name: '大香菇',
        mobile: '13542849555',
        addr: '广东省广州市天河区车陂660号',
        list: [{
            goods_name: '[仁和]维C银翘片'
          },
          {
            goods_name: '[仁和]维C银翘片'
          }
        ]
      },
	  orderShippings: [],
      receiver: {},
      param: {},
      orders: {},
      leaveMsg: '',
    }
  },
  computed: {
    
    footSafe() {
      return `padding-bottom:${this.safeAreaBottom}px`;
    },
    orderState() {
      return this.$global.orderState
    },
    orderStateName() {
      return this.$global.orderStateName
    },
    isDel(){
      return [ // FAILED("已失败"), CANCELED("已取消"), DENIED("已拒绝")
        this.orderState.failed,
        this.orderState.cancel,
        this.orderState.denied
      ]
    },
  },
  methods: {
	  async refund_choose() {
	  	uni.navigateTo({
	  		url: '/pagesM/pages/after_sale_choose?orderId=' + this.orders.id
	  	});
	  },
	//复制快递单号
	copyOrderShipping(trackingNo) {
		uni.setClipboardData({ data: trackingNo });
	},
    // 过期
    onTimer() {
      // let dataDetail = this.dataDetail
      let state = this.orderState.cancel
      this.dataDetail.status = state
      this.orders.status=state;
      this.dataDetail.statusTxt = this.$global.orderStateName[state];
      this.orders.statusTxt=this.$global.orderStateName[state];
      // this.dataDetail = dataDetail
      
    },
    // 再次购买
    tapBuy(){
      uni.switchTab({
        url:'/pages/life/life'
      })
    },
    cancelOrder(){
      this.$dialog.confirm({
        content:'确认取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            todoCancelOrder()
          }
        }
      })
      let ctx = this
      async function todoCancelOrder(){
        let resp = await ctx.$api.cancelOrder({
          sn: ctx.orders.sn,
          detail:'订单取消',
          remark:'B2C微信小程序用户取消订单',
        })
        ctx.$dialog.success('取消成功',()=>{
          ctx.$util.refreshPage(['pages/mine','pages/mine_order_list'])
          ctx.queryDataDetail()
        })
      }
    },
    async payOrder() {
      let item = this.orders
      if(item && item.sn){
        let sns = [item.sn]
        uni.navigateTo({ url: "/pages/order_pay?orderSns=" + JSON.stringify(sns) + "&payFlag=" + this.$global.payFlag.order });
      }
    },
    async refund(){
      uni.navigateTo({
        // url:'/pages/after_sale_choose?orderId='+this.orders.id
        url:'/pages/after_sale_submit?orderId='+this.orders.id
      })
    },
    
    async receiveOrder(){
      this.$dialog.confirm({
        content:'确认收货吗？',
        success:(res) => {
          if (res.confirm) {
            todoReceiveOrder()
          }
        }
      })
      let ctx = this
      async function todoReceiveOrder(){
        let resp = await ctx.$api.orderChange({
          memberId: ctx.memberId,
          orderId: ctx.orders.id,
          execType: 2
        })
        ctx.$dialog.success('确认收货',()=>{
          ctx.$util.refreshPage(['pages/mine','pages/mine_order_list'])
          ctx.queryDataDetail()
        })
      }
    },
    tapAppraise(){
      uni.navigateTo({
        url: '/pagesM/pages/order_appraise?orderId=' + this.orders.id
      })
    },
    // delOrder(){
    //   this.$dialog.confirm({
    //     content:'确认删除该订单吗？',
    //     success:(res) => {
    //       if (res.confirm) {
    //         todoDelOrder()
    //       }
    //     }
    //   })
    //   let ctx = this
    //   async function todoDelOrder() {
    //     let resp = await ctx.$api.delOrder({
    //       orderId:ctx.orders.id
    //     })
    //     // this.$dialog.success('删除成功')
    //     ctx.$util.refreshPage(['pages/mine','pages/mine_order_list'])
    //     uni.navigateBack()
    //   }
    // },
    tapCall() {
      let phone = this.orders.store.phone
      if(phone){
        this.makePhoneCall(phone)
      }else{
        this.$dialog.toast('暂无商家电话号码，请通过“我的>>联系商家”拨打服务电话')
      }
    },
    async queryDataDetail() {
      try{
        // 订单详情
        let resp = await this.$api.getOrderDetail({
          _isShowLoading:true,
          _isReject:true,
          orderSns: [this.loadOptions.orderSns]
        })
        if (resp) {
          this.emptyType = 0
          this.dataDetail = resp
          let receiver = resp.receiver || {}
          this.receiver = receiver
          if (receiver.areaName && receiver.address) {
            this.receiver.addr = receiver.areaName + receiver.address
          }
          this.param = resp.param || {}
          if (resp.orders && resp.orders[0]) {
            let orderObj = resp.orders[0]
            orderObj.orderItems.map((item) => {
              item.specificationsDesc = item.specificationValues.join('　')
              item.name = item.skuName
              return
            })
            this.orders = orderObj
            this.orders.products = orderObj.orderItems.slice(0)
          }
        }else{
          this.emptyType = 1
        }
      }catch(err){
        this.emptyType = 2
        this.$dialog.alert({
          content:err.errmsg || '暂无数据~'
        })
      }
    },
    async getOrderShippingInfo() {
    	try {
    		// 订单详情
    		let resp = await this.$api.getOrderShippingInfo(this.loadOptions.orderSns);
    		this.orderShippings = resp ? resp : [];
    	} catch (err) {
    		Log.e("========getOrderShippingInfo==>err>>"+err)
    	}
    },
	// // 售后详情
    // async findAftersales(){
      
    // },
    onLoadPage() {
	  wx.hideShareMenu();
      if(this.isLoad){
        this.memberId = this.$auth.getMemberId()
      }
      this.queryDataDetail();
	  this.getOrderShippingInfo();
    },
  },
  onShow(){
    this.onShowPage()
  }
}
</script>

<style lang="scss" scoped>
.dt-page {
  min-height: 100vh;
  background-color: #f2f2f2;

  .hd-wrap {
    display: flex;
    flex-wrap: wrap;
    padding: 0 30upx;
    background-color: $base-btn-color;
    color: #fff;
    font-weight: 400;

    .order-state {
      padding-top: 40upx;
      width: 100%;
      font-size: 48upx;
      line-height: 1;
    }

    .order-state-tips {
      display: flex;
      width: 100%;
      padding-bottom: 30upx;
      padding-top: 10upx;
      font-size: 24upx;
      line-height: 1.5;

      .time-wrap {
        padding: 0 10upx;
      }
    }
  }

  .order-item-wrap {
    margin-top: 20upx;
  }

  // .state-row{
  //   display:flex;
  //   justify-content: space-between;
  //   padding:0 30upx;
  //   line-height:80upx;
  //   border-bottom:1upx solid #e5e5e5;
  //   .timer{
  //     color:$dt-color-error;
  //     .tips{
  //       padding-left:10upx;
  //     }
  //   }
  //   .order-no{
  //     color:#666666;
  //   }
  //   .order-state{
  //     font-size:30upx;
  //     color:#666666;
  //   }
  // }
  // .goods-row{
  //   margin-top:20upx;
  //   background-color:#fff;
  //   .goods-item{
  //     display:flex;
  //     padding:30upx;
  //     height: 220rpx;
  //     box-sizing: border-box;
  //     border-bottom:1upx solid #e5e5e5;
  //     .main-pic{
  //       width:152upx;
  //       height:152upx;
  //     }
  //     .rt-wrap{
  //       padding-left:26upx;
  //       flex:1;
  //       .good-mn{
  //         display:flex;
  //         justify-content:space-between;
  //         align-items:flex-end;
  //         font-size:30upx;
  //         .goods-name{
  //           flex:1;
  //           margin-right:20upx;
  //           line-height:1.5;
  //         }
  //       }
  //       .specifications{
  //         margin:30upx 0 20upx;
  //         line-height:1;
  //         color:#999999;
  //         font-size:26upx;
  //         font-weight:500;
  //       }
  //       .price{
  //         font-size:30upx;
  //       }
  //     }
  //   }
  // }

  .detail-item {
    display: flex;
    align-items: center;
    margin: 20upx 0;
    padding: 0 30upx;
    height: 90upx;
    background-color: #fff;

    .title {
      display: flex;
      align-items: center;
      margin-right: 20upx;
      color: #666666;
      font-weight: 400;
    }

    .value {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .input-box {
        width: 100%;
        text-align: right;
      }
    }
	
	.copy {
		color: #2DABF3;
		margin: 0rpx 10rpx;
	}
  }

  .order-detail-wrap {
    padding: 10upx 0;
    background-color: #fff;
		
	.detail-item-title{
		display: flex;
		padding: 10upx 30upx 20upx 30upx;
		border-bottom: 1upx solid #e5e5e5;
	}

    &>.detail-item {
      height: 68rpx;
      margin: 0;
    }

    .line {
      margin: 10upx auto;
      width: 690upx;
      height: 1upx;
      background-color: #e5e5e5;
    }

    .card {
      margin: 0 10upx;
      padding: 0 6upx;
      height: 32upx;
      line-height: 32upx;
      font-size: 22upx;
      background-color: #ffc600;
      border-radius: 4upx;
      color: #fff;
    }
  }

  

  .btn-wrap {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100vw;
    height: 100upx;
    background-color: #fff;
    padding: 0 30upx;
    box-sizing: border-box;

    .btn-base {
      position: relative;
      margin: 0 0 0 30upx;
      width: 150upx;
      height: 56upx;
      line-height: 56upx;
      font-size: 28upx;
      border-radius: 6upx;
    }

    .btn-base:before {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      border: 2upx solid $base;
      border-radius: 6upx;
      content: "";
    }

    .btn-plain {
      background-color: transparent;
      color: $base;
    }

    .btn-plain:before {
      border-color: #ccc;
      content: "";
    }

    .btn-primary {
      background-color: $base;
      color: #fff;
    }

    .btn-primary:before {
      border-color: $base;
      content: "";
    }

    .btn-primary-plain {
      background-color: transparent;
      color: $base;
    }
  }
}
</style>
