<template>
	<view class="page-container">
		<view class="status-bar"></view>
		<view class="page-head">
			<view class="page-head-btn" @click="back">
				<uni-icons type="back" size="26"></uni-icons>
			</view>
			<view class="page-head-title">观看记录</view>
			<view class="page-head-btn" @click="edit">
				<view class="text-btn">{{ isEdit ? '取消' : '管理' }}</view>
			</view>
		</view>
		<view class="history-container">
			<scroll-view
				scroll-y
				refresher-enabled="true"
				refresher-background="none"
				:refresher-threshold="100"
				:refresher-triggered="refreshTriggered"
				@refresherrefresh="refresh"
				@scrolltolower="getData"
			>
				<view class="history-list">
					<checkbox-group @change="changeCheck">
						<label v-for="(vod, index) in list" :key="index" class="history-item align-center" @click="click(vod)">
							<checkbox v-if="isEdit" color="#DA2538" :value="vod.id + ''" :checked="vod.is_checked" />
							<view class="vod-image">
								<vodImage :src="vod.data && vod.data.vod_pic"></vodImage>
							</view>
							<view class="vod-info">
								<view v-if="vod.data" class="vod-name">{{ vod.data.vod_name }}</view>
								<view v-else class="vod-name vod-name-gray">该影片已被删除</view>
								<view class="vod-progress" v-if="vod.episodes">播放至 {{ vod.episodes }}</view>
								<view class="vod-time">{{ formatTime(vod.time) }}</view>
							</view>
						</label>
					</checkbox-group>
				</view>
				<u-empty v-if="pageTotal === 0" icon="/static/images/empty.svg" width="240" />
				<view v-else class="load-more">
					<u-loadmore :status="loadStatus" loading-icon="semicircle" :line="true" />
				</view>
			</scroll-view>
			<view v-if="isEdit" class="history-bottom align-center">
				<u-button :plain="true" shape="circle" text="全选" @click="selectAll"></u-button>
				<u-button type="error" :plain="true" shape="circle" text="删除" @click="delHistory"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
import { app } from '@/utils/api';
import { decryptImg } from '@/utils/crypto.dist';
import vodImage from '@/components/vod-image';
// #ifdef H5
import { vodHistory } from '@/utils/dexie';
// #endif

