<style lang="scss" scoped>
	@import url("@/asset/css/flex.css");

	.orcodeBox {
		background: #fff;
		border-radius: 8rpx;
		position: relative;
		z-index: 2;
	}

	.Title {}

	.orcodeImg image {
		width: 500rpx;
		height: 500rpx;
	}

	.SureBox {
		font-size: 28rpx;
		border-top: 1px solid #F2F2F2;
	}

	.SureBox view:last-child {
		color: #295EEB;
	}

	.SureBox view:first-child {
		border-right: 1px solid #ddd;
		color: #8C8C8C;
	}

	.swiper {
		height: 500rpx;
	}

	.swiper-item {
		display: block;
		height: 500rpx;
	}

	.swiper-list {
		margin-top: 40rpx;
		margin-bottom: 0;
	}

	.sty-box {
		width: 500rpx;
		height: 500rpx;
	}
</style>
<template>
	<view>
		<u-popup mode="center" border-radius="20" :popup="false" v-model="currencyVisible" :maskCloseAble="true"
			length="80%" :safeAreaInsetBottom="true" @close="close" :z-index="9999">
			<view class="orcodeBox">
				<view class="Title PY30 color000 column justify-center items-center">
					<text class="fz28">领队小程序码（{{current+1}}/{{list.length}}）</text>
					<text class="fz24">{{ list[current].TCNUMS }}</text>
				</view>
				<view class="orcodeImg row items-center justify-center PX40">
					<swiper :indicator-dots="false" circular style="height:500rpx;width:500rpx" :current="current"
						@change="changeHandler">
						<swiper-item v-for="(item, index) in list" :key="index">
							<!-- <canvas :canvas-id="`firstCanvas_${index}`" class="sty-box"
								@error="(e)=>canvasIdErrorCallback(e,index)"></canvas> -->
							<image class="sty-box" mode="aspectFit" :src="item.Url" />
						</swiper-item>
					</swiper>
				</view>
				<view class="SureBox row MT40">
					<view class="flex1 PY20 text-center" @click="close">取消</view>
					<view class="flex1 PY20 text-center" @click="preservation">保存</view>
				</view>
			</view>

		</u-popup>
	</view>
