<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
  <view class="page">
    <h3>配送方式</h3>
    <div class="appraise" @click="showPicker = true">
      <div>{{ detailData.deliveryTypeStr }}</div>
      <div class="flex appraise-right">
        <u-icon name="arrow-right" size="12" />
      </div>
    </div>
    <div class="cont">
		<div class="flex justify-between m-8">
			<div class="top-source m-8">订单类型: 预订餐</div>
			<div>就餐日期: {{ shoppingCartList[0].orderDate }}</div>
		</div>
     
		<div class="flex justify-between m-8">
			<div class="flex align-center">
			  <div>{{ canteenName }}/{{stallName}}</div> 
			</div>
		</div>
      <div class="img-cont m-8">
        <div class="img-list m-8" v-for="(item, index) in shoppingCartList" :key="index">
          <div class="flex align-center">
            <u-image :src="item.goodsImgUrl" width="80px" height="80px" />
            <div class="name-num">
              <div style="margin-bottom: 10px">{{ item.goodsName }} ({{item.mealtimeName}})</div>
              <div>x{{ item.quantity }}</div>
            </div>
          </div>
          <div>￥{{ ((item.prefPrice/100)*(item.quantity)).toFixed(2) }}</div>
        </div>
      </div>
      <div class="flex justify-between m-8 bt">
        配送费
        <div>{{ detailData.deliveryFee||"免配送费" }}</div>
      </div>
      <div class="flex justify-between m-8 bt">
        包装费
        <div>{{ detailData.packingFee||"免包装费" }}</div>
      </div>
      <div class="flex justify-between align-center m-8 bt">
        备注
        <u-input v-model="detailData.remark" placeholder="请填写备注信息" border="none" inputAlign="right"></u-input>
      </div>
      <u-line />
      <div class="flex justify-between m-8 realAmount">
        小计
        <div>￥{{ totalPrice }}</div>
      </div>
    </div>
    <div class="order">
      <div class="m-8 bt" style="font-weight: 800">支付方式</div>
      <div class="flex justify-between align-center m-8">
        <div class="flex justify-between align-center">
          <u-icon name="/static/images/remaining-sum.png" size="36" />
          <div style="margin-left: 10px">
            <div>钱包支付</div>
            <div style="font-size: 24rpx; color: rgba(15, 39, 75, 0.6)">推荐使用</div>
          </div>
        </div>
        <u-icon name="/static/images/active-circle.png" size="20" />
      </div>
    </div>

    <div style="height: 60px"></div>
    <div class="shop-car">
      <div class="car-cont">
        <div class="flex align-center">
          <span class="money">
            <span style="font-size: 13px">实付款￥</span>
            {{ totalPrice }}
          </span>
        </div>

        <div>
          <u-button shape="circle" color="#FF6816" style="width: 100px; height: 28px;font-size: 28rpx;" @click="handleOrder()">
            提交订单
          </u-button>
        </div>
      </div>
    </div>

    <u-picker
      :show="showPicker"
      :columns="columns"
      keyName="label"
      @cancel="showPicker = false"
      @confirm="confirm"
    ></u-picker>
  </view>
</template>

<script> 
	import { getListElectronMobileUsableAPI,addReserveMealApi,clearAdvancehoppingCartAPI } from '@/api/advanceOrder/index.js'
