<template>
	<view class="container">
		<view class="title">会议名称</view>
		<input class="tui-input" placeholder-class="phcolor" placeholder="请输入会议名称" v-model="name"
			maxlength="20"></input>

		<view class="title">会议分类</view>
		<w-select v-model="type" :list="typeList" valueName="name" keyName="id" filterable></w-select>


		<view class="title top64">组织部门</view>
		<as-tree-select class="tui-input" v-model="unit" title="组织部门" :placeholder="org_name" :options="sortOptions"
			:checkStrictly="true">
		</as-tree-select>

		<view class="title top64">开始时间</view>
		<uni-datetime-picker type="datetime" :clear-icon="false" v-model="drawup" />

		<view class="title top64">结束时间</view>
		<uni-datetime-picker type="datetime" :clear-icon="false" v-model="enddrawup" />

		<view class="title top64">主持人</view>
		<w-select v-model="anchor" :list="anchorList" valueName="nickname" keyName="id" filterable></w-select>

		<view class="title top64">参会人员</view>
		<view class="people">
			<view class="tags">
				<uni-tag :circle="true" type="primary" v-for="item in writer_info" :key="item.id" :text="item.nickname"
					@click="writerTagClick(item)"></uni-tag>
				<uni-tag :circle="true" :inverted="true" @click="popupShow('writer','userList')" text="+"></uni-tag>
			</view>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="writerPopup">
				<view class="search">
					<tui-input label="姓名" v-model="writerNickname" placeholder="请输入姓名" />
					<tui-button width="200rpx" @click="getuserList">搜索</tui-button>
				</view>
				<uni-table ref="writerTable" :loading="loading" border stripe emptyText="暂无更多数据" type="selection">
					<uni-tr @row-click="electionSelectAll">
						<uni-th align="center">用户名</uni-th>
						<uni-th align="center">姓名</uni-th>
						<!-- <uni-th align="center">手机号</uni-th> -->
						<uni-th align="center">部门</uni-th>
					</uni-tr>
					<uni-tr v-for="(value, key) in userList" :key="value.name"
						@row-click="(checked)=>selectionSelect(checked,key,value)">
						<uni-td>
							{{ value.name }}
						</uni-td>
						<uni-td align="center">{{ value.nickname }}</uni-td>
						<!-- <uni-td>{{value.mobile}}</uni-td> -->
						<uni-td>
							<text v-for="(item, index) in value.user_orgs"
								:key="index">{{ item && item.org && item.org.name ? item.org.name : '' }}</text>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="paginate">
					<uni-pagination show-icon :page-size="limit" :current="writerPage" :total="total"
						@change="pageChange" />
				</view>
			</uni-popup>
		</view>

		<view class="title top64">协作人员</view>
		<view class="people">
			<view class="tags">
				<uni-tag :circle="true" type="primary" v-for="(item,index) in actor_info" :key="index" :text="item.name"
					@click="actorTagClick(item)"></uni-tag>
				<uni-tag :circle="true" :inverted="true" @click="popupShow('actor','collaboratorList')"
					text="+"></uni-tag>
			</view>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="actorPopup">
				<view class="search">
					<tui-input label="姓名" v-model="actorName" placeholder="请输入姓名" />
					<tui-button width="200rpx" @click="getcollaboratorList">搜索</tui-button>
				</view>
				<uni-table ref="actorTable" :loading="loading" border stripe emptyText="暂无更多数据" type="selection">
					<uni-tr @row-click="selectionSelectAll">
						<uni-th align="center">姓名</uni-th>
						<uni-th align="center">手机号</uni-th>
						<uni-th align="center">部门</uni-th>
					</uni-tr>
					<uni-tr v-for="(value, key) in collaboratorList" :key="value.worker_id"
						@row-click="(checked)=>selectionSelect(checked,key,value)">
						<uni-td align="center">{{ value.name }}</uni-td>
						<uni-td align="center">{{value.cell_phone}}</uni-td>
						<uni-td align="center">
							<text>{{value.team_name}}</text>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="paginate">
					<uni-pagination show-icon :page-size="limit" :current="actorPage" :total="total"
						@change="pageChange" />
				</view>
			</uni-popup>
		</view>

		<view class="title top64">会议地点</view>
		<view class="address">
			<text class="location">{{ location }}</text>
			<input class="tui-input" placeholder-class="phcolor" placeholder="详细地点" v-model="location_detail"
				maxlength="20"></input>
		</view>
		<view id="myMap" style="width: 100%; height: 400px;background-color: #fff;">
		</view>

		<view class="title top64">会议通知</view>
		<input class="tui-input" placeholder-class="phcolor" placeholder="请输入会议通知" v-model="notify">
		</input>

		<view class="form-upload">
			<view class="form-upload-title">
				会议影像
			</view>

			<view class="form-upload-input">
				<uni-file-picker file-mediatype="image" @select="upload" v-model="uniImages"
					@delete="handleRemove"></uni-file-picker>
			</view>
		</view>

		<view class="top64">
			<view class="title">会议记录</view>
			<!-- todo -->

			<textarea id="content" v-model="content"></textarea>
		</view>

		<view class="tui-ptop">
			<button class="tui-button-primary tui-btn-submit" hover-class="tui-button-hover" @click="submit"
				style="background-color:#008782;">提交</button>
		</view>
		<tui-loading text="上传中..." v-show="isLoading"></tui-loading>
		<tui-tips ref="toast" backgroundColor="#008782" color="#fff"></tui-tips>
	</view>

