<template>
	<view class="pages">
		<u-navbar title="订单统计" :border-bottom="false" :background="bgc" title-color='#fff' back-icon-color="#fff"
			title-size='36' height='50'></u-navbar>
		<!-- 快捷选择 -->
		<view class="ordertongji">
			<view class="orderday">
				<view class="sj">
					<text @click="btnriq(1)" :class="dateindex == 1 ? 'dateactive' : ''">今日</text>
					<text @click="btnriq(2)" :class="dateindex == 2 ? 'dateactive' : ''">昨日</text>
					<text @click="btnriq(3)" :class="dateindex == 3 ? 'dateactive' : ''">近七日</text>
					<text @click="btnriq(4)" :class="dateindex == 4 ? 'dateactive' : ''">本月</text>
				</view>
			</view>
		</view>
		<view class="time">
			<!-- <view class="timetit">
				时间范围
			</view> -->
			<view class="timert">
				<view style="margin-right: 10rpx;" class="xztime" @click="btnks(1)">{{endtime}} <image src="https://api.ccttiot.com/smartmeter/img/static/u2x4BXCLOru9JkebEuQx" mode=""></image> </view> <text style="color: #fff;">—</text> <view
					style="margin-left: 10rpx;" class="xztime" @click="btnks(2)">{{lasttime}} <image src="https://api.ccttiot.com/smartmeter/img/static/u2x4BXCLOru9JkebEuQx" mode=""></image> </view> 
				<view class="qinc" @click="btnqc">×</view>
			</view>
		</view>

		<view class="serch">
			<input type="text" v-model="type" placeholder="请输入店铺名称"/>
			<view class="" @click="btnsear">搜索</view>
		</view>
		<view class="zongji">
			<view class="lt">
				<view class="name">
					完成总订单
				</view>
				<view class="price">
					{{totalOrder == null ? 0 : totalOrder}} <text style="font-size: 36rpx;">单</text>
				</view>
			</view>
			<view class="lt">
				<view class="name">
					订单总金额
				</view>
				<view class="price">
					{{totalOrderAmount  == null ? 0 : totalOrderAmount}} <text style="font-size: 36rpx;">元</text>
				</view>
			</view>
		</view>
		<u-picker mode="time" v-model="show" :params="params" @confirm="confirm"></u-picker>

		
		<view class="table-container">  
		    <view  
		      v-for="(row, index) in tableData"  
		      :key="row.storeId"  
		      class="table-row"  
		      @click="toggleRow(index,row.storeId)">  
			  <view class="" style="margin-bottom: 20rpx;">
			  	 <text style="font-size: 32rpx;font-weight: 600;">{{ row.storeId == -1 ? '未分配店铺设备' : '店铺：' + row.storeName }}</text>  
			  </view>
			  <view class="tab">
			  	<view class="">设备</view>
			  	<view class="">订单数</view>
			  	<view class="">时长</view>
			  	<view class="">电量</view>
			  	<view class="">金额</view>
			  </view>
		      <view class="row-header">  
				<text class="">{{row.deviceCount}}台</text>
				<text class="">{{row.orderCount}}单</text>
				<text class="" style="width: 19%;">{{row.formattedDuration}}</text>
				<text class="">{{row.ele}}度</text>
				<text class="">{{row.arrivalAmount}}元</text>
		      </view>  
		      <view v-if="!row.folded" class="row-details" v-for="(val,index) in vallist" :key="index">  
		        <view>{{val.deviceName == null ? '未命名': val.deviceName}}</view>  
		        <view>{{val.orderCount}}单</view>  
		        <view>{{val.formattedDuration}}</view>  
				<view>{{val.ele}}度</view>  
		        <view>{{val.arrivalAmount}}元</view>  
		      </view>  
			  <view  class="" style="width: 100%;text-align: center;margin-top: 20rpx;align-items: center;display: flex;justify-content: center;">
			  	 点击展开 <image style="width: 32rpx;height: 32rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uO5pr0UkQAr3R98MM9dG" mode=""></image>
			  </view>
		    </view>  
		  </view>  

	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#8883F0",
				},
				statusList: '',
				type: '',
				endtime: '',
				lasttime: '',
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				show: false,
				num: '',
				tableData: [],  
				vallist:[],
				previouslyExpandedIndex: null,
				dateindex:1,
				totalOrder:'',
				totalOrderAmount:''
			}
		},
		onLoad() {
			const todayStartTime = this.getTodayStartTime()
            this.endtime = this.formatDate(todayStartTime)
			 // this.endtime = '2024-01-09'
			this.lasttime = this.formatDate(todayStartTime)
			this.getList()
		},
		onShow() {

		},
		// 分享到好友（会话）
		onShareAppMessage: function() {
			return {
				title: '创想物联',
				path: '/pages/shouye/index'
			}
		},

		// 分享到朋友圈  
		onShareTimeline: function() {
			return {
				title: '创想物联',
				query: '',
				path: '/pages/shouye/index'
			}
		},
		methods: {
			btnriq(num) {
				this.dateindex = num
				if (num == 1) {
					let today = new Date();
					this.endtime = this.formatDate(today)
					this.lasttime = this.formatDate(today)
					this.getList()
				} else if (num == 2) {
					let yesterday = new Date()
					yesterday.setDate(yesterday.getDate() - 1)
					this.endtime = this.formatDate(yesterday)
					this.lasttime = this.formatDate(yesterday)
					this.getList()
				} else if (num == 3) {
					let today = new Date()
					let firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6)
					this.endtime = this.formatDate(firstDayOfMonth)
					this.lasttime = this.formatDate(new Date())
					this.getList()
				} else if (num == 4) {
					let today = new Date()
					let firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 1)
					let lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), today.getDate())
					this.endtime = this.formatDate(firstDayOfLastMonth)
					this.lasttime = this.formatDate(lastDayOfLastMonth)
					this.getList()
				} 
			},
			formatDate(date) {
				let year = date.getFullYear()
				let month = String(date.getMonth() + 1).padStart(2, '0')
				let day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			
			// 请求统计列表
			getList(){
				this.$u.get(`/mch/dashboard/businessStatisticsByStore?storeName=${this.type}&dateRange=${this.endtime+ ',' +this.lasttime}`).then((res) => {
					if (res.code == 200) {
					  this.totalOrder = res.data.totalOrder
					  this.totalOrderAmount = res.data.totalOrderAmount
					  let arr = res.data.list
					  this.tableData = arr.map(item => ({  
					    ...item,   
					   folded: true,
					   formattedDuration: this.formatDuration(item.seconds)
					  }))
					}
				})
			},
			
			formatDuration(seconds) {
			  const days = Math.floor(seconds / (3600 * 24));
			  const remainingSeconds = seconds % (3600 * 24);
			  const hours = Math.floor(remainingSeconds / 3600);
			  const minutes = Math.floor((remainingSeconds % 3600) / 60);
			  return `${days.toString().padStart(2, '0')}天${hours.toString().padStart(2, '0')}小时${minutes.toString().padStart(2, '0')}分钟`;
			}, 
			
			// 点击搜索
			btnsear(){
				if(this.endtime == '' || this.endtime == ''){
					uni.showToast({
						title: '时间范围不能为空',
						icon: 'none',
						duration:2000 
					})
				}else{
					this.getList()
					this.dateindex = ''
				}
			},
			// 获取当天时间
			getTodayStartTime() {  
			  const now = new Date();  
			  const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);  
			  return startOfDay;  
			},
			// 调用函数并打印结果  
			formatDate(date) {  
			  const year = date.getFullYear();  
			  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零  
			  const day = String(date.getDate()).padStart(2, '0'); // 补零  
			  const hours = String(date.getHours()).padStart(2, '0'); // 补零（虽然这里总是00）  
			  const minutes = String(date.getMinutes()).padStart(2, '0'); // 补零  
			  const seconds = String(date.getSeconds()).padStart(2, '0'); // 补零  
			  return `${year}-${month}-${day} `;  
			},
			
		    // 点击展开折叠
			toggleRow(index,storeId) {  
				if(this.endtime == '' || this.endtime == ''){
					uni.showToast({
						title: '时间范围不能为空',
						icon: 'none',
						duration:2000 
					})
				}else{
					this.$u.get(`/mch/dashboard/businessStatisticsByDevice?storeId=${storeId == null ? '' : storeId}&dateRange=${this.endtime+ ',' +this.lasttime}`).then(res => {
						if(res.code == 200){
							let arr = res.data
							this.vallist = arr.map(item => ({
							  ...item,   
							 formattedDuration: this.formatDuration(item.seconds)
							}))
							// 如果之前有展开的行，则将其折叠
							if (this.previouslyExpandedIndex !== null && this.previouslyExpandedIndex !== index) {  
							  this.$set(this.tableData, this.previouslyExpandedIndex, {  
							    ...this.tableData[this.previouslyExpandedIndex],  
							    folded: true  
							  });  
							}  
							// 展开当前行  
							this.$set(this.tableData, index, {  
							  ...this.tableData[index],  
							  folded: false  
							});  
							// 更新之前展开行的索引  
							this.previouslyExpandedIndex = index; 
						}
					})
				}   
			  },
			  
			// 选择时间
			btnks(num) {
				this.show = true
				if (num == 1) {
					this.num = 1
				} else {
					this.num = 2
				}
			},

			// 清除时间
			btnqc() {
				this.endtime = ''
				this.lasttime = ''
			},
			// 确定时间
			confirm(e) {
				if (this.num == 1) {
					this.endtime = e.year + '-' + e.month + '-' + e.day 
				} else {
					this.lasttime = e.year + '-' + e.month + '-' + e.day 
				}
			},
		},
	}
