<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view class="content">
    <view class="top-wrapper">
      <view class="top-cont">
        <view class="top-title">订单</view>
        <u-input
          v-model="searchValue"
          class="top-ipt"
          placeholder="请输入食堂、档口、菜品/商品名"
          shape="circle"
          suffixIcon="search"
          suffixIconStyle="color: #909399; font-size: 36rpx;"
          placeholderStyle="font-weight: 400;font-size: 20rpx;color: rgba(15,39,75,0.4);"
          @blur="handleSearch"
        ></u-input>
        <view class="top-filter" @click="openPopup">
          <span style="font-size: 28rpx; color: #0f274b">筛选</span>
          <u-icon name="../../static/images/pull.png" />
        </view>
      </view> 
      <view style="padding: 0 16px">
        <Tabs :tabList="tabList" @changeTab="changeTab" />
      </view>
    </view>


    <!-- <view style="height: 56px"></view> -->
    <scroll-view style="width: 100%;height: 76vh;" @scrolltolower="onScrollTolower" scroll-y="true">
		<view class="evaluateCenter" v-if="this.tabIndex==1">
			<view class="evaluateCenterLeft">
				<u-image src="../../static/images/user.png" width="30px" height="30px" />
				<text>评价中心</text>
			</view>
			<view class="evaluateCenterRight" @click="goEvaluateCenter">
				去看看
			</view>
		</view>
      <view class="order-list" v-for="(item, index) in tableList" :key="index">
        <view class="flex justify-between">
          <!-- <view class="order-source">订单来源：双屏消费机</view> -->
          <view class="order-source" style="font-size: 28rpx;font-weight: bold;">订单类型：{{ item.orderTypeStr }}</view>
          <view style="color: rgba(15, 39, 75, 0.8)">就餐日期：{{ item.orderDate }}</view> 
        </view>
        <view class="flex justify-between">
          <view style="display: flex;width: 70%;align-items: center;">
            <view style="color: #0f274b;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;font-size: 28rpx;max-width: 75%;">{{ item.canteenName }}/{{item.stallName}}</view>
            <!-- <span style="color: #0f274b">{{ item.canteenName }}</span> -->
            <view class="intervalName" v-if="item.mealtimeName">{{ item.mealtimeName }}</view>
          </view>
          <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==1">已下单</view>
          <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==2">已完成</view>
          <view style="color: red;font-size: 28rpx;" v-if="item.orderState==3&&item.payState==3">已退单</view>
          <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==3&&item.payState==4">已取消</view>
          <view style="color: red;font-size: 28rpx;" v-if="item.orderState==4&&item.payState==1">未支付</view>
          <!-- <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==4&&item.payState==3">待下单</view> -->
          <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==4&&item.payState==4">支付失败</view>
          <view style="color: rgba(15, 39, 75, 0.8);font-size: 28rpx;" v-if="item.orderState==5">部分退单</view>
        </view>
        <view class="img-cont" @click="goDetail(item)">
			<view style="width: 80%;display: flex;align-items: center;flex-wrap: wrap;">
				<view class="img" v-for="(goods, gindex) in item.orderDetailList" :key="gindex" v-if="gindex<3">
				  <u-image :src="goods.goodsImgUrl" width="80px" height="80px" />
				  <view style="width: 100%;white-space: nowrap;text-align: center;overflow: hidden;text-overflow: ellipsis;">{{ goods.goodsName }}</view>
				</view>
			</view> 
			<view class="price">
				<view>
				  <span>￥</span>
				  <span style="font-size: 18px">{{ (item.realAmount/100).toFixed(2) }}</span>
				</view>
				<view style="color: rgba(15, 39, 75, 0.6)">共{{ item.orderDetailList.length }}件</view>
			</view>
        </view>
		<view class="btn-cont">
			<view v-if="item.orderState==2&&item.commentState==2">
			   <u-button size="small" style="background: #ff6816;color: #FFF;font-size: 24rpx;" @click="goEvaluate(item)">评价</u-button>
			</view>
			<view style="display: flex;" v-if="(item.orderState==4&&item.payState==4) || (item.orderState==4&&item.payState==1)">
			   <u-button size="small" shape="circle" :plain="true" style="font-size: 24rpx;margin-right: 20rpx;" @click="refundOrder(item)">取消订单</u-button>
			   <u-button size="small" shape="circle" type="primary" style="font-size: 24rpx;" @click="goPay(item)">立即支付</u-button>
			</view>
		</view>
      </view>
	  <view style="margin: 20px 0" v-if="tableList.length > 0">
	    <u-loadmore :status="status" nomoreText="没有更多数据了" />
	  </view>
	  <view v-else class="flex justify-center align-center" style="height: 50vh">
	    <u-empty icon="../../static/images/not_order.png" text="暂无相关订单" textColor="#000" />
	  </view>
    </scroll-view>
    <!--  筛选部分-->
    <u-popup :show="localShow" @close="closePopup" mode="bottom" round="20">
      <view class="filter-popup">
        <!-- 订单日期 -->
        <view class="section">
          <view class="section-title">订单日期</view>
          <view class="date-quick-select">
            <view
              v-for="(item, index) in dateOptions"
              :key="index"
              class="date-option"
              :class="{ active: currentDateOption == index }"
              @click="selectDateOption(index)"
            >
              {{ item.label }}
            </view>
          </view>

          <view class="date-range">
            <view class="date-input" @click="showStartCalendar = true">
              <text class="date-placeholder" v-if="!startDate">开始时间</text>
              <text v-else class="selected-date">{{ startDate }}</text>
            </view>
            <text class="date-separator">-</text>
            <view class="date-input" @click="showEndCalendar = true">
              <text class="date-placeholder" v-if="!endDate">结束时间</text>
              <text v-else class="selected-date">{{ endDate }}</text>
            </view>
          </view>
        </view>

        <!-- 订单类型 -->
       <view class="section">
          <view class="section-title">订单类型</view>
          <u-grid :border="false" col="3">
            <u-grid-item v-for="(item, index) in orderTypes" :key="index" @click="selectOrderType(item.id,index)">
              <view class="order-type-item" :class="{ active: selectedOrderTypes.includes(item.id) }">
                {{ item.name }}
              </view>
            </u-grid-item>
          </u-grid>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-buttons">
          <u-button
            text="清空"
            shape="circle"
            :customStyle="{
              border: '2rpx solid #DDDDDD',
              color: '#666666',
              background: '#ffffff',
              marginRight: '24px'
            }"
            @click="clearAll"
          ></u-button>
          <u-button
            type="warning"
            text="确定"
            shape="circle"
            :customStyle="{
              background: '#ff6633'
            }"
            @click="confirm"
          ></u-button>
        </view>
      </view>

      <!-- 日期选择器 -->
      <u-datetime-picker
		v-model="dateValue"
        :show="showStartCalendar"
        @cancel="showStartCalendar = false"
        @confirm="selectStartDate"
        mode="date"
      ></u-datetime-picker>

      <u-datetime-picker
		v-model="dateValue2"
        :show="showEndCalendar"
        @cancel="showEndCalendar = false"
        @confirm="selectEndDate"
        mode="date"
      ></u-datetime-picker>
    </u-popup>
  </view>