</template>
<script>
	export default {
		props: ['TCIDs'],
		data() {
			return {
				currencyVisible: false,
				list: [],
				current: 0,
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				BaseInfo: [],
				TCIDsList: []
			}
		},
		watch: {
			TCIDs: {
				handler(newVal, oldVal) {
					this.list = []
					this.getTem(newVal)
				},
				deep: false,
				immediate: true,
			}
		},
		mounted() {

		},
		methods: {
			changeHandler(i) {
				this.current = i.detail.current;
			},
			getTem(TCIDs) {
				uni.showLoading({
					title: "正在生成",
				});
				this.apipost("dmcstatistics_post_GetExtendLeaderAllStatics", {
					TCIDs: TCIDs,
					NewCombinationNum: ''
				}, (res) => {
					if (res.resultCode == 1) {
						this.BaseInfo = res.data.BaseInfo
						this.TCIDsList = this.TCIDs.split(',')
						this.TCIDsList.forEach((x, index) => {
							this.init(x)
						});
					}
				})
			},
			async init(x) {
				await this.apipostQrCode("", {
					TCID: x
				}, (res) => {
					if (res.resultCode == 1) {
						let findIndex = this.BaseInfo.findIndex(item => item.TCIDS == x)
						this.list.push({
							Url: 'data:image/png;base64,' + res.data,
							data: res.data,
							TCID: x,
							TCNUMS: this.BaseInfo[findIndex].TCNUMS
						})
						if (this.list.length == this.TCIDsList.length) {
							uni.hideLoading()
							this.currencyVisible = true
							// this.list.forEach((x, i) => {
							// 	this.drawCtx(i)
							// })
						}
					}
				})
			},
			close() {
				this.currencyVisible = false
				this.$emit('close')
			},
			drawCtx(i) {
				let ctx = uni.createCanvasContext(`firstCanvas_${i}`, this);
				let that = this;
				ctx.drawImage(that.list[i].Url, 0, 0, 250, 250); //绘制图	
				that.drawQrCode(ctx,i)
			},
			drawQrCode(ctx,i) {
				let that = this;
				setTimeout(() => {
					ctx.draw(false, () => {
						uni.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: 750,
								height: 1344,
								destWidth: 750.0,
								destHeight: 1344.0,
								canvasId: `firstCanvas_${i}`,
								success: (res) => {
									uni.hideLoading();
									// that.tempPic = res.tempFilePath;
								},
								fail(e) {
									uni.hideLoading();
									console.log(e);
								},
							},
							that
						);
					});
				}, 200)
			},
			preservation() {
				let that= this
				// 1. 清理 Base64 前缀（如 data:image/png;base64,）
				const base64Data = this.list[this.current].data
				// 2. 解码 Base64 为二进制字符串
				const arrayBuffer = wx.base64ToArrayBuffer(base64Data);
				// 3. 转换为临时文件路径（微信小程序需通过临时文件）
				const tempDir = wx.env.USER_DATA_PATH; // 临时目录（无需权限）
				const fileName = `temp_${Date.now()}.png`;
				const filePath = `${tempDir}/${fileName}`;

				// 4. 写入临时文件（使用 uni.getFileSystemManager）
				const fs = uni.getFileSystemManager();
				fs.writeFile({
					filePath: filePath,
					data: arrayBuffer, // 直接写入 ArrayBuffer
					encoding: 'binary', // 必须指定为 binary
					success: () => {
						// uni.showToast({ title: '临时文件:' + filePath });
						console.log(filePath,'----')
						// 可选：保存到相册（需授权）
						that.saveFileToPhone(filePath);
					},
					fail: (err) => {
						uni.showToast({ title: '写入失败', icon: 'none' });
						console.error('写入错误', err);
					}
				});
			},
			saveFileToPhone(tempFilePath) {
				const platform = uni.getSystemInfoSync().platform;
				// #ifdef MP-WEIXIN
					wx.saveImageToPhotosAlbum({
						filePath: tempFilePath,
						success: (saveRes) => {
							uni.showToast({ title: '保存成功'});
							console.log(saveRes,'----文件地址');
						},
						fail: (err) => {
							uni.showToast({ title: '保存失败', icon: 'none' });
							console.error('保存错误', err);
						}
					});
				// #endif
				
				// uni.saveFile({
				// 	tempFilePath: tempFilePath,
				// 		success: (saveRes) => {
				// 		uni.showToast({ title: '文件已保存至：' + saveRes.savedFilePath });
				// 		console.log(saveRes.savedFilePath,'----文件地址');
				// 	},
				// 	fail: (err) => {
				// 		uni.showToast({ title: '保存失败', icon: 'none' });
				// 		console.error('保存错误', err);
				// 	}
				// });
			},
			canvasToTempFilePath(){
				uni.canvasToTempFilePath({
						canvasId: `firstCanvas_${that.current}`,
						success: (res) => {
							uni.showLoading({
								title: "正在保存",
							});
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.showToast({
										title: "保存成功",
									});
								},
								fail: function(err) {
									if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success: (res) => {

											},
											fail: (res) => {
												uni.showModal({
													content: '检测到您没打开保存到相册权限，是否去设置打开？',
													confirmText: "确认",
													cancelText: '取消',
													success: (res) => {
														if (res.confirm) {
															uni.openSetting({
																success: (
																	res
																	) => {
																	console
																		.log(
																			res
																			);
																	if (res
																		.authSetting[
																			'scope.writePhotosAlbum'
																			]
																		) {
																		that.preservation()
																	}
																}
															})
														} else {
															console.log('取消');
														}
													}
												})
											}
										})
									} else {
										uni.showToast({
											title: '保存失败，请稍后重试',
											icon: 'none',
											duration: 2000
										})
									}
								},
								complete: function() {
									uni.hideLoading();
								},
							});
						},
						fail: function(e) {
							console.log(e);
							uni.showToast({
								title: '生成失败，请稍后重试',
								icon: 'none',
								duration: 2000
							})
						},
					},
					this
				);

			
			},
			canvasIdErrorCallback: function(e, index) {
				console.error(e.detail.errMsg, '---index', index);
			}
		}
	}
</script>