<template>
	<view class="page">
		<u-navbar title="故障上报" :border-bottom="false" :background="bgc" title-color='#000' title-size='36'
			height='40'></u-navbar>
		<view class="cardbox">
			<view class="tip">
				<view class="ipnt">*</view>故障车编号
			</view>
			<view class="iptbox">
				<input type="text" class="ips" v-model="sn" placeholder="请输入车辆二维码下方编号"
					placeholder-style='font-weight: 400;font-size: 36rpx;color: #808080;' />
				<view class="iptbtn" @click="scanQRCode()">
					<image src="https://api.ccttiot.com/smartmeter/img/static/un6Wi8CefEjy04qzvn67" mode=""></image>
				</view>
			</view>
		</view>
		<view class="cardbox">
			<view class="tip">
				<view class="ipnt">*</view>请选择车辆故障部位
			</view>
			<view class="txt">
				车头故障
			</view>
			<view class="checkbox">
				<view v-for="(item, index) in cbgz" :key="index" class="check_li" :class="item.checked === true ? 'act1' : ''" @click="toggleCheckbox(index)">
				  {{ item.dictLabel }}
				  <image src="https://api.ccttiot.com/smartmeter/img/static/uuMYyKHxezgXIREa0bpT" mode="" v-if="item.checked === true "></image>
				</view>
			</view>
			<view class="txt">
				车身故障
			</view>
			<view class="checkbox">
				<view v-for="(item, index) in csgz" :key="index" class="check_li" :class="item.checked === true ? 'act1' : ''" @click="csCheckbox(index)">
				  {{ item.dictLabel }}
				  <image src="https://api.ccttiot.com/smartmeter/img/static/uuMYyKHxezgXIREa0bpT" mode="" v-if="item.checked === true "></image>
				</view>
			
			</view>
			<view class="txt">
				特殊故障
			</view>
			<view class="checkbox">
				<view v-for="(item, index) in tsgz" :key="index" class="check_li" :class="item.checked === true ? 'act1' : ''" @click="tsCheckbox(index)">
				  {{ item.dictLabel }}
				  <image src="https://api.ccttiot.com/smartmeter/img/static/uuMYyKHxezgXIREa0bpT" mode="" v-if="item.checked === true "></image>
				</view>
			</view>
			<view class="input-container">
				<view class="placeholder" v-if="!textValue">如选项未涵盖，请输入故障问题</view>
				<textarea class="custom-textarea" v-model="textValue" @focus="hidePlaceholder" style="border: none;"
					@input="updateWordCount" @blur="showPlaceholder"></textarea>
				<text class="word-count">{{ currentCount }}/500</text>
			</view>
		</view>
		<view class="cardbox">
			<view class="tip">
			请对故障部位拍照
			</view>
			<view class="icon">
			
				<view class="imgbox" v-for="(item,index) in imglist " :key="index">
					<image :src="item" mode=""></image>
				</view>
				<view class="imgbox" @click="btn">
					<image src="https://api.ccttiot.com/smartmeter/img/static/uY8CPw9YE6JxPzcHUaqf" mode=""></image>
				</view>
			
			</view>
		</view>
		<view class="btn" @click="sub()">
			提交
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#fff",
				},
				cbgz: [
				],
				csgz: [
				],
				tsgz: [{
						name: '有电不走',
						checked: false
					},
					{
						name: '车速失控',
						checked: false
					},
					{
						name: '车身异响',
						checked: false
					},
					{
						name: '其他',
						checked: false
					},
					
				],
				textValue: '',
				currentCount: 0,
				imglist: [],
				token: '',
				sn:'',
				upurl:''
			}
		},
		onShow() {
			this.$store.dispatch('userInfo', this.$u).then(() => {
			this.getQiniuToken()
				// 执行其他操作...
			});
		},
		onLoad(e) {
			console.log(e,'eeeeeeeeeeeeeeee');
			if(e.sn){
				this.sn=e.sn
			}
			this.getlist()
		},
		computed: {
			appointmentServiceFee() {
				return this.$store.getters.appointmentServiceFee;
			},
			dispatchFee() {
				return this.$store.getters.dispatchFee;
			},
			vehicleManagementFee() {
				return this.$store.getters.vehicleManagementFee;
			},
			startingPrice() {
				return this.$store.getters.startingPrice;
			},
			timeFee() {
				return this.$store.getters.timeFee;
			},
			timeMinutes() {
				return this.$store.getters.timeMinutes;
			},
			deposit() {
				return this.$store.getters.deposit;
			},
			userId() {
				return this.$store.getters.userId;
			},
		},
		methods: {
			sub(){
				 let data = {
						userId:this.userId,
						detail:this.textValue,
						sn:this.sn,
						
				        types: [] // Initialize the type array
				    };
					data.picture = this.imglist.join(','),
				    // Check for checked items in cbgz
				    this.cbgz.forEach(item => {
				        if (item.checked) {
				            data.types.push(item.dictValue);
				        }
				    });
				
				    // Check for checked items in csgz
				    this.csgz.forEach(item => {
				        if (item.checked) {
				            data.types.push(item.dictValue);
				        }
				    });
				
				    // Check for checked items in tsgz
				    this.tsgz.forEach(item => {
				        if (item.checked) {
				            data.types.push(item.dictValue);
				        }
				    });
					console.log(data,'dadadad');
					this.$u.post("/appVerify/fault",data).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: '提交成功',
								icon: 'none',
								duration: 1000
							});
							setTimeout(()=>{
								 uni.navigateBack({
								        delta: 1, // Delta represents how many pages to go back
								        success: function() {
								            // Optionally, you can handle success
								        }
								    });
							},1100)
						}else{
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 1000
							});
						}
					});
			},
			getQiniuToken() {
					this.$u.get("/common/qiniu/uploadInfo").then((res) => {
						if (res.code == 200) {
						this.token=res.token
						console.log(res,'resres');
						this.upurl=res.domain
						}
					});
				// this.$u.get('https://v2.ielts.langsi.online/file/getToken').then(res => {
				// 	console.log(res.data);
				// 	this.token = res.data.token
				// }).catch(err => {
				// 	console.log(err)
				// })
				
			},
			getlist(){
				// checked
				this.$u.get("/appVerify/fault/allList?dictType=et_fault_type").then((res) => {
				
					if (res.code == 200) {
						 this.cbgz = res.data.headstock.map(item => ({...item, checked: false}));
					    this.csgz = res.data.body.map(item => ({...item, checked: false}));
					    this.tsgz = res.data.special.map(item => ({...item, checked: false}));
					} else {
						uni.showToast({
							title: '未登录，请登录后尝试',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			toggleCheckbox(index) {
				this.cbgz[index].checked = !this.cbgz[index].checked;
				this.$forceUpdate()
			},
			csCheckbox(index){
				this.csgz[index].checked = !this.csgz[index].checked;
			},
			tsCheckbox(index){
				this.tsgz[index].checked = !this.tsgz[index].checked;
			},
			hidePlaceholder() {
				this.placeholderVisible = false;
			},
			showPlaceholder() {
				if (!this.textValue) {
					this.placeholderVisible = true;
				}
			},
			scanQRCode() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: res => {
						
						let sn = null;
						let queryParams = res.result.split('?')[1];
						if (queryParams) {
						    let params = queryParams.split('&');
						    params.forEach(param => {
						        let [key, value] = param.split('=');
						        if (key === 'sn') {
						            sn = value;
						        }
						    });
						}
						
						this.sn = sn
						
						
					},
					fail: err => {
						console.error('扫描失败：', err);
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},
			btn() {
				let _this = this
				let math = 'static/' + _this.$u.guid(20)
				uni.chooseImage({
					count: 9,
					type: 'all',
					success(res) {
						// tempFilePath可以作为img标签的src属性显示图片
						const tempFilePaths = res.tempFiles
						// let tempFilePaths = chooseImageRes.tempFilePaths;
						// console.log(tempFilePaths)
						// tempFilePaths.forEach(item=>{
						// 	// 上传图片到七牛云
						
						// })
						wx.uploadFile({
							url: 'https://up-z2.qiniup.com',
							name: 'file',
							filePath: tempFilePaths[0].path,
							formData: {
								token: _this.token, //后端返回的token
								key: 'smartmeter/img/' + math
							},
							success: function(res) {
								console.log(res,'resres');
								let str = JSON.parse(res.data)
								console.log(str.key)
								_this.userImgs = _this.upurl +'/'+ str.key
								console.log(_this.userImgs)
								_this.imglist.push(_this.userImgs)
							}
						});
					}
				})
			
			},
			updateWordCount() {
				this.currentCount = this.textValue.trim().replace(/\s+/g, '').length;
				// if (this.currentCount > 500) {
				// 	this.textValue = this.textValue.slice(0, this.textValue.lastIndexOf(' ', 500)).trim();
				// 	uni.showToast({
				// 		title: '字数已超过500字限制',
				// 		icon: 'none'
				// 	});
				// }
			
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.page {
		width: 750rpx;
		padding-bottom: 150rpx;
		.btn{
			margin: 0 auto;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 680rpx;
			height: 90rpx;
			background: #4C97E7;
			border-radius: 54rpx 54rpx 54rpx 54rpx;
			font-weight: 500;
			font-size: 40rpx;
			color: #FFFFFF;
		}
		.cardbox {
			margin: 30rpx auto;
			width: 680rpx;
			padding: 20rpx 45rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 10rpx 64rpx 0rpx rgba(0, 0, 0, 0.08);
			border-radius: 20rpx 20rpx 20rpx 20rpx;
			
			.tip {
				display: flex;
				flex-wrap: nowrap;
				// align-items: center;
				font-weight: 700;
				font-size: 32rpx;
				color: #3D3D3D;
				line-height: 44rpx;

				.ipnt {
					margin-top: 10rpx;
					margin-right: 12rpx;
					color: #FF4444;
					font-size: 48rpx;

				}
			}

			.iptbox {
				display: flex;
				align-items: center;
				margin-top: 30rpx;
				width: 592rpx;
				height: 80rpx;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				border: 2rpx solid #979797;
				
				.ips {
					margin-left: 30rpx;
					width: 80%;
				}

				.iptbtn {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 112rpx;
					height: 80rpx;
					background: #4C97E7;
					border-radius: 20rpx 20rpx 20rpx 20rpx;

					image {
						width: 37rpx;
						height: 37rpx;
					}
				}
			}

			.txt {
				margin-top: 18rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #3D3D3D;
			}
			.icon {
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				margin-top: 40rpx;
			
				.imgbox {
					width: 33%;
			
					image {
						width: 142rpx;
						height: 142rpx;
					}
				}
			
			}
			.checkbox {
				display: flex;
				flex-wrap: wrap;

				.check_li {
					position: relative;
					 margin-right: 10rpx;
					margin-top: 18rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 142rpx;
					height: 65rpx;
					border-radius: 20rpx 20rpx 20rpx 20rpx;
					border: 2rpx solid #C7C7C7;
					image{
						position: absolute;
						right: 0;
						bottom: 0;
						width: 40rpx;
						height: 20rpx;
					}
				}
				.check_li:nth-child(4n) {
				  margin-right: 0;
				}
				.act1 {
					// background-image: url(https://api.ccttiot.com/smartmeter/img/static/uaqN5qdoGNCs7Dumzr3F);
					width: 142rpx;
					height: 65rpx;
					 // background-size: cover;
					 border: 2rpx solid #4C97E7;
					// background: #4C97E7;
				}
			}
			.input-container {
				position: relative;
				width: 612rpx;
				height: 248rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
				border-radius: 20rpx;
				margin-top: 40rpx;
				overflow: hidden;
				padding-right: 38rpx;
				box-sizing: border-box;
				border: 2rpx solid #C7C7C7;
			}
			
			.placeholder {
				position: absolute;
				top: 18rpx;
				left: 38rpx;
				color: #999;
				/* placeholder颜色 */
				pointer-events: none;
				/* 确保点击事件可以穿透到textarea上 */
			}
			.custom-textarea {
				width: 100%;
				height: 100%;
				/* 设置一个合适高度 */
				padding-top: 18rpx;
				/* 为placeholder留出空间 */
				padding-left: 38rpx;
				box-sizing: border-box;
				border: 1px solid #ccc;
			}
			
			.word-count {
				position: absolute;
				right: 10px;
				bottom: 10px;
				font-size: 12px;
				color: #999;
			}
		}
	}
</style>