// #ifdef APP-PLUS
import DB from '@/utils/sqlite.js';
// #endif
export default {
	components: {
		vodImage
	},
	data() {
		return {
			list: [],
			history: [],
			checked: [],
			page: 1,
			limit: 10,
			pageTotal: 0,
			loadStatus: 'loadmore',
			refreshTriggered: false,
			isEdit: false
		};
	},
	onLoad() {
		// #ifdef APP-PLUS
		DB.openSqlite();
		// #endif

		this.init();
	},
	onUnload() {
		// #ifdef APP-PLUS
		DB.closeSqlite();
		// #endif
	},
	methods: {
		init() {
			// #ifdef APP-PLUS
			DB.selectTableData('vodHistory').then((res) => {
				res.sort((a, b) => b.time - a.time);
				const history = res.map((item) => item.vod_id);

				if (history.length > 0) {
					this.history = history;
					this.pageTotal = Math.ceil(this.history.length / this.limit);
					this.getData();
				} else {
					this.refreshTriggered = false;
					this.loadStatus = 'nomore';
				}
			});

			// #endif
			// #ifdef H5
			this.getData();
			// #endif
		},
		async getData() {
			if (this.loadStatus === 'nomore' || this.loadStatus === 'loading') {
				return;
			}
			// #ifdef H5
			vodHistory.list(this.page, this.limit).then(async (res) => {
				this.loadStatus = 'loading';
				this.pageTotal = res.pageCount;
				const history = res.list;
				await app
					.vodHistory(history.join(','), this.limit)
					.then((res) => {
						const resData = res.data;
						if (this.page < this.pageTotal) {
							this.loadStatus = 'loadmore';
							this.page++;
						} else {
							this.loadStatus = 'nomore';
						}
						history.forEach((item) => {
							if (resData && resData[item]) {
								this.list.push({
									...item,
									is_checked: false,
									data: resData[item],
									id: item
								});
							} else {
								this.list.push({
									...item,
									is_checked: false
								});
							}
						});
						console.log(this.list);
					})
					.catch((e) => {
						this.loadStatus = 'nomore';
					});
				this.refreshTriggered = false;
			});
			// #endif
			// #ifdef APP-PLUS

			this.loadStatus = 'loading';
			const history = this.history.slice((this.page - 1) * this.limit, this.page * this.limit);

			await app
				.vodHistory(history.join(','), this.limit)
				.then((res) => {
					const resData = res.data;
					if (this.page < this.pageTotal) {
						this.loadStatus = 'loadmore';
						this.page++;
					} else {
						this.loadStatus = 'nomore';
					}
					history.forEach((item) => {
						if (resData && resData[item]) {
							this.list.push({
								...item,
								is_checked: false,
								data: resData[item],
								id: item
							});
						} else {
							this.list.push({
								...item,
								is_checked: false
							});
						}
					});
				})
				.catch((e) => {
					this.loadStatus = 'nomore';
				});
			this.refreshTriggered = false;
			// #endif
		},
		delHistory() {
			if (this.checked.length > 0) {
				// #ifdef H5
				const numberArray = this.checked.map((str) => parseInt(str, 10));
				vodHistory.remove(numberArray).then((res) => {
					this.page = 1;
					this.list = [];
					this.loadStatus = 'loadmore';
					this.getData();
				});
				// #endif

				// #ifdef APP-PLUS
				this.checked.map((item) => {
					DB.deleteTableData('vodHistory', 'vod_id', item);
				});
				this.page = 1;
				this.list = [];
				this.loadStatus = 'loadmore';
				this.init();

				// let history = uni.getStorageSync('vod_history')
				// if (history.length > 0) {
				//   history = JSON.parse(history)
				//   history = history.filter(item => {
				//     return !this.checked.includes(item.id+'')
				//   })
				//   uni.setStorage({
				//     key: 'vod_history',
				//     data: JSON.stringify(history),
				//     success: () => {
				//       this.list = this.list.filter(item => {
				//         return !this.checked.includes(item.id+'')
				//       })
				//       this.checked = []
				//       if (this.loadStatus == 'nomore' && this.list.length == 0) {
				//         this.pageTotal = 0
				//       }
				//     }
				//   })
				// }
				// #endif
			}
		},
		refresh() {
			this.refreshTriggered = true;
			this.loadStatus = 'loadmore';
			this.page = 1;
			this.list = [];
			this.init();
		},
		edit() {
			this.isEdit = !this.isEdit;
		},
		selectAll() {
			this.list.map((item) => {
				if (!this.checked.includes(item.id + '')) {
					this.checked.push(item.id + '');
					item.is_checked = true;
				}
			});
		},
		changeCheck(e) {
			this.checked = e.detail.value;
			this.list.map((item) => {
				console.log(item);
				if (this.checked.includes(item.id + '')) {
					item.is_checked = true;
				} else {
					item.is_checked = false;
				}
			});
		},
		async click(data) {
			if (this.isEdit === false && data.data) {
				// #ifdef APP
				uni.navigateTo({
					url: '/pages/video/video-app?id=' + data.id
				});
				// #endif
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/video/video?id=' + data.id
				});
				// #endif
			}
		}
	}
};
</script>

<style lang="scss">
.page-container {
	height: 100%;
	background-color: $uni-bg-color;
	.header-bg {
		height: 100px;
	}
	.history-container {
		height: calc(100% - var(--safe-top) - 44px);
		display: flex;
		flex-direction: column;
		uni-scroll-view {
			height: 0;
			flex: 1 1 0%;
			.history-list {
				padding: 0 15px;
				.history-item {
					margin: 15px 0;
					uni-checkbox {
						margin-right: 8px;
					}
					.vod-image {
						width: 130px;
						height: 72px;
						margin-right: 10px;
						background-color: #171929;
						&::before {
							display: none;
						}
					}
					.vod-info {
						flex: 1 1 0%;
						.vod-name {
							color: #fff;
							font-size: 16px;
							font-weight: 700;
							overflow: hidden;
							text-overflow: ellipsis;
							word-break: break-all;
							&.vod-name-gray {
								color: #ccc;
							}
						}
						.vod-progress,
						.vod-time {
							margin-top: 6px;
							font-size: 12px;
							color: #60606c;
						}
					}
				}
			}
			.u-empty {
				padding-top: 120px;
			}
		}
		.history-bottom {
			height: 60px;
			padding: 0 10px;
			border-top: 1px solid rgba(0, 0, 0, 0.1);
			.u-button {
				flex: 1 1 0%;
				margin: 0 5px;
				&::before {
					display: none;
				}
			}
		}
	}
}
</style>