</script>

<style lang="scss">
	/deep/ .u-title {
		padding-bottom: 22rpx;
	}

	/deep/ .uicon-nav-back {
		padding-bottom: 22rpx;
	}
	page{
		background-color: #F6F6F6;
		width: 100%;
		height: 100vh;
	}
	.input-placeholder{
		color: #fff;
	}
	.dateactive {
		color: #fff !important;
	}
	.ordertongji {
		width: 100%;
		background: #8883F0;
		.shuju {
			display: flex;
			justify-content: space-between;
			box-sizing: border-box;
			margin-top: 24rpx;
			.sjone{
				margin: auto;
				text-align: center;
				.je{
					font-size: 40rpx;
					color: #3D3D3D;
					font-weight: 600;
				}
				.shu{
					font-size: 20rpx;
					color: #3D3D3D;
					margin-top: 20rpx;
				}
			}
		}
	
		.date {
			padding-left: 80rpx;
			padding-right: 80rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			margin-top: 26rpx;
			text {
				padding: 6rpx 18rpx;
				box-sizing: border-box;
				background: #eee; 
				border-radius: 10rpx 10rpx 10rpx 10rpx;
				font-size: 24rpx;
				color: #808080;
			}
		}
	
		.orderday {
			display: flex;
			justify-content: space-between;
			width: 750rpx;
			padding: 10rpx 76rpx;
			box-sizing: border-box;
			border-bottom: 2rpx solid #FFFFFF;
			padding-bottom: 24rpx;
			.sj{
				display: flex;
				justify-content: space-between;
				width: 750rpx;
			}
			text { 
				color: #ccc;
				font-size: 34rpx;
			}
		}
	}
	.table-container {  
	  width: 100%;
	  view{
		  
	  }
	}  
	  
	.table-row {  
	  margin-bottom: 40rpx;  
	  border-bottom: 1rpx solid #ddd;  
	  padding: 20rpx;
	  box-sizing: border-box;
	  width: 100%;
	  background-color: #fff;
	  padding: 20rpx;
	  box-sizing: border-box;
	  border-radius: 0 0 50rpx 50rpx;
	}  
	  
	.row-header {  
	  display: flex;  
	  justify-content: space-between;  
	  align-items: center;  
	  padding: 10rpx;  
	  background-color: #f5f5f5;  
	  cursor: pointer;  
	  height: 140rpx;
	  text{
		  width: 16%;
		  text-align: center;
		  overflow: scroll;
	  }
	}  
	  
	.row-details {  
	  padding: 10rpx;  
	  background-color: #fff;  
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  view{
		  width: 16%;
		  text-align: center;
		  overflow: scroll;
	  }
	}  
	  
	.folded-count {  
	  margin-top: 20rpx;  
	  font-size: 30rpx;  
	  text-align: center;  
	}  
    .list{
		padding: 0 30rpx;
		box-sizing: border-box;
	}
	.tab {
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		background-color: #fff;
		height: 50rpx;
		view{
			width: 16%;
			text-align: center;
			overflow: scroll;
			font-size: 32rpx;
		}
	}
    .zongji{
		width: 100%;
		background-color: #8883F0;
		display: flex;
		justify-content: space-between;
		padding: 0 120rpx;
		box-sizing: border-box;
		padding-bottom: 28rpx;
		.lt{
			text-align: center;
			.name{
				font-weight: 600;
				font-size: 28rpx;
				color: #FFFFFF;
			}
			.price{
				margin-top: 12rpx;
				font-weight: 600;
				font-size: 52rpx;
				color: #FFFFFF;
			}
		}
	}
	.serch {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 40rpx;
		box-sizing: border-box;
		height: 120rpx;
		background-color: #8883F0;
        
		input {
			width: 100%;
			height: 60rpx;
			line-height: 60rpx;
			padding-left: 30rpx;
			border: 1px solid #fff;
			border-radius: 10rpx;
			color: #fff;
		}

		view {
			width: 170rpx;
			height: 60rpx;
			line-height: 60rpx;
			text-align: center;
			color: #8883F0;
			background-color: #D9D8FF;
			border-radius: 10rpx;
			margin-left: 30rpx;
		}
	}

	.time {
		height: 100rpx;
		padding-top: 20rpx !important;
		padding: 0 40rpx;
		box-sizing: border-box;
		background-color: #8883F0;
        
		.timetit {
			font-weight: 600;
			font-size: 30rpx;
		}

		.timert {
			display: flex;
			line-height: 60rpx;
			justify-content: space-between;
			margin-top: 20rpx;

			.xztime {
				width: 300rpx;
				height: 60rpx;
				border: 1px solid #fff;
				border-radius: 10rpx;
				text-align: center;
				background-color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				image{
					width: 30rpx;
					height: 30rpx;
					margin-left: 20rpx;
				}
			}

			.qinc {
				font-size: 50rpx;
				color: #fff;
				width: 80rpx;
				height: 60rpx;
				text-align: center;
			}
		}
	}
</style>