<template>
	<view class="device-detail">
		<app-top-push-notice />
		<view class="bj"></view>
		<!-- 头部保持原样 -->
		<view class="tabback">
			<view class="" @click="onCancel">
				{{ $i18n.t('cancel') }}
			</view>
			<view class="name">{{$i18n.t('bjkj')}}</view>
			<view class="add-btn" :class="{ active: canAdd }" @click="onAdd">
				{{$i18n.t('editSpace')}}
			</view>
		</view>

		<view class="content-container" style="background-color: #F3F5F6;">
			<!-- 说明 -->
			<view class="instruction-section">
				<view class="" @click="btnimgava">
					<image class="da" :src="userImgs" mode="aspectFill"></image>
					<image class="xiao" src="https://api.ccttiot.com/smartmeter/img/static/uGLlOMNCblf2uDmECVKK"
						mode="aspectFill"></image>
				</view>
			</view>

			<!-- 输入区域 -->
			<view class="input-section">
				<view class="input-group">
					<text class="input-label">{{ $i18n.t('spaceNameLabel') }}</text>
					<input class="code-input" type="text" v-model="spaceName"
						:placeholder="$i18n.t('spaceNamePlaceholder')" />
				</view>
			</view>

			<!-- 提示 -->
			<view class="help-section">
				<text class="help-text">{{ $i18n.t('spaceNameHelp') }}</text>
			</view>

			<!-- 自定义底部选择弹窗 -->
			<view class="action-sheet" v-if="showActionSheet" @click="hideActionSheet">
				<view class="action-sheet-content" @click.stop>
					<view class="action-sheet-item" @click="takePhoto">
						<text class="action-sheet-text">{{ $i18n.t('takePhoto') }}</text>
					</view>
					<view class="action-sheet-item" @click="chooseFromAlbum">
						<text class="action-sheet-text">{{ $i18n.t('chooseFromAlbum') }}</text>
					</view>
					<view class="action-sheet-cancel" @click="hideActionSheet">
						<text class="action-sheet-text">{{ $i18n.t('actionSheetCancel') }}</text>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				spaceName: '',
				showActionSheet: false,
				userImgs: 'https://api.ccttiot.com/smartmeter/img/static/uKFO4XdQVUgGYJHt4gwn',
				cropImageSrc: '',
				kjid:'',
				fangdouflag:true
			}
		},
		computed: {
			canAdd() {
				return this.spaceName && this.spaceName.trim().length > 0
			}
		},
		onLoad() {
			this.kjid = uni.getStorageSync('kjid')
			this.getQiniuToken()
			this.getxq()
		},
		methods: {
			// 请求空间详情
			getxq(){
				this.$http.get(`/bst/space/${this.kjid}`).then(res => {
					if(res.code == 200){
						this.userImgs = res.data.picture
						this.spaceName = res.data.name
					}
				})
			},
			// 点击上传图片
			btnimgava() {
				this.showActionSheet = true
			},
			// 隐藏弹窗
			hideActionSheet() {
				this.showActionSheet = false
			},
			// 拍照
			takePhoto() {
				this.hideActionSheet()
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: (imgRes) => {
						this.cropImageSrc = imgRes.tempFilePaths[0]
						let _this = this
						let math = 'static/' + _this.generateGuid(20)
						// 上传裁剪后的图片到七牛云
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							name: 'file',
							filePath: _this.cropImageSrc,
							formData: {
								token: this.token, // 后端返回的token
								key: 'smartmeter/img/' + math
							},
							success: function(res) {
								uni.hideLoading()
								let str = JSON.parse(res.data)
								_this.userImgs = 'https://api.ccttiot.com/' + str.key
								console.log('最终图片路径:', _this.userImgs)
								uni.showToast({
									title: _this.$i18n.t('imageSelectedSuccess'),
									icon: 'success',
									duration: 3000
								})
							},
							fail: function(err) {
								uni.hideLoading()
								console.error('上传失败:', err)
								uni.showToast({
									title: _this.$i18n.t('uploadFailed'),
									icon: 'none',
								})
							}
						})
					},
					fail: (err) => {
						console.error('拍照失败:', err)
						uni.showToast({
							title: this.$i18n.t('imageOperationCancelled'),
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			// 从相册选择
			chooseFromAlbum() {
				this.hideActionSheet()
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (imgRes) => {
						this.cropImageSrc = imgRes.tempFilePaths[0]
						let _this = this
						let math = 'static/' + _this.generateGuid(20)
						// 上传裁剪后的图片到七牛云
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							name: 'file',
							filePath: _this.cropImageSrc,
							formData: {
								token: this.token, // 后端返回的token
								key: 'smartmeter/img/' + math
							},
							success: function(res) {
								uni.hideLoading()
								let str = JSON.parse(res.data)
								_this.userImgs = 'https://api.ccttiot.com/' + str.key
								console.log('最终图片路径:', _this.userImgs)
								uni.showToast({
									title: _this.$i18n.t('imageSelectedSuccess'),
									icon: 'success'
								})
							},
							fail: function(err) {
								uni.hideLoading()
								console.error('上传失败:', err)
								uni.showToast({
									title: _this.$i18n.t('uploadFailed'),
									icon: 'none'
								})
							}
						})
					},
					fail: (err) => {
						console.error('选择图片失败:', err)
						uni.showToast({
							title: this.$i18n.t('imageOperationCancelled'),
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			// 生成随机字符串（替代$u.guid方法）
			generateGuid(length) {
				const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
				let result = ''
				for (let i = 0; i < length; i++) {
					result += chars.charAt(Math.floor(Math.random() * chars.length))
				}
				return result
			},
			// 获取上传七牛云token
			getQiniuToken() {
				this.$http.get("/common/qiniuToken").then((res) => {
					if (res.code == 200) {
						this.token = res.data
					}
				})
			},


			// 点击跳转到验证
			btnyz() {
				uni.navigateTo({
					url: '/pages/login/twodl'
				})
			},
			onAdd() {
				if (!this.canAdd) {
					uni.showToast({
						title: this.$i18n.t('pleaseEnterSpaceName'),
						icon: 'none',
						duration: 3000
					})
					return
				}
				// let userId = uni.getStorageSync('user').userId
				let data = {
					id:this.kjid,
					name: this.spaceName,
					picture: this.userImgs,
					// userId: userId
				}
				if(this.fangdouflag == true){
					this.fangdouflag = false
					this.$http.put("/bst/space", data).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								duration: 3000
							})
							setTimeout(() => {
								this.fangdouflag = true
								uni.navigateBack()
							}, 1500)
						}else{
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 3000
							})
							this.fangdouflag = true
						}
					})
				}
			},
			// 点击返回上一级
			onCancel() {
				uni.navigateBack({
					delta: 1
				})
			}
		}
	}
