<template>
  <view class="order-page">
		<view class="header-box">
			<view class="search-box">
			  <u-search
			    v-model="orderSn"
			    placeholder="搜索订单号"
			    :show-action="false"
				  @custom="onSearchFn" 
					@search="onSearchFn"
			  ></u-search>
			</view>
			<u-tabs :list="tabList" :current="tabCurrent" name="dictLabel" @change="tabChange"></u-tabs>
		</view>
    
    <mescroll-body
      ref="mescrollRef"
			top="192rpx"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
			:up="upOption"
    >
      <view class="order-list">
        <view class="order-item" v-for="(item, index) in orderList" :key="index">
          <view class="order-header">
            <text class="order-no">订单号：{{item.orderSn}}</text>
            <text class="order-status" :class="['dict-item',getDictName('mall_order_status',item.orderStatus,'listClass')]">{{getDictName('mall_order_status',item.orderStatus,'dictLabel')}}</text>
          </view>
          
          <view class="product-info" v-for="val in item.orderItems">
            <image :src="val.productPic" mode="aspectFill" class="product-image" @click="lookPic(val.productPic)"></image>
            <view class="product-detail">
              <view class="product-name">{{val.productName}}</view>
							<view class="product-count">x{{val.productQuantity}}</view>
							<view class="product-price">¥{{ val.productPrice ? (val.productPrice / 100).toFixed(2) : '0.00' }}</view>
							<view class="product-funlist">
								<u-button
								  v-if="val.funPath"
								  size="mini"
								  plain
									type="primary"
								  @click="goFun(val.funPath, val.productId, item.id, val.id, val.funName)"
								>{{ val.funName }}</u-button>
							</view>
              <!-- <view class="product-specs">
                颜色：{{item.color}}；尺码：{{item.size}}
              </view> -->
            </view>
            
          </view>
          <view class="total-info">
            共{{item.orderItems.length}}件商品 总金额：
            <text class="price">¥{{ item.totalAmount ? (item.totalAmount / 100).toFixed(2) : '0.00' }}</text>
          </view>
          <view class="order-footer">
            <view class="button-group">
              <!-- <u-button 
                v-if="item.showCancel"
                size="mini"
                plain
                @click="cancelOrder(item)"
              >取消订单</u-button> -->
							<u-button
								v-if="item.orderStatus === 0"
							  size="mini"
								shape="circle"
							  type="primary"
							  @click="viewDetail(item)"
							>去付款</u-button>
              <u-button
                size="mini"
                type="primary"
								shape="circle"
								plain
                @click="goDetail(item)"
              >查看详情</u-button>
            </view>
          </view>
        </view>
      </view>
    </mescroll-body>
  </view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
