<template>
	<view class="upload-container">
		<uni-section title="定制" type="line">
			<view class="choose-img">
				<view v-for="(item, index) in imageVideoData" :key="index" :data="index" class="box-img">
					<view style="width: 100%;">
						<view v-if="item.type == 'image/jpeg' || item.type == 'image/png'" style="width: 100%;">
							<image :src="item.path" mode="widthFix" class="img-list" lazy-load />
						</view>
						<view v-else style="width: 100%;"><video :src="item.path" object-fit="fill" class="img-list" /></view>
						<view class="iconfont icon-icons03 replace" @click="replaceImg(index)" style="color: #007aff;"></view>
						<view class="iconfont icon-shanchu delele" @click="deleteImg(index)" style="color: #F56C6C;"></view>
					</view>
				</view>
			</view>
			<view @click="upload" style="margin: 40rpx 0 10rpx 0;" class="addImage"><view class="iconfont icon-jia"></view></view>
			<view style="padding-top: 20rpx;">只能上传图片或视频文件，且不超过20mb</view>
			<button type="primary" @click="save" style="margin-top: 20px;">保存</button>
		</uni-section>
	</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { saveCustomPage, updateCustomPage, templateAdd } from '@/services/api';
import { baseURL } from '@/services/request';

let imageVideoData = ref([] as any);
// 区分通用还是空白
let type = ref();
let templateId = ref();
let downUrl = '/wx/storage/fetch/';

onLoad((options: any) => {
	if (options) {
		type.value = JSON.parse(options.type);
		if (type.value == 'currency') {
			// 通用定制模板
			let currencyPage = JSON.parse(options.currencyPage);
			templateId.value = JSON.parse(options.id);
			for (let s in currencyPage) {
				imageVideoData.value.push({
					path: baseURL + downUrl + currencyPage[s].pageComponent,
					type: currencyPage[s].type,
					sort: currencyPage[s].sort
				});
			}
		} else if (type.value == 'edit') {
			// 编辑模板列表
			let pageData = JSON.parse(options.pageData);
			templateId.value = JSON.parse(options.templateId);
			for (let s in pageData) {
				imageVideoData.value.push({
					path: baseURL + downUrl + pageData[s].pageComponent,
					type: pageData[s].type,
					sort: pageData[s].sort
				});
			}
		}
	}
});
let upload = () => {
	uni.showActionSheet({
		title: '请选择上传类型',
		itemList: ['图片', '视频'],
		success(res: any) {
			if (res.tapIndex == 0) uploadImage();
			else uploadVideo();
		}
	});
};

// 上传图片
let uploadImage = () => {
	if (templateId.value) {
		uni.chooseImage({
			success(res: any) {
				uni.showLoading({
					title: '上传中...'
				});
				for (let i = 0; i < res.tempFilePaths.length; i++) {
					uni.uploadFile({
						url: baseURL + '/wx/storage/upload',
						filePath: res.tempFilePaths[i],
						name: 'file',
						success: (res: any) => {
							let data = JSON.parse(res.data).data;
							imageVideoData.value.push({
								path: baseURL + data.url,
								type: data.type,
								sort: imageVideoData.value.length
							});
							uni.hideLoading();
						},
						fail(res: any) {
							console.log(res);
						}
					});
				}
			}
		});
	} else {
		uni.chooseImage({
			success(res: any) {
				for (let i = 0; i < res.tempFilePaths.length; i++) {
					imageVideoData.value.push({
						path: res.tempFilePaths[i],
						type: res.tempFiles[i].type
					});
				}
			}
		});
	}
};

// 上传视频
let uploadVideo = () => {
	if (templateId.value) {
		uni.chooseVideo({
			sourceType: ['camera', 'album'],
			success(res: any) {
				uni.showLoading({
					title: '上传中...'
				});
				uni.uploadFile({
					url: baseURL + '/wx/storage/upload',
					filePath: res.tempFilePath,
					name: 'file',
					success: (res: any) => {
						let data = JSON.parse(res.data).data;
						imageVideoData.value.push({
							path: baseURL + data.url,
							type: data.type,
							sort: imageVideoData.value.length
						});
						uni.hideLoading();
					},
					fail(res: any) {
						console.log(res);
					}
				});
			}
		});
	} else {
		uni.chooseVideo({
			sourceType: ['camera', 'album'],
			success(res: any) {
				imageVideoData.value.push({
					path: res.tempFilePath,
					type: res.tempFile.type
				});
			}
		});
	}
};

