<template>
	<view class="content">
		<!-- 轮播图 -->
		<uni-card title="通知公告">
			<uni-swiper-dot class="uni-swiper-dot-box" :info="noticeList" :current="current" field="content">
				<swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
					<swiper-item v-for="(item, index) in noticeList" :key="index">
						<view class="swiper-item" @click="handleOpenNotice(item)">
							<image v-if="item.firstPicture" :src="item.firstPicture" mode="aspectFill"
								:draggable="false" />
							<view v-else class="no-picture">
								{{item.remark}}
							</view>
							<view class="notice-info">
								<view class="top">
									<uni-tag :text="item.remark" style="white-space: nowrap;"
										:type="['', 'success', 'primary', 'warning', 'error'][Math.floor(Math.random()*6)]" />
									<text class="notice-title">{{item.noticeTitle}}</text>
								</view>
								<view class="bottom">
									<rich-text :nodes="item.noticeContent"></rich-text>
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</uni-card>

		<!-- 姨妈提醒 -->
		<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']"
			:show="Boolean(menstruation)">
			<uni-card title="姨妈提醒" class="menstruation">
				<view class="top" v-if="menstruationAssistantSetting.state === 'zjjq'" v-html="menstruation"></view>
				<view class="top" v-if="menstruationAssistantSetting.state === 'whyl'">
					孕 <text class="theme-red margin-right-xs margin-left-xs">{{ pregnancy[0] }}</text> 周 <text
						class="theme-blue margin-right-xs margin-left-xs">{{
			                    pregnancy[1]
			                }}</text> 天
				</view>
				<view class="bottom" v-if="menstruationAssistantSetting.state === 'zjjq'">{{ menstruationLabel }}</view>
				<view class="bottom theme-grey text-sm" v-if="menstruationAssistantSetting.state === 'whyl'">
					已经{{ pregnancy[2] }}了
				</view>
			</uni-card>
		</uni-transition>

		<!-- 纪念日 -->
		<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']"
			:show="commemorationDayList.length > 0">
			<uni-card title="纪念日">
				<uni-list class="commemoration-day">
					<uni-list-item v-for="item in commemorationDayList" avatar="../static/icons/svg/404.svg"
						:key="item.id">
						<template v-slot:header>
							<view class="d-flex align-center">
								<svg-icon :icon-class="item.icon" />
							</view>
						</template>
						<template v-slot:body>
							<view class="d-flex flex-column margin-left margin-right">
								<view class="theme-blue text-bold">{{item.name}}</view>
								<view class="font-13">
									{{item.repeat ? `每年${$parseTime(item.date, '{m}月{d}日')}` : $parseTime(item.date, '{y}年{m}月{d}日')}}
								</view>
							</view>
						</template>
						<template v-slot:footer>
							<view class="d-flex align-center theme-grey font-11">
								还有
								<text
									class="font-13 theme-red">{{$getTimeDifference(nowTime, (new Date().getFullYear()) + '-' + item.date.slice(5, item.date.length)).slice(0, 1)}}</text>
								天
								<text class="font-13 theme-red">{{dateFormatHour(item)}}</text>
								小时
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-card>
		</uni-transition>

		<!-- 情侣卡券 -->
		<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']"
			:show="toDoCardList.length > 0">
			<uni-card title="情侣卡券">
				<uni-list class="card">
					<uni-list-item>
						<template v-slot:body>
							<view class="d-flex">
								<text>卡券名称</text>
								<text></text>
								<text>使用说明</text>
								<text>使用时间</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item v-for="item in toDoCardList" :key="item.id">
						<template v-slot:body>
							<view class="d-flex">
								<text :span="6">{{ item.cardName }}</text>
								<text :span="3">
									<svg-icon :icon-class="item.userName === '秦可爱' ? 'female' : 'male'"
										class="business-icon" />
								</text>
								<text :span="8">{{ item.instructions }}</text>
								<text :span="7">{{ item.createTime }}</text>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-card>
		</uni-transition>

		<!-- 今日账单 -->
		<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']"
			:show="billList.length > 0">
			<uni-card title="今日账单">
				<view class="d-flex justify-between">
					<text class="left">
						<text class="font-24 text-bold">{{ new Date().getDate() }}</text>
						<text class="font-13">日 / 周{{ $parseTime(new Date(), '{a}') }}</text>
					</text>
					<text class="right">
						<text v-if="income">
							<svg-icon icon-class="加号" />
							<text>{{ income | moneyFilter }}</text>
						</text>
						<text class="income" v-if="expenditure">
							<svg-icon icon-class="减少" />
							<text>{{ expenditure | moneyFilter }}</text>
						</text>
					</text>
				</view>
				<no-data :loading="billLoading" text="暂无记录" v-if="billList.length < 1" />
				<uni-list class="bill" v-else>
					<uni-list-item v-for="bill in billList" :key="bill.id">
						<template v-slot:header>
							<view class="d-flex align-center">
								<view style="width: 1.5rem;">
									<svg-icon size="1.2rem"
										:icon-class="Boolean(bill.typeObject) ? bill.typeObject.typeIcon : ''" />
								</view>
								<view class="d-flex flex-column margin-left margin-right">
									<view v-if="bill.typeObject && bill.typeObject.typeDifference === '2'"
										class="transfer">
										<text>{{ bill.accountObject.accountName }}</text>
										<svg-icon class="business-icon" icon-class="右箭头" />
										<text>{{ bill.otherAccountObject.accountName }}</text>
									</view>
									<view v-else>{{ bill.typeObject && bill.typeObject.typeName }}</view>
									<view class="font-13 theme-grey">
										{{ bill.remark }}
									</view>
								</view>
							</view>
						</template>
						<template v-slot:footer>
							<view class="d-flex align-center theme-blue font-13 text-bold">
								{{bill.money | moneyFilter}}
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-card>
		</uni-transition>

		<!-- 今日待办 -->
		<uni-transition ref="ani" custom-class="transition" :mode-class="['fade', 'zoom-in']"
			:show="toDoList.length > 0">
			<uni-card title="今日待办">
				<uni-list class="todo">
					<uni-list-item v-for="todo in toDoList" :key="todo.id" :title="todo.content" :note="todo.remark" />
				</uni-list>
			</uni-card>
		</uni-transition>

		<!-- 悬浮按钮 -->
		<uni-fab ref="fab" :popMenu="popMenu" :pattern="pattern" :content="content" horizontal="right"
			direction="vertical" @trigger="trigger" />

		<!-- 更新app -->

		<!-- APP下载 -->
		<uni-popup ref="updateDialog" type="dialog">
			<uni-popup-dialog type="info" confirmText="后台下载" title="正在下载" @confirm="backgroundDownload">
				<view>下载进度<text class="theme-blue" style="padding: 0 0.2rem">{{ percentageNum }}</text>%</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		listNotice
	} from '@/api/system/notice';
	import {
		getLastStartDate,
		selectMenstruationRecordList
	} from '@/api/px/life/menstruationRecord';
	import {
		getCommemorationDayList
	} from '@/api/px/life/commemorationDay';
	import {
		getToDoCard
	} from "@/api/px/life/card";

	import {
		listDo
	} from '@/api/px/life/todo';
	import {
		listRecord
	} from '@/api/px/life/bookkeeping/record';
	import {
		getAdminNewestAppInfo
	} from "@/api/px/app";

	export default {
		data() {
			return {
				// 当前所在滑块的 index
				current: 0,
				// 当前所在滑块的 index
				swiperDotIndex: 0,
				// 当前时间
				nowTime: this.$parseTime(new Date()),
				// 通知列表
				noticeList: uni.getStorageSync('homepageNoticeList') || [],
				// 姨妈提醒时间
				menstruation: '',
				// 姨妈时间
				pregnancy: [0, 0, ''],
				// 姨妈提醒内容
				menstruationLabel: '',
				// 经期设置表单
				menstruationAssistantSetting: {
					state: '',
					cycle: undefined,
					duration: undefined
				},
				// 纪念日提醒
				commemorationDayList: [],
				// 情侣卡券使用历史
				toDoCardList: [],
				// 待办列表
				toDoList: [],
				// 今日总支出
				expenditure: 0,
				// 今日总收入
				income: 0,
				// 账单加载标志
				billLoading: false,
				// 账单列表
				billList: uni.getStorageSync('homepageBillList') || [],
				// 安装包下载进度
				percentageNum: 0,
				// 悬浮按钮
				popMenu: true,
				// 悬浮按钮配置
				pattern: {
					color: '#a1a1a1',
					backgroundColor: '#FFFFFF',
					selectedColor: '#5A8DEE',
					buttonColor: '#5A8DEE',
					iconColor: '#FFFFFF'
				},
				// 悬浮按钮菜单
				content: [{
						iconPath: '/static/icons/svg/搜索.svg',
						selectedIconPath: '/static/icons/svg/搜索.svg',
						text: '搜索',
						active: false
					},
					{
						iconPath: '/static/icons/svg/时间-time.svg',
						selectedIconPath: '/static/icons/svg/时间-time.svg',
						text: '写日记',
						active: false
					},
					{
						iconPath: '/static/icons/svg/account.svg',
						selectedIconPath: '/static/icons/svg/account.svg',
						text: '记账',
						active: false
					}
				]
			}
		},
		onLoad() {
			this.getNoticeList();
			this.getMenstruationRecordList();
			this.getLastStartDate();
			this.getCommemorationDayList();
			this.getToDoCard();
			this.getBillList();
			this.getTodayToDoList();
		},
		mounted() {
			if (window.plus) {
				this.plusReady();
			} else {
				document.addEventListener('plusready', this.plusReady, false);
			}
		},
		methods: {
			/**
			 * 格式化时间
			 */
			dateFormatHour(item) {
				let date = this.$getTimeDifference(this.nowTime, (new Date().getFullYear()) + '-' + item.date.slice(5, item
					.date.length));
				return date.slice(date.indexOf('天') + 1, date.indexOf('小'))
			},
			/**
			 * 后台下载
			 */
			backgroundDownload() {
				this.$refs.updateDialog.close();
			},
			/**
			 * 查询公告列表
			 */
			getNoticeList() {
				const regex = /(<([^>]+)>)/ig;
				listNotice().then(response => {
					this.noticeList = response.rows;
					this.noticeList.map(item => {
						if (item.firstPicture) {
							item.firstPicture = item.firstPicture.slice(10, item.firstPicture.indexOf(
								' alt') - 1)
						}
						return item
					})
					this.noticeList.forEach(item => {
						item.noticeContent = item.noticeContent.replace(regex, '')
					});
					uni.setStorageSync('homepageNoticeList', this.noticeList)
				})
			},
			/**
			 * 打开通知公告详情
			 * @param {Object} item
			 */
			handleOpenNotice(item) {
				console.info(item)
			},
			/**
			 * 切换通知公告
			 * @param {Object} e
			 */
			changeSwiper(e) {
				this.current = e.detail.current
			},
			/**
			 * 获取姨妈提醒
			 */
			async getMenstruationRecordList() {
				this.$getConfigKey("ymdqzt").then(response => {
					this.menstruationAssistantSetting.state = response.msg;
				});
				await this.$getConfigKey("ymzq").then(response => {
					this.menstruationAssistantSetting.cycle = response.msg;
				});
				await this.$getConfigKey("ymsc").then(response => {
					this.menstruationAssistantSetting.duration = response.msg;
				});
				selectMenstruationRecordList().then(res => {
					let prefix = '您的小可爱'
					let labelPrefix = '请提醒您的小可爱'
					if (res.data[0].type === '0') {
						let day = this.$getTimeDifference(res.data[0].date, this.nowTime).slice(0, this
							.$getTimeDifference(res.data[0].date, this.nowTime).indexOf('天'));
						this.menstruation =
							`${prefix}大姨妈已经<span class="theme-blue" style="font-weight: bold;"> ${Number(day) + 1} </span>天`;
						this.menstruationLabel = `${labelPrefix}不要吃冰的、辣的，注意保暖、少生气！！！`
					} else if (res.data[0].type === '1') {
						let day = this.$getTimeDifference(this.nowTime, res.data[1].date).slice(0, this
							.$getTimeDifference(this.nowTime, res.data[1].date).indexOf('天'));
						if (Number(day) + Number(this.menstruationAssistantSetting.cycle) > 5 && Number(day) +
							Number(this.menstruationAssistantSetting.cycle) <= Number(this
								.menstruationAssistantSetting.cycle)) {
							return
						}
						if (Number(day) + Number(this.menstruationAssistantSetting.cycle) < 0) {
							this.menstruation =
								`${prefix}大姨妈已经推迟<span class="theme-red" style="font-weight: bold; font-size: 1.4rem;"> ${(Number(day) + Number(this.menstruationAssistantSetting.cycle)) * (-1)} </span>天`
							this.menstruationLabel = `${labelPrefix}不要着急，大不了养个娃！！！`
							return
						}
						this.menstruation =
							`${prefix}大姨妈还有<span class="theme-blue" style="font-weight: bold;"> ${Number(day) + Number(this.menstruationAssistantSetting.cycle) + 1} </span>天`
						this.menstruationLabel = `${labelPrefix}提前准备好姨妈巾！！！`
					}
				})
			},
			/**
			 * 获取最后一次开始信息
			 */
			getLastStartDate() {
				getLastStartDate().then(res => {
					let timeDifference = this.$getTimeDifference(res.data.date).slice(0, 8);
					let day = timeDifference.slice(0, timeDifference.indexOf('天'));
					this.pregnancy = [Math.floor(day / 7), day % 7, timeDifference];
				})
			},
			/**
			 * 获取纪念日提醒
			 */
			getCommemorationDayList() {
				getCommemorationDayList().then(res => {
					this.commemorationDayList = res.data;
				})
			},
			/**
			 * 获取使用历史记录列表
			 */
			getToDoCard() {
				getToDoCard().then(res => {
					this.toDoCardList = res.data;
				})
			},
			/**
			 * 获取今日待办
			 */
			getTodayToDoList() {
				listDo({
					planEndTime: this.$getNow(),
					performer: this.$store.getters.userId,
					status: false
				}).then(res => {
					this.toDoList = res.rows;
				})
			},
			/**
			 * 获取今日账单
			 */
			getBillList() {
				this.billLoading = true;
				listRecord({
					version: 1
				}).then(res => {
					this.expenditure = this.$arraySum(res.rows.filter(r => {
						return r.typeObject?.typeDifference === '1'
					}), 'money');
					this.income = this.$arraySum(res.rows.filter(r => {
						return r.typeObject?.typeDifference === '0'
					}), 'money')
					this.billList = res.rows;
					this.billLoading = false;
				})
			},
			/**
			 * 选择菜单
			 */
			trigger(e) {
				this.content[e.index].active = true;
				uni.navigateTo({
					url: '/pages_system/search/index'
				}).finally(() => {
					this.$refs.fab.close();
					this.content[e.index].active = false;
				});
			},
			/**
			 * 推送信息
			 */
			plusReady() {
				plus.push.createMessage(`欢迎${this.$store.getters.userInfo.nickName}使用Pei你看雪App`);
				plus.runtime.getProperty(plus.runtime.appid, (info) => {
					// 获取最新版本
					getAdminNewestAppInfo().then(res => {
						if (res.data.version !== info.version) {
							const task = plus.downloader.createDownload(res.data.downloadUrl, {}, (d,
								status) => {
								if (status === 200) {
									console.log("下载更新成功：" + d.filename);
									this.installWgt(d.filename);
								} else {
									console.log("下载更新失败！");
									plus.nativeUI.toast("下载更新失败！");
								}
								plus.nativeUI.closeWaiting();
							});
							task.start();

							// 下载时实时显示下载进度
							let prg = 0;
							this.showProgress = true;
							task.addEventListener('statechanged', (task, status) => {
								// 给下载任务设置一个监听 并根据状态  做操作
								switch (task.state) {
									case 1:
										//'正在下载';
										plus.push.createMessage(`正在下载···`);
										break;
									case 2:
										// '已连接到服务器';
										plus.push.createMessage(`已连接到服务器···`);
										break;
									case 3:
										prg = parseInt(
											(parseFloat(task.downloadedSize) /
												parseFloat(task.totalSize)) *
											100
										);
										this.percentageNum = prg; // 赋值给进度条组件
										break;
									case 4:
										this.showProgress = false; // 进度隐藏
										break;
								}
							});
						}
					})
				});
			},
			/**
			 * 下载
			 * @param path
			 */
			installWgt(path) {
				plus.nativeUI.showWaiting("安装更新");
				plus.runtime.install(path, {}, () => {
					plus.nativeUI.closeWaiting();
					console.log("安装更新成功！");
					plus.nativeUI.alert("更新完成！", () => {
						plus.runtime.restart(); //安装成功后重启应用
					});
				}, (e) => {
					plus.nativeUI.closeWaiting();
					console.log("安装更新失败！[" + e.code + "]：" + e.message);
					plus.nativeUI.toast("安装更新失败！");
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding-bottom: 1rem;
	}

	.swiper-box {
		// height: 400rpx;
	}

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

		uni-image {
			width: 6rem;
			height: 6rem;
			border-radius: 0.5rem;
			overflow: hidden;
			border: 1px solid hsla(0, 0%, 60%, .2196078431372549);
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.no-picture {
			width: 6rem;
			height: 6rem;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: bold;
			color: #5A8DEE;
			border-radius: 0.5rem;
			border: 1px solid hsla(0, 0%, 60%, .2196078431372549);
		}

		.notice-info {
			padding: 1rem;
			flex: 1;

			.top {
				display: flex;
				align-items: center;

				.uni-tag {
					white-space: nowrap;
				}

				.notice-title {
					color: #605e5e;
					margin-left: 1rem;
				}
			}

			.bottom {
				font-size: 0.9rem;
				color: #999;
				height: 5rem;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 3;
				padding: 0.5rem 0;
				overflow: hidden;
			}
		}
	}

	@media screen and (min-width: 500px) {
		.uni-swiper-dot-box {
			width: 400px;
			/* #ifndef APP-NVUE */
			margin: 0 auto;
			/* #endif */
			margin-top: 8px;
		}
	}

	// 姨妈提醒
	.menstruation {
		padding: 1rem;

		.top {
			font-size: 1.2rem;
		}

		.bottom {
			color: $theme-blue;
			margin-top: 0.5rem;
		}

		.top,
		.bottom {
			text-align: center;
		}
	}

	// 纪念日
	.commemoration-day {
		::v-deep .uni-list-item__container {
			justify-content: space-between;
		}
	}

	// 账单
	.bill {
		::v-deep .uni-list-item__container {
			justify-content: space-between;
		}
	}

	// 待办
	.todo {
		::v-deep .uni-list-item__content-note {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			/*截取第三行*/
			-webkit-line-clamp: 2;
			overflow: hidden;
		}
	}
</style>