export default {
  data() {
    return {
      orderSn: '',
      tabCurrent: 0,
      tabList: [
        { dictLabel: '全部',dictValue: null },
        // { name: '待付款' },
        // { name: '待发货' },
        // { name: '待收货' },
        // { name: '已完成' }
      ],
			upOption:{
				page:{
					num : 0 ,
					size : 12 ,
					time : null
				},
				noMoreSize: 4,
				empty:{
					icon:'https://fast.gk-hd.com/resource/app-sec/new.png',
					use : true ,
					tip: '~ 消息列表为空 ~',
				  fixed: true,
					top: "200rpx",
				},
				bgColor:"#f5f5f5"
			},
      orderList: [],
      mescroll: null,
      pageNum: 1,
      pageSize: 10,
			mall_order_status:[],
			orderStatus:'',
    }
  },
	mixins:[MescrollMixin],
	onLoad() {
		this.getDictDataList('mall_order_status');
	},
	onShow() {
		this.$nextTick(() => {
				if (this.mescroll) {
						this.mescroll.resetUpScroll();
				} else {
						console.warn('mescroll is not initialized yet');
				}
		});
	},
  methods: {
		getDictDataList(type){
			this.$api.getDictList(type).then((res)=>{
				if(res.code===200){
					this[type] = res.data || [];
					if(type == 'mall_order_status'){
						this.tabList =  [{ dictLabel: '全部',dictValue: '' },...res.data]
					}
				}
			})
		},
		getDictName(list,value,key){
			let name = ''
			if(this[list]){
				this[list].forEach((item)=>{
					if(item.dictValue == value){
						name = item[key];
					}
				})
				return name;
			}
		},
    mescrollInit(mescroll) {
      this.mescroll = mescroll
    },
    // // 下拉刷新
    // downCallback(mescroll) {
    //   this.pageNum = 1
    //   this.getOrderList(mescroll)
    // },
    // 上拉加载
		onSearchFn(){
			this.mescroll.resetUpScroll();
		},
		lookPic(url){
			uni.previewImage({
				current: '', // 当前显示图片的 http 链接
				urls: [url] // 需要预览的图片 http 链接列表
			});
		},
    upCallback(page) {
			let pageNum = page.num; // 页码, 默认从1开始
			let pageSize = page.size; // 页长, 默认每页10条
			let obj = {
				pageNum:pageNum,
				pageSize:pageSize,
				orderSn:this.orderSn,
				orderStatus:this.orderStatus,
			}
			this.$api.orderApi.getOrderList(obj).then((res)=>{
				console.log("当前订单列表",res)
				if (res.rows && res.rows.length>0) {
					// 接口返回的当前页数据列表 (数组)
					let curPageData = res.rows;
					// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
					let curPageLen = curPageData && curPageData.length;
					//设置列表数据
					console.log(curPageLen,res.total);
					if(pageNum == 1){
						this.orderList = []; //如果是第一页需手动置空列表
						// this.getUnreadNewIdList(); //
						// this.getUnreadNewNum();
					}
					this.orderList = this.orderList.concat(curPageData); //追加新数据
					this.mescroll.endBySize(curPageLen, res.total); // 推荐
					this.loading = false;
				} else{
					this.orderList = [];
					this.mescroll.endErr();
					this.mescroll.showEmpty();
					this.loading = false;
					// this.mescroll.endUpScroll(true)
				}
			}).catch(()=>{
				this.$u.toast('服务器开小差了呢，请您稍后再试')
				this.orderList = [];
				//联网失败, 结束加载
				this.mescroll.endErr();
				this.mescroll.showEmpty();
				this.loading = false;
			})
      // this.getOrderList(page)
    },
    // 获取订单列表
    getOrderList(mescroll) {
      // 模拟接口请求
      setTimeout(() => {
        let curList = [{
          orderNo: '202312150001',
          status: '待付款',
          productName: 'NIKE AIR MAX 2023新款运动鞋',
          productImage: '/static/shoes.jpg',
          color: '白色',
          size: '42',
          count: 1,
          price: '899.00',
          totalPrice: '899.00',
          showCancel: true
        }]
        
        if(this.pageNum === 1) {
          this.orderList = curList
        } else {
          this.orderList = this.orderList.concat(curList)
        }
        
        this.pageNum++
        mescroll.endSuccess(curList.length)
      }, 500)
    },
    // 切换标签
    tabChange(index) {
			console.log("index",index)
			this.orderStatus = this.tabList[index].dictValue;
      this.tabCurrent = index
      this.mescroll.resetUpScroll()
    },
    // 取消订单
    cancelOrder(item) {
      uni.showModal({
        title: '提示',
        content: '确认取消该订单吗？',
        success: (res) => {
          if(res.confirm) {
            // 处理取消订单逻辑
          }
        }
      })
    },
    // 查看详情
    goDetail(item) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${item.id}`
      })
    },
		goFun(path, productId, orderId, orderItemId, name){
			console.log("path",path, productId, orderId)
			uni.navigateTo({
			  url: `/pages${path}?productId=${productId}&orderId=${orderId}&orderItemId=${orderItemId}&name=${name}`
			})
		}
  }
}
</script>

<style lang="scss" scoped>
.order-page {
  // min-height: 100vh;
  background-color: #f5f5f5;
	// position: relative;
  .header-box{
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 999;
		background-color: #fff;
	}
  .search-box {
    padding: 20rpx;
    background-color: #fff;
  }
  
  .order-list {
    padding: 20rpx;
    
    .order-item {
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 20rpx;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        padding-bottom: 20rpx;
        border-bottom: 1px solid #eee;
        
        .order-status {
          // color: #2979ff;
        }
      }
      
      .product-info {
        display: flex;
        padding: 20rpx 0;
        
        .product-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
        }
        
        .product-detail {
          flex: 1;
          padding: 0 20rpx;
          
          .product-name {
            font-size: 28rpx;
						font-weight: bold;
            line-height: 1.4;
          }
          
          .product-specs {
            font-size: 24rpx;
            color: #999;
            margin-top: 10rpx;
          }
          
          .product-count {
            font-size: 24rpx;
            color: #666;
            margin-top: 5rpx;
          }
					
					.product-price {
					  color: #ff0000;
					  font-size: 28rpx;
					}
					.product-funlist{
						padding: 5rpx 0;
					}
        }
        
        
      }
      .total-info {
				text-align: right;
        font-size: 26rpx;
				color: #999;
        margin-bottom: 10rpx;
        .price {
          color: #ff0000;
          font-weight: bold;
        }
      }
      .order-footer {
        display: flex;
        // justify-content: space-between;
				justify-content: flex-end;
        align-items: center;
        padding-top: 20rpx;
        border-top: 1px solid #eee;
        
        
        
        .button-group {
          display: flex;
          gap: 20rpx;
        }
      }
    }
  }
}
</style>