let save = () => {
	if (templateId.value) {
		let idArr: any = [];
		console.log(imageVideoData.value);
		for (let key in imageVideoData.value) {
			let str = imageVideoData.value[key].path.split('/');
			idArr.push({
				pageComponent: str[str.length - 1],
				sort: imageVideoData.value[key].sort
			});
		}
		if (type.value == 'currency') {
			console.log(idArr, '添加');
			setTimeout(() => {
				templateAdd({ pageComponentList: idArr }).then((res: any) => {
					if (res.data.errno == 0) {
						imageVideoData.value = [];
						close();
					}
				});
			}, 50);
		} else {
			console.log('編輯', idArr);
			setTimeout(() => {
				updateCustomPage({ id: templateId.value, pageComponentList: idArr }).then((res: any) => {
					if (res.data.errno == 0) {
						imageVideoData.value = [];
						close();
					}
				});
			}, 50);
		}
	} else {
		// 空白
		let idArr: any = [];
		for (let key in imageVideoData.value) {
			uni.uploadFile({
				url: baseURL + '/wx/customPage/upload',
				filePath: imageVideoData.value[key].path,
				name: 'file',
				success(res: any) {
					if (res.data.errno != 502) {
						uni.showLoading({
							title: '上传中'
						});
						idArr.push(res.data);
						if (Number(key) == imageVideoData.value.length - 1) {
							saveCustomPage({ fileIds: idArr }).then((res: any) => {
								if (res.statusCode == 200) {
									uni.hideLoading();
									imageVideoData.value = [];
									close();
								}
							});
						}
					}
				},
				fail(res: any) {
					console.log(res);
				}
			});
		}
	}
};

// 替换图片
let replaceImg = (index: number) => {
	if (imageVideoData.value[index]['type'] == 'image/jpeg') {
		uni.showModal({
			cancelText: '取消',
			confirmText: '确认',
			content: '确认替换图片？',
			success: (res: any) => {
				if (res.confirm) {
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['camera', 'album'], //从相册选择
						success: function(res: any) {
							uni.uploadFile({
								url: baseURL + '/wx/storage/upload',
								filePath: res.tempFilePaths[0],
								name: 'file',
								success: (res: any) => {
									let data = JSON.parse(res.data).data;
									imageVideoData.value[index]['path'] = baseURL + data.url;
								},
								fail(res: any) {
									console.log(res);
								}
							});
						}
					});
				}
			}
		});
	} else {
		uni.showModal({
			cancelText: '取消',
			confirmText: '确认',
			content: '确认替换视频？',
			success: (res: any) => {
				if (res.confirm) {
					uni.chooseVideo({
						sourceType: ['camera', 'album'], //从相册选择
						success: function(res: any) {
							uni.uploadFile({
								url: baseURL + '/wx/storage/upload',
								filePath: res.tempFilePath,
								name: 'file',
								success: (res: any) => {
									let data = JSON.parse(res.data).data;
									imageVideoData.value[index]['path'] = baseURL + data.url;
									console.log(imageVideoData.value);
								},
								fail(res: any) {
									console.log(res);
								}
							});
						}
					});
				}
			}
		});
	}
};

// 删除图片
let deleteImg = (index: number) => {
	if (templateId.value) {
		uni.showModal({
			cancelText: '取消',
			confirmText: '确认',
			content: '确认删除图片？',
			success: (res: any) => {
				if (res.confirm) {
					imageVideoData.value.splice(index, 1);
					for (let s in imageVideoData.value) {
						if (Number(s) >= index) imageVideoData.value[s].sort = imageVideoData.value[s].sort - 1;
					}
				}
			}
		});
	} else {
		uni.showModal({
			cancelText: '取消',
			confirmText: '确认',
			content: '确认删除图片？',
			success: (res: any) => {
				if (res.confirm) imageVideoData.value.splice(index, 1);
			}
		});
	}
};

// 返回刷新
let close = () => {
	//调用上一个页面中的方法
	uni.navigateBack({
		delta: 1,
		success: () => {
			uni.$emit('updateData')
			// let pages: any = getCurrentPages();
			// // let currPage = pages[pages.length - 1]; //当前页面
			// let prePage = pages[pages.length - 2]; //上一个页面
			// prePage.$vm.initHavePage();
		}
	});
};
</script>

<style lang="scss" scoped>
.upload-container {
	box-sizing: border-box;
	padding: 20rpx 60rpx 20rpx 20rpx;
	width: 100%;
	height: 100vh;
	background-color: #fff;

	.choose-img {
		display: flex;
		flex-direction: column;

		.box-img {
			display: flex;
			position: relative;
			width: 100%;
			// height: 160rpx;
			margin-right: 10rpx;

			.img-list {
				width: 100%;
				// background-color: pink;
			}

			.replace {
				position: absolute;
				top: 64rpx;
				right: -48rpx;
				color: rgba(0, 0, 0, 0.5);
				font-size: 44rpx;
			}

			.delele {
				position: absolute;
				top: 10rpx;
				right: -48rpx;
				color: rgba(0, 0, 0, 0.5);
				font-size: 44rpx;
			}

			.mark {
				position: absolute;
				top: 0;
				width: 100%;
				height: 100%;
				color: #fff;
				background: rgba(0, 0, 0, 0.3);
				left: 0%;
				right: 0%;
				// margin-top: -500px;
				font-size: 26rpx;
				text-align: center;
				box-shadow: 2px -3px 100px -5px #ffffff;
			}
		}
	}

	.addImage {
		width: 100px;
		height: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #e2e2e2;
		.icon-jia {
			color: #fff;
			font-size: 90rpx;
		}
	}
}
</style>