</template>
<script module="bmap" lang="renderjs">
	export default {
		data() {
			return {
				map: null
			}
		},
		mounted() {
			// 初始化百度地图
			this.initBaiDuMap()
		},
		methods: {
			// 动态创建Script标签
			createScript(url) {
				return new Promise((resolve, reject) => {
					var script = document.createElement('script')
					script.type = 'text/javascript'
					script.src = url
					script.onload = () => {
						resolve()
					}
					script.onerror = () => {
						reject()
					}
					document.head.appendChild(script)
				})
			},
			initBaiDuMap() {
				const ak = 'E4uPHnn6VhE6g7xCBU4V2oqigGc8svx7'
				if (typeof window.BMap == 'function') {
					this.initMap()
				} else {
					window.init = () => this.initMap()
					this.createScript(`https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=init`)
				}
			},
			async initMap() {
				// myMap 要渲染地图的view的id
				this.map = new BMap.Map("myMap")
				let point = new BMap.Point(112.265533, 38.012094);
				this.map.centerAndZoom(point, 15); // 设置中心点
				var scaleCtrl = new BMap.ScaleControl(); // 添加比例尺控件
				this.map.addControl(scaleCtrl);
				var zoomCtrl = new BMap.NavigationControl({
					anchor: BMAP_ANCHOR_TOP_RIGHT
				}); // 添加缩放控件
				this.map.addControl(zoomCtrl)

				// 创建城市选择控件
				var cityControl = new BMap.CityListControl({
					// 控件的停靠位置(可选,默认左上角)
					anchor: BMAP_ANCHOR_TOP_LEFT,
					// 控件基于停靠位置的偏移量(可选)
					offset: new BMap.Size(10, 5)
				});
				// 将控件添加到地图上
				this.map.addControl(cityControl);

				/** 点击地图创建坐标事件Start */
				// 添加地图点击事件
				this.map.addEventListener("click", (e) => {
					var clickpt = e.point; // 点击的坐标
					this.map.clearOverlays(); // 移除地图上的标注
					var marker = new BMap.Marker(clickpt); // 创建标注
					this.map.addOverlay(marker); // 将标注添加到地图中
					// 逆地址解析
					this.geocAddress(clickpt);
				});
				/** 点击地图创建坐标事件End */
			},
			/** 逆向解析地址 point */
			geocAddress(point) {
				var geoc = new BMap.Geocoder();
				geoc.getLocation(point, (geocInfo) => {
					// 设置基本信息
					var addressInfo = geocInfo.addressComponents;
					let address = addressInfo.street + addressInfo.streetNumber;
					if (geocInfo.surroundingPois.length > 0) {
						address = address + geocInfo.surroundingPois[0].title;
					}
					// 改变组件中的值
					this.$ownerInstance.callMethod("renderOver", {
						point,
						addressInfo,
						address
					})
				});
			}
		}
	}
