<template>
	<view>
		<u-form :model="cameara" ref="uForm">
			<u-form-item label-width="150" label="设备编号">
				<u-input v-model="cameara.number" disabled='true' />
			</u-form-item>
			<u-form-item label-width="150" label="设备类型">
				<u-input v-model="cameara.type" disabled='true' />
			</u-form-item>
			<u-field v-model="cameara.remarks" label="备注" placeholder="备注" type="textarea">
			</u-field>
			<view>
				<view class="uploadImages">
					<view v-for="(item,index) in imgList" class="imgBox">
						<image mode="aspectFit" :src="item.url"></image>
						<uni-icons type="trash" size="22" @click="removeImage(index)"></uni-icons>
					</view>
					<uni-icons type="plusempty" size="48" @click="selectBase64Img"></uni-icons>
				</view>
			</view>

		</u-form>

		<u-button v-if="cameara.id!=''" class="btn1" type="primary" @click="updateAction(1)">更新</u-button>
		<u-button v-if="cameara.id==''" class="btn1" type="primary" @click="updateAction(2)">新增</u-button>
	</view>
</template>

<script>
	import config from "../../libs/config/config.js"
	const _api = config.api + "/upload"

	export default {
		data() {
			return {
				cameara: {
					id: "",
					camera_name: "",
					camera_code: "",
					longitude: "",
					latitude: "",
					images: "",
					remarks: "",
					type: "",
				},
				radioList: [{
						name: '摄像头',
						disabled: false
					},
					{
						name: '消防栓',
						disabled: false
					},
					{
						name: '消防炮',
						disabled: false
					},
					{
						name: '泡沫栓',
						disabled: false
					},
					{
						name: '栓炮一体',
						disabled: false
					},
					{
						name: '手动报警器',
						disabled: false
					},
					{
						name: '消防器材箱',
						disabled: false
					}
				],
				radio: '',
				switchVal: false,
				action: _api,
				fileList: [],
				uploadList: [],
				camearaDetails: null,
				imgList: [],
			};
		},
		onLoad(options) {
			if (options.cameara) {
				this.cameara = JSON.parse(options.cameara)
				uni.setNavigationBarTitle({
					title: '编辑'
				})
				this.getById(this.cameara.id)
			}
		},
		onShow() {
			this.cameara = this.$store.state.equip.currentData
			if(this.$store.state.equip.currentDataDetails){
				if(this.$store.state.equip.currentDataDetails.remarks){
						this.cameara.remarks=this.$store.state.equip.currentDataDetails.remarks
				}
			}
		},
		methods: {
			getImgByDocId(docIdList) {
				let _this =this;
				docIdList.map((item) => {
					_this.$u.post(config.api + '/xfhrshInternet/service/selImageBase64', JSON.stringify({
						docId: item.docId,
					})).then(res => {
						console.log(res)
						if(res.code==0){
							_this.imgList.push({
								url: res.data,
								docId: item.docId
							})
						}
					});
				})
			},
			removeImage(index) {
				this.imgList=this.imgList.splice(index, 1)
				console.log(index)
			},
			selectBase64Img() {
				let _this = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePath = res.tempFilePaths[0]
						_this.imgUrlToBase64(tempFilePath)
					}
				});

			},
			uploadImg() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log(res, '返回临时路径');
						const tempFilePath = res.tempFilePaths[0]
						this.imgUrlToBase64(tempFilePath)
					}
				})
			},
			imgUrlToBase64(url) {
				let _this = this;
				// #ifdef MP-WEIXIN
				uni.getFileSystemManager().readFile({
					filePath: url, //选择图片返回的相对路径
					encoding: 'base64', //编码格式
					success: res => { //成功的回调
						console.log(res, '返回结果');
						let base64 = 'data:image/png;base64,' + res.data //不加上这串字符，在页面无法显示的哦
						console.log(base64)
						this.$u.post(config.api + '/xfhrshInternet/service/uploadImage', JSON.stringify({
							fileName: uni.$u.guid(20) + '.png',
							data: base64
						})).then(res => {
							console.log()
							_this.imgList.push({
								url: base64,
								docId: res.docId
							})
							//this.camera_list = res;
						});

					},
					fail: (e) => {
						console.log("图片转换失败");
					}
				})

				// #endif

				// #ifdef H5
				uni.request({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer',
					success: ress => {
						let base64 = uni.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
						base64 = 'data:image/png;base64,' + base64;
						console.log(base64, '转换结果')
						this.imgURL = base64
					},
					fail: (e) => {
						console.log("图片转换失败");
					}

				})

				// #endif
				// #ifdef APP-PLUS
				plus.io.resolveLocalFileSystemURL(url, (entry) => {
					// 可通过entry对象操作test.html文件 
					entry.file((file) => {
						let fileReader = new plus.io.FileReader();
						fileReader.onloadend = (evt) => {
							const base64 = evt.target.result.substr(22);
							this.imgURL = base64
						}
						fileReader.readAsDataURL(file);
					});
				}, (e) => {
					alert("Resolve file URL failed: " + e.message);
				});
				// #endif
			},
			getById(id) {
				this.$u.post(config.api + '/xfhrshInternet/service/selPicture', {
					subjectId: id
				}).then(res => {
					console.log(res)
					if (res.status = "success") {
						if(res.data.length>0){
							this.$store.dispatch('setCurrentEquipDtails', {
								data: res.data[0]
							})
							this.getImgByDocId(res.data[0].docIds)
						}
					}
					//this.camera_list = res;
				});
			},
			// 图片自动上传成功的钩子
			onSuccess(data) {
				console.log("========================onSuccess")
				let files = [];
				// 通过filter（过滤数组），筛选出上传进度为100的文件
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				// 如果不需要进行太多的处理，直接如下即可
				files = this.$refs.uUpload.lists;
				console.log(files);
				this.fileList.push({
					url: data.url
				});
			},
			clickAction() {
				uni.$emit('updateCamera', {
					cameara: this.cameara
				})
				uni.navigateBack()
			},
			onRemove(index) {
				console.log('图片已被移除', index);
				this.fileList.splice(index, 1); // arr.splice(i,n) 删除从i(索引值)开始之后的那个元素。返回值是删除的元素
			},
			updateAction(index) {
				console.log(this.$store.state.equip.currentData)
				let _data = {
					subjectId: this.$store.state.equip.currentData.id,
					remarks: this.cameara.remarks,
					docId: []
				}
				this.imgList.map((item) => {
					_data.docId.push(item.docId)
				})
				_data.docId=JSON.stringify(_data.docId)
			    this.$store.dispatch('updateEquipDetails', {data: _data})
			}
		}
	};
</script>
<style lang="scss">
	.uploadImages {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
	}

	.imgBox {
		width: 200rpx;
		height: 200rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

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

	.u-btn {
		margin-top: 40rpx;
	}
</style>