</template>

<script> 
import Tabs from '@/pages/components/Tabs.vue'
import { getDate } from '../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/util'
import { getOrderInfoListAPI,getOrderSourceTypeListAPI,payOrderApi,refundOrderApi } from '../../api/order/index'

export default {
  components: { Tabs },
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
		fontValue:uni.getStorageSync('fontSize') || 8,
		tabIndex: 0,
		pageNum: 1,
		pageSize: 10,
		total: 0,
		searchValue: '',
		orderState:'',
		orderStateList:[],
		commentState:'',
		payState:'',
		orderRefundState:'',
		status: 'loadmore',
		tabList: ['全部订单', '待评价', '退单'],
		dateValue:new Date(),
		dateValue2:new Date(),
		sourceTypeList:[],
		tableList: [
			// {
			//   sourceType: 'hygyy双屏消费机', // 订单来源
			//   canteenName: '宏源工业园/本周菜谱', // 订单来源
			//   intervalName: '午餐', // 餐次
			//   ordState: 11, // 订单状态 1 已下单 9 已取消 10 已退款 11 已完成
			//   orderTime: '2024-08-12', // 下单时间
			//   realAmount: 30.2, // 实付金额
			//   detailList: [
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg' // 商品图片
			// 	},
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
			// 	},
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
			// 	}
			//   ] // 订单详情
			// },
			// {
			//   sourceType: 'hygyy双屏消费机', // 订单来源
			//   canteenName: '宏源工业园/本周菜谱', // 订单来源
			//   intervalName: '午餐', // 餐次
			//   ordState: 10, // 订单状态 1 已下单 9 已取消 10 已退款 11 已完成
			//   orderTime: '2024-08-12', // 下单时间
			//   realAmount: 30.2, // 实付金额
			//   detailList: [
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-1.jpg' // 商品图片
			// 	},
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
			// 	},
			// 	{
			// 	  goodsName: '苹果', // 商品名称
			// 	  goodsImgUrl: 'https://img.yzcdn.cn/vant/apple-2.jpg' // 商品图片
			// 	}
			//   ] // 订单详情
			// }
		],
		localShow: this.show,
		monthNum: 12,
		minData: getDate(new Date()),
		dateOptions: [
			{ label: '近1个月', value: 1 },
			{ label: '近3个月', value: 3 },
			{ label: '近6个月', value: 6 }
		],
		currentDateOption: -1,
		startDate: '',
		endDate: '',
		showStartCalendar: false,
		showEndCalendar: false,
		orderTypes: [{id:"2",name:'预订餐'},{id:"4",name:'商城'},{id:"11",name:'线下消费'}],
		orderTypeList:[],
		typeList:[
			{id:"1",name:'当餐点餐'},{id:"2",name:'预订餐'},{id:"3",name:'自定义报餐'},{id:"4",name:'商城'},{id:"5",name:'预订商城'},{id:"6",name:'包间'},
			{id:"7",name:'餐桌'},{id:"8",name:'班车'},{id:"9",name:'3天报餐'},{id:"10",name:'7天报餐'},{id:"11",name:'线下消费'},{id:"12",name:'自助餐'},
			{id:"13",name:'到店扫码'},{id:"14",name:'到店扫码'},{id:"15",name:'美团外卖'},{id:"16",name:'美团到店'},{id:"21",name:'补扣'},{id:"22",name:'外部订单'},{id:"99",name:'其他'}
		],
		selectedOrderTypes: [],
		
    }
  },
	watch: {
		show(newVal) {
			this.localShow = newVal // 监听 prop 变化并更新本地数据属性
		}
	},
	onLoad() {
		// this.getSourceTypeList()
	},
	onShow() {
		this.getList()
	},
	methods: {
		async getSourceTypeList() {
		  try {
		    const res = await getOrderSourceTypeListAPI({})
		    console.log('?? ~ getList ~ res:', res)
			this.sourceTypeList=res
		  } catch (error) {
		    console.log(error)
		  }
		},
		
		// 翻页
		onScrollTolower(){
			console.log(this.tableList.length)
				if(this.total>this.tableList.length){
					this.pageNum++
					this.getList()
				}
		},
		//获取订单列表
		async getList() {
			console.log('获取列表',)
			let params = {
				userId: uni.getStorageSync('userId'),
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				searchValue: this.searchValue,
				commentState:this.commentState,
				orderState:this.orderState,
				orderStateList:this.orderStateList,
				payState:this.payState,
				orderRefundState:this.orderRefundState,
				orderTypeList:this.orderTypeList
			}
			if(this.startDate&&this.endDate){
				params.startDateTime = this.startDate+" 00:00:00"
				params.endDateTime = this.endDate+" 23:59:59"
				
			}else{
				params.startDateTime = getDate(new Date())+" 00:00:00"
				params.endDateTime = getDate(new Date())+" 23:59:59"
			}
			try {
			const res = await getOrderInfoListAPI(params)
				console.log('?? ~ getList ~ res:', res)
				this.total = res.total;
				res.rows.forEach(item=>{
					let hasIndex=this.typeList.findIndex(v=>v.id==item.orderType)
					item.orderTypeStr = this.typeList[hasIndex].name
				})
				if(this.pageNum==1){
					this.tableList = res.rows
				}else{
					this.tableList.push(...res.rows)
				}
				this.status = this.total == this.tableList.length ? 'nomore' : 'loadmore'
			} catch (error) {
				console.log(error)
			}
		},
		//翻页
		onReachBottom() {
			console.log('?? ~ onReachBottom ~ ')
			// if (this.total < 10 || this.total == this.tableList.length) {
			//   this.status = 'nomore'
			//   return
			// }
			// this.status = 'loading'
			// setTimeout(() => {
			//   this.pageSize += 10
			//   this.getList()
			//   if (this.tableList.length != this.total) this.status = 'loadmore'
			//   else this.status = 'nomore'
			// }, 500)
			// console.log('加载..', this.pageSize)
		},
		//搜索图标-搜索
		handleSearch() {
		  console.log('搜索', this.searchValue)
		  this.pageNum=1;
		  this.tableList=[]
		  this.getList()
		},
		//全部/待评价/退款
		changeTab(index) {
			console.log('?? ~ changeTab ~ index:', index)
			this.tabIndex = index;
			if(index==1){
				this.commentState="2"
				this.orderState=""
				this.orderStateList = [2]
				this.payState=""
				this.orderRefundState=""
			}else if(index==2){
				this.commentState="";
				this.orderState="3";
				this.orderStateList = []
				this.payState="3"
				this.orderRefundState="2";
			}else{
				this.commentState=""
				this.orderState=""
				this.orderStateList = []
				this.payState=""
				this.orderRefundState=""
			}
			this.pageNum=1;
			this.tableList=[]
			this.getList()
		},
		
		// 处理订单状态展示
		handleOrderState(state) {
		  switch (state) {
			case 1:
			  return '已下单'
			case 2:
			  return '已完成'
			case 3:
			  return '已退单'
			 
		  }
		},
		//筛选
		openPopup() {
			this.localShow = true
		}, 
		//取消筛选
		closePopup() {
			this.localShow = false
		},
		// 选择日期区间
		selectDateOption(index) {
			this.currentDateOption = Number(index) 
			const months = Number(this.dateOptions[index].value) 
			const end = new Date() 
			const start = new Date() 
			start.setMonth(start.getMonth() - months) 
			this.startDate = this.formatDate(start) 
			this.endDate = this.formatDate(end) 
		},
		selectStartDate(e) {
			console.log('selectStartDate', e)
			const timeFormat = uni.$u.timeFormat
			this.startDate = timeFormat(e.value, 'yyyy-mm-dd')
			this.currentDateOption = -1 // 清除快速选择的高亮
			this.showStartCalendar = false
		},
		selectEndDate(e) {
			const timeFormat = uni.$u.timeFormat
			this.endDate = timeFormat(e.value, 'yyyy-mm-dd')
			this.currentDateOption = -1
			this.showEndCalendar = false
		},
		// 选择类型
		selectOrderType(id,index) {
			var hasIndex = this.selectedOrderTypes.findIndex((item) => {
			  return item==id
			})
			if (hasIndex > -1) {
				this.selectedOrderTypes.splice(hasIndex, 1)
			} else {
				this.selectedOrderTypes.push(id)
			}
		},
		clearAll() {
			this.currentDateOption = -1
			this.startDate = ""
			this.endDate = ""
			this.selectedOrderTypes = []
			this.orderTypeList=[]
		},
		confirm() {
			// if (!this.startDate || !this.endDate) {
			// 	uni.$u.toast('请选择完整的日期范围')
			// 	return
			// }
			// console.log(this.selectedOrderTypes)
			if(this.selectedOrderTypes.length>0){
				let orderTypes = this.selectedOrderTypes.join(","); 
				this.orderTypeList = orderTypes.split(",")
			}else{
				this.orderTypeList=[]
			}
			this.closePopup()
			this.pageNum=1;
			this.tableList=[]
			this.getList() 
		},
		//退单
		refundOrder(item) {
			let param = {
				"orderId": item.orderId, 
			}
			this.$modal.confirm('确定取消订单吗？').then(() => {
				refundOrderApi(param).then((res) => {
					if(res.code==200){
						uni.showToast({
						  title: "操作成功",
						  icon: 'none'
						})
						setTimeout(()=>{
							this.getOrderDetail()
						},500)
					}else{
						uni.showToast({
						  title: res.msg,
						  icon: 'none'
						}) 
					}
				}).catch((res)=>{
						uni.showToast({
						  title: res.msg,
						  icon: 'none'
						}) 
				}) 
			}) 
		},
		//立即支付
		goPay(item) {
			console.log(item)
			let param = {
				"orderId": item.orderId,
			}
			this.$modal.confirm('确定立即支付该订单吗？').then(() => {
				payOrderApi(param).then((res) => {
					console.log(res)
					if(res.code==200){
						uni.showToast({
						  title: "操作成功",
						  icon: 'none'
						})
						setTimeout(()=>{
							this.getList()
						},500)
					}else{
						uni.showToast({
						  title: res.msg,
						  icon: 'none'
						}) 
					}
				}) 
			})
			
		},
		
		
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 跳转订单详情
		goDetail(item) {
			console.log('跳转订单详情', item)
			uni.navigateTo({
				url: `/pages/work/details?params=${JSON.stringify(item)}`
			})
		},
		//评价按钮
		goEvaluate(item) {
			console.log('跳转订单详情', item)
			uni.navigateTo({
				url: `/pages/work/evaluate?params=${JSON.stringify(item)}`
			})
		},
		//跳转评价中心
		goEvaluateCenter() {
			uni.navigateTo({
				url: `/pages/work/evaluateCenter?startDate=${this.startDate}&endDate=${this.endDate}`
			})
		},
	},
	// onUnload() {
	// 	uni.switchTab({
	// 	  url: '/pages/index'
	// 	})
	// },
	// onBackPress(e) {
	// 	//e.from === 'backbutton' 说明如果点击的是物理返回键或导航栏的返回键就进行以下操作
	// 	if (e.from === 'backbutton') {
	// 	  //返回值为true 时,表示不执行默认的返回（默认返回上一页），执行自定义的返回
	// 	  uni.switchTab({
	// 	    url: '/pages/index'
	// 	  })
	// 	  //如果要限制必须写成true
	// 	  return true;
	// 	}
	// },
}
</script>