</script>
<script>
	import tuiLoading from "@/components/thorui/tui-loading/tui-loading";
	import tuiTips from "@/components/thorui/tui-tips/tui-tips";
	import wSelect from "@/components/w-select/w-select"
	import {
		mapState,
		mapGetters,
		mapActions,
		mapMutations
	} from "vuex";
	import config from '@/common/config.js'
	export default {
		components: {
			tuiLoading,
			tuiTips,
			wSelect,
		},
		onLoad() {
			let info = uni.getStorageSync('safeconference_info')
			if (info) {
				this.id = info.id
				this.name = info.name
				this.unit = info.unit.toString()
				this.org_name = info.org.name
				this.drawup = info.drawup
				this.enddrawup = info.enddrawup
				this.location = info.location
				this.location_detail = info.location_detail
				this.longitude = info.longitude
				this.latitude = info.latitude
				this.images = info.images
				this.uniImages = info.images.map(item => {
					return {
						...item,
						url: this.joinImageUrl(item.url)
					}
				})
				this.anchor = info.anchor
				this.anchor_info = info.anchor_info
				this.writer = info.writer
				this.writer_info = info.writer_info
				this.actor = info.actor
				this.actor_info = info.actor_info
				this.notify = info.notify
				this.content = info.content
				this.type = info.type
			} else {
				uni.setNavigationBarTitle({
					title: '新建会议'
				})
			}
			this.getOrgInfo()
			this.getuserList()
			this.getTypeList()
		},
		onShow() {
			if (!this.hasLogin) {
				uni.redirectTo({
					url: '/pages/common/login/login?href2=user/user/index'
				});
				return false;
			}
		},
		computed: {
			...mapState(["hasLogin", "userinfo"]),
		},
		data() {
			return {
				id: 0,
				name: "",
				unit: "",
				type: "",
				org_name: "",
				location: "",
				location_detail: "",
				longitude: "",
				latitude: "",
				drawup: "",
				enddrawup: "",
				images: [],
				anchor: '',
				anchor_info: {},
				writer: [],
				writer_info: [],
				actor: [],
				actor_info: [],
				uniImages: [],
				notify: '',
				content: '',
				isLoading: false,
				uploadImg: [],
				sortOptions: [],
				userList: [],
				anchorList: [],
				collaboratorList: [],
				typeList: [],
				userIsNoPage: true,
				field: 'writer',
				listName: 'userList',
				writerNickname: '',
				actorName: '',
				// 每页数据量
				limit: 5,
				// 当前页
				writerPage: 1,
				actorPage: 1,
				// 数据总量
				total: 0,
				loading: false,
				editor: null, //编辑器实例
			};
		},
		methods: {
			renderOver({
				point,
				addressInfo,
				address
			}) { // 可以获取renderjs中的数据
				this.longitude = point.lng;
				this.latitude = point.lat;
				this.location = addressInfo.province + addressInfo.city + addressInfo.district + address;
			},
			writerTagClick(row) {
				this.field = 'writer'
				this.destroyItem(row)
			},
			actorTagClick(row) {
				this.field = 'actor'
				this.destroyItem(row)
			},
			pageChange(e) {
				this.$refs[this.field + 'Table'].clearSelection()
				this[this.field + 'Page'] = e.current
				this['get' + this.listName]()
			},
			selectionSelect(checked, key, row) {
				if (this[this.field].includes(row[this.field == 'actor' ? 'worker_id' : 'id'])) {
					this.destroyItem(row)
				} else {
					this.storeItem(row)
				}
				return
			},
			selectionSelectAll(checked) {
				if (checked) {
					this[this.listName].map((item, index) => {
						if (this[this.field].indexOf(item[this.field == 'actor' ?
								'worker_id' : 'id'
							]) === -1) {
							this.storeItem(this[this.listName][index])
						}
					})
				} else {
					this[this.listName].map((item, index) => {
						this.destroyItem(item)
					})
				}
			},
			storeItem(row) {
				this[this.field].push(row[this.field == 'actor' ? 'worker_id' : 'id'])
				this[this.field + '_info'].push(row)
			},
			destroyItem(row) {
				if (this[this.field].indexOf(row[this.field == 'actor' ? 'worker_id' : 'id']) !== -1) {
					this[this.field].splice(this[this.field].indexOf(row[this.field == 'actor' ? 'worker_id' : 'id']), 1);
				}
				if (this[this.field + '_info'].findIndex(x => x[this.field == 'actor' ? 'worker_id' : 'id'] === row[this
						.field == 'actor' ? 'worker_id' : 'id']) !== -1) {
					this[this.field + '_info'].splice(this[this.field + '_info'].findIndex(x => x[this.field == 'actor' ?
						'worker_id' : 'id'] === row[this.field == 'actor' ? 'worker_id' : 'id']), 1);
				}
			},
			popupShow(field, listName) {
				this.field = field
				this.listName = listName
				this.userIsNoPage = false
				this['get' + this.listName]()
				this.$refs[this.field + 'Popup'].open('bottom')
			},
			getOrgInfo() {
				getApp().globalData.request.post(
					"learn/train/getOrgInfo"
				).then(res => {
					this.sortOptions = res.data
				})
			},
			getTypeList() {
				getApp().globalData.request.post(
					"responsibility/safeconference/typeList"
				).then(res => {
					this.typeList = res.data
				})
			},
			getuserList() {
				getApp().globalData.request.post(
					"responsibility/safeconference/userList", {
						limit: this.limit,
						page: this.writerPage,
						isNoPage: this.userIsNoPage,
						nickname: this.writerNickname,
					}
				).then(res => {
					if (!this.userIsNoPage) {
						this.userList = res.data.data
						this.$nextTick(() => {
							this.userList.forEach((item, index) => {
								if (this.writer_info.some((x) => item.id === x.id)) {
									this.$refs.writerTable.toggleRowSelection(index)
								}
							})
						})

						this.total = res.data.total
					} else {
						this.anchorList = res.data
					}

				})
			},
			getcollaboratorList() {
				getApp().globalData.request.post(
					"responsibility/safeconference/collaborator", {
						isPage: true,
						limit: this.limit,
						page: this.actorPage,
						name: this.actorName,
					}
				).then(res => {
					this.collaboratorList = res.data

					this.$nextTick(() => {
						this.collaboratorList.forEach((item, index) => {
							if (this.actor_info.some((x) => item.id === x.id)) {
								this.$refs.actorTable.toggleRowSelection(index)
							}
						})
					})

					this.total = res.total
				})
			},
			handleRemove(data) {
				this.images = this.images.filter(item => this.joinImageUrl(item.url) !== data.tempFile.url);
				this.uniImages = this.uniImages.filter(item => item.url !== data.tempFile.url);
			},
			joinImageUrl(url) {
				return config.ROOTPATH + url.substring(1)
			},
			async upload(data) {
				let res = await getApp().globalData.request.upload(
					config.ROOTPATH + "mobile/common/upload/uploadImage",
					data.tempFilePaths[0],
					data.tempFiles[0]
				);
				this.images.push(res.data)
				this.uniImages.push({
					...res.data,
					url: this.joinImageUrl(res.data.url)
				})
			},
			showTips(msg) {
				let options = {
					msg,
					duration: 3000,
				};
				this.$refs.toast.showTips(options);
			},
			async submit() {
				if (!this.name) {
					uni.showToast({
						title: "请输入会议名称",
						icon: "error",
					});
					return
				}
				let url = ''
				if (this.id) {
					url = "responsibility/safeconference/update/" + this.id
				} else {
					url = "responsibility/safeconference/store"
				}
				var res = await getApp().globalData.request.post(
					url, {
						id: this.id,
						name: this.name,
						unit: this.unit,
						drawup: this.drawup,
						enddrawup: this.enddrawup,
						images: this.images,
						notify: this.notify,
						content: this.content,
						anchor: this.anchor,
						writer: this.writer,
						actor: this.actor,
						type: this.type,
						location: this.location,
						location_detail: this.location_detail,
						longitude: this.longitude,
						latitude: this.latitude,
					}
				);
				if (res.code == 0) {
					uni.showToast({
						title: res.msg,
						icon: "success",
					});
					setTimeout(() => {
						uni.redirectTo({
							url: 'index'
						});
					}, 1500)
				} else {
					uni.showToast({
						title: res.msg,
						icon: "error",
					});
				}
			},
			/* 以下为处理editor */

		}
	};