</script>

<style scoped lang="less">
	/* 自定义底部弹窗样式 */
	.action-sheet {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 9999;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}

	.action-sheet-content {
		width: 100%;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding-bottom: 40rpx;
		animation: slideUp 0.3s ease-out;
	}

	@keyframes slideUp {
		from {
			transform: translateY(100%);
		}

		to {
			transform: translateY(0);
		}
	}

	.action-sheet-item {
		padding: 30rpx 40rpx;
		border-bottom: 1rpx solid #f0f0f0;
		text-align: center;
	}

	.action-sheet-item:active {
		background-color: #f5f5f5;
	}

	.action-sheet-cancel {
		padding: 30rpx 40rpx;
		text-align: center;
		margin-top: 20rpx;
		background-color: #f8f8f8;
	}

	.action-sheet-cancel:active {
		background-color: #e8e8e8;
	}

	.action-sheet-text {
		font-size: 32rpx;
		color: #333;
	}

	.action-sheet-cancel .action-sheet-text {
		color: #666;
	}

	/* 图片裁剪弹窗样式 */
	.image-crop-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #000;
		z-index: 10000;
		display: flex;
		flex-direction: column;
	}

	.crop-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #000;
	}

	.bj {
		width: 100%;
		height: 50vh;
		position: fixed;
		top: 0;
		z-index: -1;
		background-color: #0F0F0F;
	}

	.tabback {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		height: 126rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		margin-top: 102rpx;
		border-radius: 30rpx 30rpx 0 0;

		.rtjt {
			font-size: 36rpx;
			color: #333;
		}

		.name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin: 0 auto;
		}

		.add-btn {
			font-size: 32rpx;
			color: #ccc;
			transition: color 0.3s;

			&.active {
				color: #333;
			}
		}
	}

	.device-detail {
		min-height: 100vh;
	}

	.content-container {
		display: flex;
		flex-direction: column;
		min-height: calc(100vh - 228rpx);
	}

	.instruction-section {
		background: #f3f5f6;
		text-align: center;
		width: 100%;
		height: 448rpx;

		view {
			position: relative;
			left: 50%;
			transform: translateX(-50%);
			width: 272rpx;
			margin-top: 88rpx;
		}

		.da {
			width: 272rpx;
			height: 272rpx;
			border-radius: 50%;
		}

		.xiao {
			width: 116rpx;
			height: 72rpx;
			position: absolute;
			right: 0;
			bottom: 0;
		}

		.instruction-text {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			margin-top: 30rpx;
		}
	}

	.input-section {
		background: #fff;
		padding: 40rpx 32rpx;
		margin-top: 40rpx;

		.input-group {
			margin-bottom: 40rpx;
		}

		.input-label {
			display: block;
			font-size: 28rpx;
			color: #666;
			margin-bottom: 20rpx;
		}

		.code-input {
			width: 100%;
			height: 80rpx;
			border: none;
			border-bottom: 2rpx solid #e5e5e5;
			font-size: 32rpx;
			color: #333;
			background: transparent;
			padding: 0;

			&::placeholder {
				color: #bbb;
				letter-spacing: 8rpx;
			}

			&:focus {
				border-bottom-color: #000;
				outline: none;
			}
		}
	}

	.help-section {
		background: #f3f5f6;
		padding: 40rpx 0;
		padding-top: 20rpx;
		padding-left: 48rpx;
	}

	.help-text {
		font-size: 28rpx;
		color: #727272;
	}

	.button-section {
		margin-top: auto;
		padding-top: 42rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 750rpx;
		height: 220rpx;
		background: #FFFFFF;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 0;

		.continue-btn {
			width: 674rpx;
			height: 80rpx;
			line-height: 80rpx;
			background: #BBBBBB;
			color: #fff;
			border: none;
			border-radius: 50rpx;
			font-size: 32rpx;
			font-weight: 600;
		}

		.continue-btn.active {
			background: #000;
		}

		.cancel-btn {
			margin-top: 34rpx;
			font-size: 28rpx;
			color: #000;
		}
	}
</style>