<template>
	<view class="hidden">
		<view class="hiddenItem">
			<u--form labelWidth="150rpx" :model="dataUser" ref="uForm" labelAlign="right">
				<u-form-item label="活动名称:" prop="names" borderBottom>
					<u--input v-model="dataUser.names" placeholder="请输入活动名称"></u--input>
				</u-form-item>
				<u-form-item label="活动介绍:" prop="comment" borderBottom>
					<u--textarea :maxlength="-1" v-model="dataUser.comment" placeholder="请输入内容"
						autoHeight></u--textarea>
				</u-form-item>
				<u-form-item label="类别:" prop="comment" borderBottom @click="show = true">
					<u-action-sheet @select="radioChanges" @close="show = false" closeOnClickAction="true"
						:actions="radiolist" :show="show"></u-action-sheet>
					<view class="dataUserunit" :style="{color: dataUser.type ||'#c2cad2'}" v-model="dataUser.type">
						{{dataUser.type || "请输入用户类型"}}
					</view>
				</u-form-item>
				<u-form-item label="上传图片:" borderBottom @click="chooseImage">
					<view style="color: red">点击上传图片最多只能上传9张</view>
				</u-form-item>
			</u--form>
		</view>

		<view class="drag-container">
			<view class="darg-item item-transition" v-for="(item, index) in dragImgList" :mark:index="index"
				:mark:key="item.key" :key="index"
				:style="{ transform: `translate(${index === currentIndex ? tranX : item.tranX + 'px'},${index === currentIndex ? tranY : item.tranY + 'px'})` }">
				<image class="darg-item-img" :src="item.src" mode="aspectFit"></image>
				<text class="drag-item-delete" :key="item.key" @click="deleteImg">x</text>
			</view>

		</view>
		<view class="uploadbutton"
			:style="{ transform: `translate(${uploadPosition.tranX + 'px'},${uploadPosition.tranY + 'px'})` }">
			<button :hidden="!dragImgList.length" @click="uploadImage" size="mini" type="primary">提交申请</button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import {
		timestampFormatTime
	} from '@/utils/index.js';
	import {
		schoolnewsdata
	} from '@/api/login.js';
	export default {
		data() {
			return {
				dataUser: {
					names: '',
					comment: '',
					type: ''
				},
				show: false,
				radiolist: [{
						name: '应急演练'
					},
					{
						name: '法治宣传'
					},
					{
						name: '校园风采'
					}
				],
				baseURl: 'https://www.lonsungsh.com:8083',
				dragImgList: [], // 图片列表 { src: string, key: number, tranX: number, tranY: number }[]
				imageID: [], //上传图片的id集合
				imageUrlsDate: [], //上传图片url的合集
				uploadPosition: {
					// upload上传图标位移距离
					tranX: 0,
					tranY: 0
				},
				ITEM_SIZE: 128, // 图片大小 单位px
				// containerRes: {}, // 拖拽容器属性
				currentKey: -1, // 正在拖拽图片的key
				currentIndex: -1, // 正在拖拽图片的index
				tranX: 0, // 正在拖拽图片移动的x距离
				tranY: 0, // 正在拖拽图片移动的y距离
			};
		},
		onLoad() {},
		computed: {
			// 拿取vuex数据
			...mapGetters({
				userInfo: 'users/getLoginInfo'
			})
		},
		methods: {
			chooseImage() {
				console.log(1111);
				// 多张图片上传
				var that = this;
				if (that.dragImgList.length >= 9) {
					uni.showToast({
						title: '最大限制9张',
						timeout: 6000
					});
					console.log(222);
				} else {
					
					console.log(333);
					uni.chooseImage({
						count: 9,
						sizeType: ['original', 'compressed'],
						mediaType: ['image', 'video'],
						sourceType: ['album', 'camera'],
						maxDuration: 30,
						camera: 'back',
						success: async (res) => {							
							if (!res) {
								return  
							}
							const imgs = res.tempFiles
							if (!imgs || imgs.length <= 0) {
								return
							}
							const picUploadData = {
								creator: that.userInfo.name,
								business: 'school.news',
								type: 'image',
								deviceid: that.userInfo.id,
								createtime: timestampFormatTime(),
								description: '2222',
								comment: '图片描述'
							};

							for (var i = 0; i < imgs.length; i++) {
								const item = imgs[i];
								let listParams = {
									tranX: that.ITEM_SIZE * ((that.dragImgList.length + i) % 3),
									tranY: Math.floor((that.dragImgList.length + i) / 3) * that.ITEM_SIZE,
									key: that.dragImgList.length + i
								}
								wx.uploadFile({
									url: that.baseURl + '/mdev/picture/upload',  //这里就是保存到服务器的接口
									filePath: item.path,
									timeout: 5000,
									// 参数名和接口一致
									name: 'file',
									header: {
										'Content-Type': 'multipart/form-data;charset=utf-8'
									},
									formData: {
										jsondata: JSON.stringify(picUploadData)
									},
									success(res) {
										const resImage = JSON.parse(res.data)?.data;
										if (resImage) {
											listParams.src = that.baseURl + resImage.uri,
												that.dragImgList.push(listParams);
											if (!that.imageID.includes(resImage.id)) {
												that.imageID.push(resImage.id);
											}
											if (!that.imageUrlsDate.includes(resImage.uri)) {
												that.imageUrlsDate.push(resImage.uri);
											}
											that.setUploaPosition(that.dragImgList.length);
										}
									},
									fail(err) {
										uni.showToast({
											title: err,
											timeout: 6000
										});
										
									}
								})
							}
							
						},
						fail(res) {
							uni.showToast({
								title: res,
								timeout: 6000
							});
						}
					});
				}
			},
			// 修改上传图片位置
			setUploaPosition(listLength) {
				const uploadPositions = {
					tranX: (listLength % 3) * this.ITEM_SIZE,
					tranY: Math.floor(listLength / 3) * this.ITEM_SIZE
				};
				this.uploadPosition = {
					tranX: uploadPositions.tranX,
					tranY: uploadPositions.tranY
				};
			},
			/**
			 * 删除图片
			 */
			deleteImg(e) {
				var that = this;
				const keyDelete = e.mark.key;
				const list = that.dragImgList.filter((item) => item.key !== keyDelete);
				let imagesLIst = that.imageID.filter((value, index, arr) => index !== keyDelete);
				that.imageID = imagesLIst;
				let UrlsDateLIst = that.imageUrlsDate.filter((value, index, arr) => index !== keyDelete);
				that.imageUrlsDate = UrlsDateLIst;
				console.log(that.imageUrlsDate);
				list.forEach((item) => item.key > keyDelete && item.key--);
				that.getListPosition(list);
				that.setUploaPosition(list.length);
			},
			/**
			 * 修改位置
			 */
			getListPosition(list) {
				const dragImgLists = list.map((item) => {
					item.tranX = this.ITEM_SIZE * (item.key % 3);
					item.tranY = Math.floor(item.key / 3) * this.ITEM_SIZE;
					return item;
				});
				this.dragImgList = dragImgLists;
			},
			// 提交
			uploadImage() {
				var that = this;
				const schoolNews = {
					newsId: `${Math.round(Math.random() * 100000000)}`,
					creator: that.userInfo.name,
					timestamp: timestampFormatTime(),
					title: that.dataUser.names,
					comment: that.dataUser.comment,
					images: JSON.stringify(that.imageID),
					imageUrls: JSON.stringify(that.imageUrlsDate),
					brigade: that.userInfo.brigade,
					borough: that.userInfo.borough,
					detachment: '',
					station: that.userInfo.station,
					type: that.dataUser.type
				};
				schoolnewsdata(schoolNews)
					.then((res) => {
						uni.showLoading({
							title: '正在上传中....'
						});
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: '上传成功'
							});
							setTimeout(() => {
								uni.switchTab({
									url: `/pages/securityCheck/securityCheck`
								});
							}, 900);
						}, 1000);
					})
					.catch((error) => {
						console.log(error);
					});
			},

			radioChanges(val) {
				this.dataUser.type = val.name
			}
		}
	};