export default {
  props: {},
  data() {
    return {
		fontValue:uni.getStorageSync('fontSize') || 8,
		canteenId:"",
		canteenName:"",
		stallId:"",
		stallName:"",
		totalPrice:0,
		orderDate:"",
		shoppingCartList:[],
		shoppingCartList2:[],
      // 详情页数据
      detailData: {
        // 订单状态
        deliveryType: 5,
        deliveryTypeStr: '自取外带',
        // 订单来源
        orderSource: '预订餐',
        // 餐厅名称
        canteenName: '',
        // 餐次
        canteenType: '',
        // 就餐时间
        diningTime: '',
        // 菜品
        addFood: [],
        remark: '', // 备注
        // 支付方式
        payType: '小程序二维码支付'
      },
	  sumbitStatus:false,
      showPicker: false, // 是否显示选择器
      // 选择器数据
      columns: [
        [
			{
				label: '自取外带',
				value: '5'
			},
			{
				label: '自取堂食',
				value: '1'
			}
        ]
      ]
    }
  },
  onLoad(options) {
	this.canteenId = options.canteenId
	this.canteenName = options.canteenName
	this.stallId = options.stallId
	this.stallName = options.stallName 
	this.totalPrice = Number(options.totalPrice).toFixed(2)
	this.orderDate = options.orderDate;
	this.shoppingCartList=JSON.parse(options.carList)
	this.shoppingCartList2=JSON.parse(options.carList)
	console.log(this.shoppingCartList) 
	// this.getListElectronMobileUsable()
  },
  methods: {
	//（获取餐卷）
	// async getListElectronMobileUsable(){
	//   	let param = {
	//   		"userId":uni.getStorageSync('userId'),
	// 		"canteenIdSet":[this.canteenId],
	//   		"shopstallIdSet":[this.stallId],
	// 		"intervalIdSet":[this.shoppingCartList[0].mealtimeType]
	//   	}
	//   	const res = await getListElectronMobileUsableAPI(param)
	//   	console.log(res, '获取餐卷')
	   
	// },
    confirm(e) {
      console.log('?? ~ confirm ~ value:', e)
      this.showPicker = false
      this.detailData.deliveryType = e.value[0].value
      this.detailData.deliveryTypeStr = e.value[0].label
    },
	getNowFormatDate() {
	  let date = new Date()
	  let year = date.getFullYear()
	  let month = (date.getMonth() + 1).toString().padStart(2, '0')
	  let day = date.getDate().toString().padStart(2, '0')
	  let hours = date.getHours().toString().padStart(2, '0');
	  let minutes = date.getMinutes().toString().padStart(2, '0');
	  let seconds = date.getSeconds().toString().padStart(2, '0');
	  return `${year}-${month}-${day}`
	},
	async handleOrder(){
		if(!this.sumbitStatus){
			this.sumbitStatus = true 
			let mealtimeTypeList = [];//餐次数组
			let orderList = []  
			// console.log(this.shoppingCartList) 
			this.shoppingCartList.forEach(item=>{
				let index = mealtimeTypeList.findIndex(v=>v==item.mealtimeType)
				if(index<0){//不存在
					mealtimeTypeList.push(item.mealtimeType)
					let obj = {
						"canteenId": this.canteenId,
						"canteenName": this.canteenName,
						"stallId": this.stallId,
						"stallName": this.stallName,  
						"mealtimeType": item.mealtimeType, 
						"mealtimeName": item.mealtimeName, 
						"orderDate": this.orderDate,
						"orderType": 2,
						"orderDetailList": item.orderDetailList
					}
					orderList.push(obj) 
				}else{
					let index2 = orderList.findIndex(v=>v.mealtimeType==item.mealtimeType)
					let index3 = orderList[index2].orderDetailList.findIndex(v=>v.cartId==item.orderDetailList[0].cartId)
					if(index3<0){
						orderList[index2].orderDetailList.push(item.orderDetailList[0])
					}
				}
			})
			// console.log(orderList)
			let param={
				"realAmount": this.totalPrice*100, 
				"payableAmount": this.totalPrice*100,  
				"userId": uni.getStorageSync('userId'),  
				"placeDate": this.getNowFormatDate(),  
				"payType": 1,
				"sourceType": 7,
				"isOnline": 1,
				"deliveryType": this.detailData.deliveryType,
				"remark": this.detailData.remark,
				"orderList":orderList
			}
			console.log(param)
			addReserveMealApi(param).then((res)=>{ 
				if(res.code==200){
					uni.showToast({
					  title: res.msg,
					  icon: 'none'
					})
					this.clearShoppingCart()
					setTimeout(()=>{
						this.sumbitStatus = false
						uni.switchTab({
						  url: `/pages/work/index`
						})
					},1000) 
				}
			}).catch(()=>{
				this.sumbitStatus = false;
				// this.$set(this,'shoppingCartList',this.shoppingCartList2) 
			})
		}
	},
	async clearShoppingCart(){ 
		let param = {
			"userId":uni.getStorageSync('userId'),
			"cartIds":[], 
		}
		console.log(this.shoppingCartList)
		this.shoppingCartList.forEach(cartItem=>{ 
			param.cartIds.push(cartItem.cartId) 
		})
		console.log(param)
		const res = await clearAdvancehoppingCartAPI(param)
	},
	
	
	
  }
}
</script>

<style lang="scss" scoped>
.page {
  background: #f9fbff;
  padding: 16px;
  min-height: 100vh;
  color: #0f274b;
}
.appraise {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  margin: 8px 0 20px;
  .appraise-right {
    color: #ff6816;
  }
}
.m-8 {
  margin: 0 8px;
}
.bt {
  margin-bottom: 16px;
}
.cont {
  background: #fff;
  border-radius: 8px;
  padding: 8px 0;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  .top-source {
    font-weight: 800;
    margin-bottom: 12px;
  }
  .tag {
    margin-left: 5px;
    min-width: 40px;
    border-radius: 1px 1px 1px 1px;
    border: 1px solid #ff6816;
    color: #ff6816;
    display: flex;
	font-size: 20rpx;
    justify-content: center;
    align-items: center;
  }
  .img-cont {
    margin: 20px 0;
    .img-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      .name-num {
        margin-left: 10px;
      }
    }
  }
  .realAmount {
    margin-top: 16px;
    font-size: 32rpx;
    font-weight: 800;
  }
}
.order {
  margin-top: 16px;
  padding: 8px 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
.shop-car {
  height: 60px;
  background: #fff;
  box-shadow: 0px -1px 4px 0px rgba(0, 102, 204, 0.1);
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;

  .car-cont {
    margin: 15px 20px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .money {
      margin-left: 8px;
      font-weight: 600;
      font-size: 36rpx;
      color: #0f274b;
    }
  }
}
</style>
