<template>
	<view class="container">
		<view class="line"></view>
		<view class="picker-box">
			<picker @change="bindYearPickerChange" :value="selYearIndex" :range="years" class="picker-input">
				<view class="txt-picker">
					<view>{{years[selYearIndex]}}</view>
					<uni-icons type="bottom" size="22"></uni-icons>
				</view>
			</picker>
			<picker @change="bindMonthPickerChange" :value="selMonthindex" :range="months" class="picker-input">
				<view class="txt-picker">
					<view>{{months[selMonthindex]}}</view>
					<uni-icons type="bottom" size="22"></uni-icons>
				</view>
			</picker>
		</view>
		<view class="line"></view>
		<view class="show-charts">
			<view class="show-label">
				<image class="show-logo-left" src="../static/images/dt.png"></image>
				<view class="show-txt-label">消费走势图</view>
			</view>
			<view class="charts-box">
				<qiun-data-charts canvasId="canvasAirId" type="line" :chartData="chartData" :opts="chartOpts"
					:ontouch="true" :canvas2d="false" id="chartsAir" />
			</view>
		</view>
		<view class="line"></view>
		<view class="xfjl">
			<view class="xfjl-title">
				<image class="show-logo-left" src="../static/images/xfjl.png"></image>
				<view class="show-txt-label">消费记录</view>
			</view>
			<scroll-view scroll-y="true" :style="{height: screenHeight}" @scrolltoupper="scroll_to_upper"
				@scrolltolower="scroll_to_lower">
				<view class="items" v-for="(item, index) in consumeRecords" :key="index">
					<view class="item">
						<view class="item-left">
							<image src="../static/images/item-icon.png" mode=""></image>
							<view class="item-desc">
								<view class="item-title">{{item.loudong}}</view>
								<view class="item-time">开始时间：{{item.startTime}}</view>
								<view class="item-time">结束时间：{{item.endTime}}</view>
							</view>
						</view>
						<view class="item-right">{{item.amount.toFixed(2)}}</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ceshi: 'air',
				id_card: '', // 身份证号
				screenHeight: 0,
				years: this.$getDate('get_year'), // 候选年份
				months: ['全部', '01月', '02月', '03月', '04月', '05月', '06月', '07月', '08月', '09月', '10月', '11月', '12月'], // 候选月份
				selYearIndex: 0, // 选择的年份index
				selMonthindex: this.$getDate('get_month'), // 选择的月份index
				selYearMonth: '', // 选择的年份、月份
				chartData: {
					categories: [],
					series: []
				},
				chartDataInit: { // 如果 chartData 没有数据，解决一直打转的问题
					"categories": ["无数据"],
					"series": [{
						"name": "金额",
						"data": ["0.00"]
					}]
				},
				chartOpts: {
					color: ["#1890FF", "#91CB74", "#FAC858"],
					padding: [15, 10, 0, 15],
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {
						data: [{
							max: 0
						}]
					},
					extra: {
						line: {
							type: "curve",
							width: 2
						}
					}
				},
				consumeRecords: []
			}
		},
		onLoad() {
			// 获取基本信息
			this.get_base_info()
			// 获取年月格式
			this.get_year_month()
		},
		onShow() {
			// 从新计算高度
			setTimeout(() => {
				this.calc_screen_height()
			}, 1000)
		},
		mounted() {
			// 走势图数据
			this.getRechargeRecord()
		},
		methods: {
			/**
			 * 获取身份证号
			 */
			get_base_info() {
				try {
					if (this.id_card == '' || typeof(this.id_card) == 'undefined') {
						const userinfo = uni.getStorageSync('userinfo_storage_key')
						if (userinfo) {
							this.id_card = userinfo.id_card
						} else {
							uni.navigateTo({
								url: '../index/index?from=' + options.from
							})

							uni.showToast({
								icon: 'none',
								title: '身份证号为空，请进行授权',
								duration: 3000
							});

							return
						}
					}
				} catch (e) {
					console.log('获取基本信息：' + e.message);
				}
			},
			/**
			 * 查询当月消费
			 */
			async getRecord(param) {
				if (this.id_card == '') {
					uni.showToast({
						icon: 'none',
						title: '身份证号为空，请进行授权',
						duration: 3000
					});
					return
				}

				let pYear = this.years[this.selYearIndex].substring(0, 4);
				let pData = '';
				if (param === '全部') {
					pData = {
						page: 1,
						rows: 90,
						sfzh: this.id_card,
						con_year: pYear
					};
				} else {
					pData = {
						page: 1,
						rows: 90,
						sfzh: this.id_card,
						con_year: pYear,
						con_month: this.selYearMonth
					};
				}

				let res = await this.$myRequest({
					host: this.ceshi,
					url: '/airManage/consumequeryOwnPage.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: pData
				})

				// console.log(res.data);
				let data = res.data
				if (typeof data.rows !== 'undefined' && data.rows === '') {
					uni.showToast({
						title: '暂无消费数据',
						duration: 1500
					})
					// 清空列表
					this.consumeRecords = []
					return
				}
				if (data.code === 200) {
					if (typeof data.rows === 'undefined' || data.rows === '') {
						uni.showToast({
							title: '暂无消费数据',
							duration: 1500
						})
						// 清空列表
						this.consumeRecords = []
						return
					}
					let tmpRecord = []
					for (var i = 0; i < data.rows.length; i++) {
						tmpRecord.push({
							loudong: data.rows[i].build + '-' + data.rows[i].floors + '-' + data.rows[i].dom
								.split('-')[1],
							startTime: data.rows[i].time,
							endTime: data.rows[i].end_time,
							amount: data.rows[i].account
						})
					}
					this.consumeRecords = tmpRecord
				} else if (typeof data.code === 'undefined') {
					uni.showToast({
						title: data.message,
						duration: 1500
					})
				} else {
					uni.showToast({
						title: '暂无数据',
						duration: 1500
					})
				}
			},
			/**
			 * 获取消费走势图数据
			 */
			async getRechargeRecord() {
				let pYear = this.years[this.selYearIndex].substring(0, 4);
				let pMonth = '';
				if (this.selMonthindex == 0) {
					pMonth = this.months[this.selMonthindex].substring(0, 2);
				} else {
					pMonth = pYear + '-' + this.months[this.selMonthindex].substring(0, 2);
				}
				let res = await this.$myRequest({
					host: this.ceshi,
					url: '/airManage/consumequeryOwnConTong.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						// sfzh: '421182199112100031'
						sfzh: this.id_card,
						con_year: pYear,
						con_month: pMonth
					}
				})

				// console.log(res.data);
				let _this = this
				if (typeof res.data === 'undefined') {
					uni.showToast({
						title: '暂无走势图数据',
						duration: 1500
					});

					setTimeout(() => {
						_this.chartData = _this.chartDataInit
					}, 1000);

					return
				}
				let tmpdata = res.data
				if (tmpdata.code === 200) {
					if (typeof tmpdata.data === 'undefined' || tmpdata.data.length === 0) {
						uni.showToast({
							title: '暂无走势图数据',
							duration: 1500
						});

						setTimeout(() => {
							_this.chartData = _this.chartDataInit
						}, 1000);

						return;
					}

					let chrt_data = {
						categories: [],
						series: []
					};
					let elc_max = -1.0;
					let dt = '';
					let temp = 0;
					let data = [];
					if (this.selMonthindex == 0) {
						let echartData = tmpdata.data.sort((a, b) => a.month.localeCompare(b.month));
						for (var i = 0; i < echartData.length; i++) {
							dt = echartData[i].month;
							chrt_data.categories.push(parseInt(dt.substr(dt.lastIndexOf('-') + 1, dt.length)) + '月');
							temp = echartData[i].num;
							temp = temp.toFixed(2);
							data.push(temp);
							if (parseFloat(temp) > parseFloat(elc_max)) {
								elc_max = temp;
							}
						}
					} else {
						let echartData = tmpdata.data.sort((a, b) => a.day.localeCompare(b.day));
						for (var i = 0; i < echartData.length; i++) {
							dt = echartData[i].day;
							chrt_data.categories.push(parseInt(dt.substr(dt.lastIndexOf('-') + 1, dt.length)) + '日');
							temp = echartData[i].num;
							temp = temp.toFixed(2);
							data.push(temp);
							if (parseFloat(temp) > parseFloat(elc_max)) {
								elc_max = temp;
							}
						}
					}

					let items = {
						name: '金额',
						data: data
					};
					chrt_data.series.push(items);
					let m = parseFloat(Math.abs(elc_max));
					// console.log(chrt_data);
					if (elc_max == 0.0) {
						setTimeout(() => {
							this.chartOpts.yAxis.data[0].max = parseInt(10);
							this.chartData = chrt_data;
						}, 1000);
					} else {
						setTimeout(() => {
							this.chartOpts.yAxis.data[0].max = parseInt(m + 5);
							this.chartData = chrt_data;
						}, 1000);
					}
				} else if (tmpdata.code === 205) {
					setTimeout(() => {
						_this.chartData = _this.chartDataInit
					}, 1000);

					uni.showToast({
						title: tmpdata.message,
						duration: 1500
					})
				} else {
					uni.showToast({
						title: '数据异常',
						duration: 1500
					})
				}
			},
			/**
			 * 转换年月格式
			 */
			get_year_month() {
				// 走势图数据
				this.getRechargeRecord();

				this.selYearMonth = this.years[this.selYearIndex].substring(0, 4) + '-' +
					this.months[this.selMonthindex].substring(0, 2);

				if (this.selMonthindex == 0) {
					// 全部，显示1-12月的数据
					this.getRecord('全部');
				} else {
					// 查询当月消费
					this.getRecord('按月');
				}
			},
			/**
			 * 选择年份
			 * @param {Object} e
			 */
			bindYearPickerChange(e) {
				// console.log(e);
				this.selYearIndex = e.target.value
				this.get_year_month()
			},
			/**
			 * 选择月份
			 * @param {Object} e
			 */
			bindMonthPickerChange(e) {
				// console.log(e);
				this.selMonthindex = e.target.value
				this.get_year_month()
			},
			/**
			 * 滚动到顶部提示
			 */
			scroll_to_upper() {
				uni.showToast({
					title: '到顶了！',
					icon: 'none',
					duration: 500
				})
			},
			/**
			 * 滚动到底部提示
			 */
			scroll_to_lower() {
				uni.showToast({
					title: '到底了！',
					icon: 'none',
					duration: 500
				})
			},
			/**
			 * 计算屏幕的高度
			 */
			calc_screen_height() {
				uni.getSystemInfo({
					success: res => {
						let h = ((res.screenHeight * (750 / res.windowWidth)) - 820) //将px 转换rpx
						this.screenHeight = Math.floor(h) + 'rpx'
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		font-family: "Microsoft YaHei-3970(82674968)";
		width: 730rpx;
		padding: 10rpx;

		.line {
			height: 20rpx;
		}

		.picker-box {
			display: flex;
			justify-content: space-between;
			width: 375rpx;

			.picker-input {
				display: flex;
				justify-content: space-around;
				align-items: center;
				border: 2rpx solid #CCCCCC;
				border-radius: 6rpx;

				.txt-picker {
					display: flex;
					justify-content: space-around;
					align-items: center;
					width: 175rpx;
					height: 60rpx;
				}
			}
		}

		.show-charts {
			display: flex;
			flex-direction: column;

			.show-label {
				display: flex;
				align-items: center;

				image {
					width: 30rpx;
					height: 30rpx;
					margin: 0 10rpx 0;
				}

				.show-txt-label {
					font-size: 32upx;
				}
			}
		}

		.xfjl {
			display: flex;
			flex-direction: column;

			.xfjl-title {
				display: flex;
				align-items: center;

				image {
					width: 30rpx;
					height: 30rpx;
					margin: 0 10rpx 0;
				}

				.show-txt-label {
					font-size: 32upx;
				}
			}

			.items {
				display: flex;
				flex-direction: column;

				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 120rpx;
					margin: 10rpx;
					padding: 15rpx 0;
					border-bottom: 1px solid #CCCCCC;

					.item-left {
						display: flex;
						align-items: center;

						image {
							width: 90rpx;
							height: 90rpx;
							margin: 0 20rpx 0 0;
						}

						.item-desc {
							display: flex;
							flex-direction: column;
							justify-content: space-between;

							.item-title {
								font-size: 32upx;
								font-weight: bold;
							}

							.item-time {
								font-size: 24upx;
								color: #c8cdd8;
							}
						}
					}

					.item-right {
						font-size: 36upx;
						font-weight: bold;
						color: #4456fb;
					}
				}
			}
		}
	}
</style>
