<style lang='scss' scoped>
.electricity{
	width: 100%;
	background-color: #f9f9f9;
	&-header{
		display: flex;
		justify-content: space-between;
		background-color: #fff;
		&-household,&-last{
			width: 50%;
			text-align: center;
			padding: 20rpx 0;
			border-bottom: 1px solid #eee;
		}
	}
	&-chart-ctn{
		padding: $paddingTB $paddingLR;
	}
	&-chart{
		width: 100%;
		background-color: #fff;
		padding: 20rpx;
		&-info{
			display: flex;
			padding-bottom: 10rpx;
			.current-month{
				border-right: 1px solid #eee;
			}
			.current-month,.last-month{
				width: 50%;
				text-align: center;
			}
		}
		&-bottom-info{
			color: #FA6400;
			text-align: center;
			padding-top: 10rpx;
		}
	}
	&-info-list{
		padding: $paddingTB $paddingLR;
		/* background-color: #f9f9f9; */
		width: 100%;
	
	}
	&-info-box{
		background-color: #fff;
		padding: 10rpx;
		padding-top: 0;
		&-header{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1px solid #eee;
		}
		&-degree{
			text-align: center;
			/* display: flex; */
			/* justify-content: center; */
			padding: 20rpx 0;
			&-num{
				font-size: 50rpx;
				color: #FA6400;
				padding: 0 20rpx;
			}
		}
	}
}
.last-electricity-content{
	padding: 30rpx $paddingLR;
	.month,.contrast{
		background-color: #fff;
		&-header{
			padding: 20rpx;
			display: flex;
			align-items: center;
		}
		.contrast-text{
			text-align: center;
			color: #FA6400;
			font-size: 32rpx;
			padding: 20rpx 0;
		}
	}
}