</script>

<style lang="scss">
	.hidden {
		height: 95vh;
		display: flex;
		flex-direction: column;

		.imageItem {
			margin-left: 20rpx;
		}

		.drag-container {
			position: relative;
			width: 300px;
			// height: 430px;
		}

		.item-transition {
			transition: transform 0.1s;
		}

		.darg-item {
			position: absolute;
			top: 0;
			left: 0;
			width: 123px;
			height: 123px;
		}

		.darg-item-img {
			width: 100%;
			height: 100%;
			// border: 1px solid red;
		}

		.drag-item-delete {
			position: absolute;
			top: 19px;
			right: -1px;
			width: 45rpx;
			height: 33rpx;
			background-color: rgba(0, 0, 0, 0.5);
			font-size: 34rpx;
			line-height: 25rpx;
			text-align: center;
			border-radius: 0 0 0 114rpx;
			color: #fff;
		}

		.drag-item-upload {
			background-color: burlywood;
			font-size: 200rpx;
			text-align: center;
			color: white;
			line-height: 160rpx;
		}

		.uploadbutton {
			width: 224rpx;
			height: 100rpx;
			text-align: center;
			line-height: 50px;
			overflow: hidden;
			margin-top: 49px;
		}

		.dataUserunit {
			padding-left: 16rpx;
		}
	}
</style>