</script>
<style>
	.form-upload {
		/* height: 240rpx; */
		margin-top: 40rpx;
	}

	.form-upload-title {
		font-size: 30rpx;
		color: #666;
		margin-bottom: 30rpx;
	}

	.form-upload-input {
		margin-left: 20rpx;
	}

	.tui-btn-submit {
		margin-top: 100rpx;
		background: #008681;
		font-size: 28rpx;
	}

	page {
		background: #fff;
	}

	.container {
		background-color: #fff;
		margin-top: 22rpx;
		padding: 30rpx;
		box-sizing: border-box;
		padding-bottom: 162rpx;
	}

	.title {
		font-size: 30rpx;
		color: #666;
		padding-bottom: 32rpx;
	}

	.tui-cells {
		border: 1rpx solid #e6e6e6;
		border-radius: 4rpx;
		height: 280rpx;
		box-sizing: border-box;
		padding: 20rpx 20rpx 0 20rpx;
	}

	.tui-textarea {
		height: 210rpx !important;
		width: 100%;
		color: #666;
		font-size: 28rpx;
		border: 1rpx solid #e6e6e6;
		border-radius: 4rpx;
	}

	.pholder {
		color: #ccc;
	}

	.textarea-counter {
		font-size: 24rpx;
		color: #999;
		text-align: left;
		height: 40rpx;
		line-height: 40rpx;
		padding-top: 4rpx;
	}

	.top64 {
		margin-top: 20rpx;
	}

	.tui-input {
		font-size: 30rpx;
		height: 88rpx;
		border: 1rpx solid #e6e6e6;
		border-radius: 4rpx;
		padding: 0 25rpx;
		box-sizing: border-box;
	}

	.tui-ptop {
		padding-top: 80rpx;
	}

	.submit {
		background: #008681;
	}

	/deep/ .uni-table {
		min-width: 100% !important;
	}

	.paginate {
		background: #FFF;
	}

	.people {
		.tags {
			display: flex;
			gap: 2rpx;
			flex-wrap: wrap;
		}
	}

	.address {
		.location {
			padding-left: 25rpx;
			color: #aaa;
		}
	}

	.search {
		display: flex;
	}
</style>