<style lang="scss" scoped>
.content {
  background: #f9fbff;
  // height: 100%;
  height: 95vh;
  padding-top: 3vh;
  

	.top-wrapper {
		// position: fixed;
		/* top: 44px; */
		// top: 1vh;
		width: 100vw;
		background: #f9fbff;
		z-index: 999;
	}

	.top-cont {
		padding: 0 16px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		.top-title {
			font-weight: 500;
			font-size: 40rpx;
			color: #0f274b;
		}
		.top-ipt {
			height: 31px;
			background: #fff;
			margin-left: 26px;
			margin-right: 12px;
		}
		.top-filter {
			display: flex;
			align-items: center;
		}
	}

	.order-list {
		padding: 8px;
		background: #fff;
		border-radius: 8px;
		font-size: 24rpx;
		font-weight: 400;
		// margin-bottom: 12px;
		margin-top: 10px;

		.order-source {
			margin-bottom: 12px;
			font-weight: 500;
			color: #0f274b;
		}

		.intervalName {
			margin-left: 10px;
			color: #ff6816;
			border-radius: 1px 1px 1px 1px;
			border: 1px solid #ff6816;
			padding: 0 4px;
		}

		.img-cont {
			width: 100%;
			margin: 5px;
			display: flex;
			justify-content: space-between;
			width: 100%; 
		}
		.img {
			width: 28%;
			margin: 10rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
				view {
					margin-top: 8px;
					color: #0f274b;
				}
		}
		.price {
			width: 20%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #0f274b;
			font-weight: 400;
			font-size: 24rpx;
		}

		.btn-cont {
			display: flex;
			justify-content: flex-end;
			margin-top: 10px;
		}
	}
}
.evaluateCenter{
	height: 30px;width: 100%;display: flex;justify-content: space-between;align-items: center;
	.evaluateCenterLeft{
		width: 28%;display: flex;justify-content: space-between;align-items: center;margin-left: 20px;font-size: 28rpx;
	}
	.evaluateCenterRight{
		width: 60px;height: 24px;line-height:24px;border: 1px solid #ff6816;color: #ff6816;margin-right: 20px;font-size: 24rpx;text-align: center;border-radius: 8px;
	}
}
.filter-popup {
  padding: 30rpx;
  min-height: 45vh;
  max-height: 80vh;
	.section {
		margin-bottom: 40rpx;

		.section-title {
		  font-size: 32rpx;
		  color: #333333;
		  font-weight: 500;
		  margin-bottom: 20rpx;
		}
	}

	.date-quick-select {
		display: flex;
		gap: 20rpx;
		margin-bottom: 20rpx;

		.date-option {
		  flex: 1;
		  height: 80rpx;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		  background-color: #f8f8f8;
		  border-radius: 100rpx;
		  font-size: 28rpx;
		  color: #666666;

		  &.active {
			background-color: #fff2ef;
			color: #ff6633;
		  }
		}
	}

	.date-range {
		display: flex;
		align-items: center;
		gap: 20rpx;

		.date-input {
		flex: 1;
		height: 80rpx;
		background-color: #f8f8f8;
		border-radius: 100rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;

		.date-placeholder {
		color: #999999;
		}

		.selected-date {
		color: #333333;
		}
		}

		.date-separator {
		color: #999999;
		font-size: 28rpx;
		}
	}

	.order-type-item {
		width: 200rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f8f8;
		border-radius: 25px;
		font-size: 28rpx;
		color: #666666;
		margin: 10rpx auto;

		&.active {
		  background-color: #fff2ef;
		  color: #ff6633;
		}
	}

	.bottom-buttons {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 28px 16rpx;
		background-color: #ffffff;
		display: flex;
		justify-content: space-between;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
}
</style>