</style>
<template>
	<view class="electricity">
		<view class="electricity-header">
			<view class="electricity-header-household" @click="swtichTabsFn('household')" 
			:style="{borderColor: currentTab=='household'?'#1C9AFF':'#eee',color:currentTab=='household'?'#1C9AFF':'#111'}">每户的用电情况</view>
			<view class="electricity-header-last" @click="swtichTabsFn('last')" 
			:style="{borderColor: currentTab=='last'?'#1C9AFF':'#eee',color:currentTab=='last'?'#1C9AFF':'#111'}">近两年用电量情况</view>
		</view>
		<view v-if="currentTab=='household'">
			<view class="electricity-chart-ctn">
				<view class="electricity-chart">
					<view class="electricity-chart-info">
						<view class="current-month">
							<view class="pb15">当月用电量(度)</view>
							<view style="color: #FA6400;">{{ chartData.currentMonth || '0' }}</view>
						</view>
						<view class="last-month">
							<view class="pb15">上月用电量(度)</view>
							<view style="color: #FA6400;">{{ chartData.lastMonth || '0' }}</view>
						</view>
					</view>
					<Arcbar :chartData="arcbarChartData" offsetY="-10" subtitleFontSize="10" width="630" height="300" ></Arcbar>
					<view class="electricity-chart-bottom-info">
						当月对比上月
						{{ chartData.ringRatio > 0 ? '增加' : '节约' }}
						{{ chartData.ringRatio ? Math.abs(chartData.ringRatio) : 0 }}
						%
					</view>
				</view>
			</view>
			<pickerGroup
				:leftSelectList="spaceList"
				leftValueName="id"
				:leftValue="leftValue"
				:rightValue="rightValue"
				rightSelectType="date"
				@onLeftConfirm="onLeftConfirm"
				@onDateChange="onRightConfirm"
				leftMode="mutil-column-auto"
			></pickerGroup>
			<mescroll-body top="0" ref="mescrollRef" height="860rpx" bottom="80" @init="mescrollInit" @down="downCallback" @up="upCallback">
				<view class="electricity-info-list">
					<view class="electricity-info-box mb20" v-for="(item, index) in electricityList" :key="index" @click="goElectricityDetailFn(item)">
						<view class="electricity-info-box-header">
							<view class="left">
								<tuiIcon name="ditu2" color="#1C9AFF"></tuiIcon>
								<text class="pl10 text-bold">{{ item.deviceAddr || '' }}</text>
							</view>
							<view class="right">
								<tuiIcon :name="item.deviceState === 'ONLINE' ? 'zaixian' : 'lixian2'" :color="setColor(item.deviceState)"></tuiIcon>
								<text class="pl10" :style="{color: setColor(item.deviceState)}">{{ getStateName(item.deviceState) }}</text>
							</view>
						</view>
						<view class="electricity-info-box-degree">
							<text class="">电量</text>
							<text class="electricity-info-box-degree-num">{{ item.electricity || '0' }}</text>
							<text class="">度</text>
						</view>
						<view class="flex-between" style="font-size: 22rpx;color:#666666;">
							<view class="">设备号：{{ item.deviceKey || '' }}</view>
							<!-- <view class="">联系人：林工 15860888888</view> -->
						</view>
					</view>
				</view>
			</mescroll-body>
		</view>
		<view v-else-if="currentTab=='last'">
			<view class="last-electricity-content">
				<view class="month mb20">
					<view class="month-header">
						<tuiIcon name='tongjifenxi' color="#FA6400"></tuiIcon>
						<text class="pl20">各月用电量</text>
					</view>
					<columnScroll :chartData="monthChartData" width="670" height="400"></columnScroll>
				</view>
				<view class="contrast">
					<view class="contrast-header">
						<tuiIcon name='tongjifenxi' color="#FA6400"></tuiIcon>
						<text class="pl20">电量同比</text>
					</view>
					<lineScroll :chartData="onYearChartData" width="670" height="400"></lineScroll>
					<view class="contrast-text">
						用电量对比去年1-12月
						{{ nearYearCount > 0 ? '增加' : '减少'}}
						{{ Math.abs(nearYearCount) }}
						度
					</view>
					<rotateScroll :chartData="nearYearChartData" width="670" height="400"></rotateScroll>
					<view style="margin-bottom: 100rpx;"></view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import Arcbar from "@/components/uchartComponents/Arcbar.vue";
	import pickerGroup from "@/components/electricalSafe/pickerGroup.vue";
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import columnScroll from "@/components/uchartComponents/column-scroll.vue";
	import lineScroll from "@/components/uchartComponents/line-scroll.vue";
	import rotateScroll from "@/components/uchartComponents/rotate-scroll.vue";
	const stateArr = [
		{
			label: '在线',
			value: 'ONLINE'
		},
		{
			label: '离线',
			value: 'OFFLINE'
		},
		{
			label: '脱线',
			value: 'OUTLINE'
		},
		{
			label: '未启用',
			value: 'UNACTIVE'
		},
	];
	
	const nameArr = [
		{
			key: 1,
			value: 'nowData',
			type: 'year',
			label: '今年',
		},
		{
			key: 2,
			value: 'pastData',
			type: 'year',
			label: '去年',
		},
		{
			key: 3,
			value: 'nowData',
			type: 'month',
			label: '本月',
		},
		{
			key: 4,
			value: 'pastData',
			type: 'month',
			label: '上月',
		},
		{
			key: 5,
			value: 'nowData',
			type: 'week',
			label: '本周',
		},
		{
			key: 6,
			value: 'pastData',
			type: 'week',
			label: '上周',
		},
		{
			key: 7,
			value: 'nowData',
			type: 'day',
			label: '今天',
		},
		{
			key: 8,
			value: 'pastData',
			type: 'day',
			label: '昨天',
		},
	];
	
	export default {
		data() {
			return {
				arcbarChartData: {},
				spaceList:[{label:"1栋",id:"1"},{label:"2栋",id:"2"}],
				// rightSelectList:[{label:"",value:""},{label:"",value:""}],
				leftValue:"",
				rightValue:"",
				currentTab:"household",
				columnData:null,
				projectId:null,
				params: {},
				electricityList: [],
				chartData: {},
				monthChartData: {},
				onYearChartData: {},
				nearYearChartData: {},
				nearYearCount:0
			}
		},
		onLoad(e) {
			this.projectId = e.projectId;
			this.rightValue = this.$u.timeFormat(new Date().getTime(),'yyyy-mm');
			this.getSpaceList()
			this.getChartData()
			this.getElectricity()
		},
		components:{Arcbar,pickerGroup,columnScroll,lineScroll,rotateScroll},
		mixins:[MescrollMixin],
		methods: {
			setColor(state) {
				let color = '#289A00';
				switch(state) {
					case 'ONLINE': 
						color = '#289A00'
						break
					case 'OFFLINE':
						color = '#FF3838'
						break
					case 'OUTLINE':
						color = '#F69608'
						break
					default:
						break
				}
				return color
			},
			getStateName(state) {
				let res = stateArr.find(item => item.value === state);
				if (res) {
					return res.label
				} else {
					return ''
				}
			},
			goElectricityDetailFn(item){
				uni.navigateTo({
					url: `./electricity-detail?projectId=${this.projectId}&spaceId=${item.spaceId}`
				})
			},
			swtichTabsFn(str){
				this.currentTab = str;
				// if (str === 'household') {
				// 	this.getChartData()
				// 	this.mescroll.resetUpScroll();
				// } else {
				// 	this.getElectricity()
				// }
			},
			// 每户用电量图表数据
			getChartData() {
				let params = {
					date: this.rightValue,
					projectId: this.projectId,
					spaceId: this.leftValue,
				}
				this.$get('/app/smart/power/space', params).then(res => {
					if(res.code === 200){
						this.chartData = res.data
						this.arcbarChartData = {
							series: [
								{
									color: "#1890ff",
									data: this.chartData.percentage/100,
									index: 0,
									legendShape: "circle",
									name: "当月消耗占比今年总量",
									pointShape: "circle",
									show: true,
									type: "arcbar"
								}
							]
						}
					}
				})
			},
			// 每户用电量列表数据
			upCallback(page) {
				const _this = this;
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				this.params['pageNum'] = pageNum;
				this.params['pageSize'] = pageSize;
				this.params['projectId'] = this.projectId;
				this.params['date'] = this.rightValue;
				this.params['spaceId'] = this.leftValue;
				
				this.$get('/app/smart/power/table', this.params).then(res => {
					if(res.code === 200){
						if(res.rows && res.rows.length > 0){
							let curPageData = res.rows;
							let curPageLen = curPageData.length;
							let totalSize = res.total;
							 
							_this.$nextTick(()=>{
							 	// 隐藏下拉刷新和上拉加载的状态;
								_this.mescroll.endBySize(curPageLen, totalSize);
							})
							if(pageNum == 1) this.electricityList = []; //如果是第一页需手动置空列表
							_this.electricityList = this.electricityList.concat(curPageData); //追加新数据
							_this.mescroll.endBySize(curPageLen, totalSize); // 推荐
						} else {
							_this.electricityList = [];
							_this.mescroll.endErr();
							_this.mescroll.showEmpty();
						}
					}
				}).finally(() => {
					// _this.mescroll.endErr();
					// _this.mescroll.showEmpty();
				})
			},
			getServerData(){
				let _self = this;
				uni.request({
					url: 'https://www.ucharts.cn/data.json',
					data:{
					},
					success: function(res) {
						console.log(res.data.data)
						let obj = {
							color: "#1890ff",
							data: 0.5,
							index: 0,
							legendShape: "circle",
							name: "当月消耗占比今年总量",
							pointShape: "circle",
							show: true,
							type: "arcbar"
						}
						let Arcbar3 = {
							series:[obj]
						}
						_self.arcbarChartData = Arcbar3;
						
						let LineA={categories:[],series:[]};
						LineA.categories=res.data.data.LineA.categories;
						LineA.series=res.data.data.LineA.series;
						_self.monthChartData = LineA;
						
						let ColumnColumn={categories:[],series:[]};
						//这里我后台返回的是数组，所以用等于，如果您后台返回的是单条数据，需要push进去
						ColumnColumn.categories=res.data.data.ColumnB.categories;
						ColumnColumn.series=res.data.data.ColumnB.series;
						_self.columnData = ColumnColumn;
						
					},
					fail: () => {
						// _self.tips="网络错误，小程序端请检查合法域名";
					},
				});
			},
			onLeftConfirm(val) {
				this.leftValue = val
				this.getChartData()
				this.mescroll.resetUpScroll();
			},
			onRightConfirm(val) {
				this.rightValue = val
				this.getChartData()
				this.mescroll.resetUpScroll();
			},
			// 近两年用电量对比 /app/smart/power/electricity
			getElectricity() {
				let params = {
					projectId: this.projectId,
				}
				this.$get('/app/smart/power/electricity', params).then(res => {
					if(res.code === 200){
						let { everyMonthPower, powerYearOnYear, near2YearPower } = res.data;
						this.monthChartData = this.setChartData(everyMonthPower, 'year');
						this.onYearChartData = this.setChartData(powerYearOnYear, 'year');
						this.nearYearChartData = this.setChartData(near2YearPower, 'year');
						this.nearYearCount = near2YearPower.nowData[0] - near2YearPower.pastData[0];
					}
				})
			},
			setChartData(obj, type) {
				let categories = [],
					series = [];
				for (let item in obj) {
					if (item === 'xName') {
						categories = obj[item];
					} else {
						let seriesObj = {
							name: this.getKeyName(item, type),
							data: obj[item]
						}
						series.push(seriesObj);
					}
				}
				return {
					categories,
					series
				}
			},
			getKeyName(value, type) {
				let res = nameArr.find(item => item.value === value && item.type === type);
				if (res) {
					return res.label
				} else {
					return ''
				}
			},
			getSpaceList() {
				let params = {
					projectId: this.projectId
				}
				this.$get('/iot/space/tree-list', params).then(res => {
					if(res.code === 200){
						this.spaceList = [
							{
								id: '',
								label: '全部',
								children: [
									{
										id: '',
										label: '全部',
									}
								]
							}
						]
						this.spaceList.push(...res.data)
					}
				})
			},
		}
	}
</script>
