<template>
	<view>
		<view v-if="stepOne">
			<view class="form">
				<view class="form-title">基本信息</view>
				<view class="form-item-title">封面图</view>
				<view class="upload-pic ddflex" v-if="!pic" @click="uploadImage(1)">
					<image src="../static/images/pic.png"></image>
					<view style="margin-top: 30rpx;">上传封面图</view>
				</view>
				<image v-else class="upload-image" :src="pic" @click="uploadImage(1)"></image>
				<view class="form-limit">* 图片尺寸限制：680*350</view>
				<view class="form-item-title">活动详情轮播图</view>
				<view class="ddflex" style="margin-top: 30rpx;">
					<view class="upload-photo-image" v-for="item ,index in fileList" @click="uploadImage(2,index+1)">
						<image :src="item" mode="aspectFill"></image>
						<image class="upload-photo-close" src="/static/pages/images/close3.png"
							@click.stop="deleteImage(2,index+1)"></image>
					</view>
					<view class="upload-photo ddflex" @click="uploadImage(2)" v-if="fileList.length<9">
						<image src="../static/images/photo.png"></image>
					</view>
				</view>
				<view class="form-limit">* 图片尺寸限制：670*350</view>
			</view>
			<view class="form-border"></view>
			<view class="form">
				<view class="form-item-title">活动标题</view>
				<view class="form-input-box">
					<input v-model="title" placeholder-class="form-input-placeholder" placeholder="请输入活动标题" />
				</view>
				<view class="form-item-title">活动说明</view>
				<view class="form-input-box">
					<input v-model="brief" placeholder-class="form-input-placeholder" placeholder="请填写活动简介说明" />
				</view>
				<view class="form-item-title">
					活动详情
					<view class="more ddflex" @click="jumpUrl('/match/editorContent/editorContent')">
						<text v-if="!text">编辑</text>
						<text v-else style="color: var(--main);">已完善</text>
						<image src="../../static/pages/images/more.png"></image>
					</view>
				</view>
				<view class="form-input-box" style="padding: 18rpx 0;">
				</view>
				<view class="form-item-title">
					自定义报名信息
					<view class="more ddflex" @click="jumpUrl('/match/addForm/addForm')">
						<text style="color: #999;" v-if="!extForm">添加（非必填）</text>
						<text v-else style="color: var(--main);">已添加</text>
						<image src="../../static/pages/images/more.png"></image>
					</view>
				</view>
				<view class="next-btn" @click="next">下一步</view>
			</view>
		</view>

		<!-- 第二步 -->
		<view v-if="stepTwo">
			<view class="form">
				<view class="form-title">报名设置</view>
				<view class="form-item-title">最大报名人数</view>
				<view class="form-number-select ddflex">
					<view @click="jian">-</view>
					<input v-model="personLimit" type="number" placeholder="最大报名人数"
						placeholder-class="form-input-placeholder" />
					<view @click="jia">+</view>
				</view>
				<view class="form-item-title" style="color: red;font-size: 24rpx;margin-top: 20rpx;" v-if="checkNum==0">
					*-1为不限制报名人数
				</view>
				<view class="form-item-title">报名时间</view>
				<view class="ddflex" style="margin-top: 20rpx;">
					<picker v-model="enlistStartTime" mode="date" class="flex" @change="enlistStartTimeChange">
						<view class="form-date-select" :style="enlistStartTime?'color:#333':''">
							{{enlistStartTime?enlistStartTime:'开始日期'}}
						</view>
					</picker>
					<text style="margin: 0 20rpx;">至</text>
					<picker v-model="enlistEndTime" mode="date" class="flex" @change="enlistEndTimeChange">
						<view class="form-date-select" :style="enlistEndTime?'color:#333':''">
							{{enlistEndTime?enlistEndTime:'结束日期'}}
						</view>
					</picker>
				</view>
				<view class="form-item-title">活动时间</view>
				<view class="ddflex" style="margin-top: 20rpx;">
					<picker v-model="startTime" mode="date" class="flex" @change="startTimeChange">
						<view class="form-date-select" :style="startTime?'color:#333':''">
							{{startTime?startTime:"开始日期"}}
						</view>
					</picker>
					<text style="margin: 0 20rpx;">至</text>
					<picker v-model="endTime" mode="date" class="flex" @change="endTimeChange">
						<view class="form-date-select" :style="endTime?'color:#333':''">
							{{endTime?endTime:"结束日期"}}
						</view>
					</picker>
				</view>
			</view>
			<view class="form-border"></view>
			<view class="form">
				<view class="form-title">活动地址</view>
				<view class="form-item-title">地址名称</view>
				<view class="form-input-box">
					<input v-model="house" placeholder-class="form-input-placeholder" placeholder="请输入活动地址简称" />
				</view>
				<view class="form-item-title">选择城市</view>
				<view class="form-input-box">
					<!-- <picker class="form-input-placeholder" mode="region" @change="bindRegionChange" :value="region" > -->
					<view class="picker" :style="region.length>0?'color: #333;':'color:#cccccc'"
						@click="chooseLocation()">
						{{region.length > 0 ? region[0]+region[1]+region[2] : '请选择所在城市'}}
					</view>
					<!-- </picker> -->
					<!-- <image src="/card/static/images/area.png" class="loca" @click="chooseLocation()"></image> -->
				</view>
				<view class="form-item-title">
					详细地址
				</view>
				<view class="form-input-box">
					<input v-model="address" placeholder-class="form-input-placeholder" placeholder="请输入详细地址" />
				</view>
				<view class="form-item-title ddflex" style="justify-content: space-between;">
					是否全省通用
					<switch v-model="isAllSee" :checked="isAllSee" style="transform:scale(0.7)" color="var(--main)"
						@change="powerChange"></switch>
				</view>
				<block v-if="!isAllSee">
					<view class="form-input-box" style="border-bottom: none;" @click="showPop()">
						已选择{{checkNum}}个区域
						<view class="more ddflex">
							<!-- <text v-if="!text">编辑</text>
							<text v-else style="color: var(--main);">已完善</text> -->
							<image src="../../static/pages/images/more.png"></image>
						</view>
					</view>
					<view class="form-item-title" style="color: red;font-size: 24rpx;margin-top: 0rpx;" v-if="checkNum==0">
						*请选择活动生效区域
					</view>
					
					<view class="mask" v-if="isShowPop" @click="hidePop"></view>
					<view class="popup" v-if="isShowPop">
						<view class="popupc ddflex">
							<view class="pleft">
								<view :class="'li ddflex' + (checkIndex == index ? ' active':'')" style="justify-content: space-between;"
									v-for="(item,index) in industryList" :key="index" @click="checkIndustry(index)">
									<view class="fflex tover">{{item.label}}</view>
									<image v-if="item.isActive" style="width: 25rpx;height: 25rpx;margin-left: 10rpx;" src="/match/static/images/checkBox_h.png" @click.stop="checkBoxIndustry(index)"></image>
									<image v-else style="width: 25rpx;height: 25rpx;margin-left: 10rpx;" src="/match/static/images/checkBox.png" @click.stop="checkBoxIndustry(index)"></image>
								</view>
							</view>
							<view class="pright">
								<view :class="'li ddflex' + (arrayIndex == index ? ' active':'')" style="justify-content: space-between;"
									v-for="(item,index) in rightArray" :key="index" @click="checkArray(index)">
									<view class="fflex tover">{{item.label}}</view>
									<image v-if="item.isActive" style="width: 25rpx;height: 25rpx;margin-left: 10rpx;" src="/match/static/images/checkBox_h.png" @click.stop="checkBoxArray(index)"></image>
									<image v-else style="width: 25rpx;height: 25rpx;margin-left: 10rpx;" src="/match/static/images/checkBox.png" @click.stop="checkBoxArray(index)"></image>
								</view>
							</view>
						</view>
					</view>
				</block>
				<view class="next-btn" @click="submit()">提交</view>
			</view>
		</view>
	</view>
</template>

<script>
	import util from "../../utils/util.js";
	const app = getApp();
	const req = require("../../utils/request.js");

	export default {
		components: {},
		props: {},
		data() {
			return {
				stepOne: true,
				stepTwo: false,

				pic: '', //封面图
				fileList: [], //banner
				title: '',
				brief: '',
				text: '',
				personLimit: -1,
				enlistStartTime: '',
				enlistEndTime: '',
				startTime: '',
				endTime: '',
				house: '',
				region: [],
				address: '',
				regionCode: [],
				id: '',
				longitude: null,
				latitude: null,

				isAllSee: true,
				isShowPop: false,
				checkIndex: 0,
				industryList: [],
				arrayIndex: -1,
				rightArray: [],
				
				companyTreeList:[],
				checkNum:0,
				
				extForm:''

			}
		},
		async onLoad(options) {
			this.id = options.id
			await this.getCompanyTreeList()
			if (this.id) {
				this.getActivityInfo()
			}
		},
		onShow() {

		},
		methods: {
			jumpUrl(url) {
				uni.navigateTo({
					url: url
				})
			},
			// 获取公司代码
			getCompanyTreeList(){
				return new Promise((r,j)=>{
					req.getRequest('/api/company/treeList',{},res=>{
						this.companyTreeList = res
						this.industryList = this.companyTreeList[0]&&this.companyTreeList[0].children?this.companyTreeList[0].children:[]
						this.rightArray = this.industryList[0]&&this.industryList[0].children?this.industryList[0].children:[]
						r()
					})
				})
			},
			checkIndustry(index){
				if(this.checkIndex == index) return false;
				this.checkIndex = index;
				this.rightArray = this.industryList[this.checkIndex].children;
			},
			checkBoxIndustry(index){
				if(this.industryList[index].isActive){
					this.industryList[index].isActive = false
					this.industryList[index].children.map(item=>{item.isActive = false})
				}else{
					this.industryList[index].isActive = true
					this.industryList[index].children.map(item=>{item.isActive = true})
				}
				this.industryList = JSON.parse(JSON.stringify(this.industryList))
				this.checkIndex = index;
				this.rightArray = this.industryList[this.checkIndex].children;
			},
			checkBoxArray(index){
				if(this.industryList[this.checkIndex].children[index].isActive){
					this.industryList[this.checkIndex].children[index].isActive = false
				}else{
					this.industryList[this.checkIndex].children[index].isActive = true
				}
				console.log(this.industryList[this.checkIndex].children.some(item=>item.isActive == false))
				if(this.industryList[this.checkIndex].children.some(item=>item.isActive == true)){
					this.industryList[this.checkIndex].isActive = true
				}else{
					this.industryList[this.checkIndex].isActive = false
				}
				this.industryList = JSON.parse(JSON.stringify(this.industryList))
				this.rightArray = this.industryList[this.checkIndex].children;
			},
			getCheckNum(){
				console.log(this.checkNum)
				this.checkNum = 0
				if(!this.isAllSee){
					this.industryList.map(item=>{
						item.children.map(it=>{
							if(it.isActive){
								this.checkNum++
							}
						})
					})
				}
			},
			getActivityInfo() {
				req.getRequest('/api/match/detail', {
					id: this.id
				}, res => {
					this.pic = res.pic
					this.fileList = res.imageList.map(item => {
						return item.url
					})
					this.title = res.title
					this.brief = res.brief
					this.text = res.text
					this.personLimit = res.personLimit
					this.extForm = res.extForm
					this.enlistStartTime = this.formatTime(res.enlistStartTime)
					this.enlistEndTime = this.formatTime(res.enlistEndTime)
					this.startTime = this.formatTime(res.startTime)
					this.endTime = this.formatTime(res.endTime)
					this.house = res.house?res.house:''
					if(res.province&&res.city&&res.country){
						this.regionCode = [res.province, res.city, res.country]
					}
					this.region = res.areaAdd?res.areaAdd.split(','):[]
					this.address = res.address?res.address:''
					this.longitude = res.lng ? res.lng : null
					this.latitude = res.lat ? res.lat : null
					if(res.areaCodeList.length>0){
						this.isAllSee = false
						let areaCodeList = res.areaCodeList.map(item=>item.areaCode)
						this.industryList.map(item=>{
							item.children.map(it=>{
								if(areaCodeList.indexOf(it.value)>-1){
									it.isActive = true
								}else{
									it.isActive = false
								}
							})
							if(item.children.some(it=>it.isActive == true)){
								item.isActive = true
							}else{
								item.isActive = false
							}
						})
						this.getCheckNum()
					}else{
						this.isAllSee = true
					}
				})
			},
			next() {
				if (!this.pic) {
					return req.msg('请上传封面图')
				}
				if (this.fileList.length == 0) {
					return req.msg('请上传活动轮播图')
				}
				if (!this.title) {
					return req.msg('请填写活动名称')
				}
				if (!this.brief) {
					return req.msg('请填写活动简介')
				}
				if (!this.text) {
					return req.msg('请填写活动详情')
				}
				this.stepOne = false
				this.stepTwo = true
			},
			uploadImage(type, index) {
				let that = this;
				let count = 1
				if (type == 1) {
					count = 1
				} else if (type == 2) {
					if (index) {
						count = 1
					} else {
						count = 9 - that.fileList.length
					}
				}
				uni.chooseImage({
					count: count,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: function({
						tempFilePaths
					}) {
						uni.showLoading({
							title:'上传中'
						})
						var promise = Promise.all(
							tempFilePaths.map(tempFilePath => {
								return new Promise(function(resolve, reject) {
									req.uploadFile('/api/nocheck/upload', tempFilePath,
									res => {
										// type 1 封面图
										if (type == 1) {
											that.pic = res.src
										} else if (type == 2) {
											if (index) {
												that.fileList[index] = res.src
												that.fileList = JSON.parse(JSON
													.stringify(that.fileList))
											} else {
												that.fileList = that.fileList.concat(
													res.src)
											}
										}
										resolve()
									});
								});
							})
						);
						promise
							.then(function(results) {
								uni.hideLoading()
								console.log(results);
							})
							.catch(function(err) {
								uni.hideLoading()
								console.log(err);
							});
					}
				});
			},
			deleteImage(type, index) {
				if (type == 2)
					this.fileList.splice(index, 1)
			},
			enlistStartTimeChange(e) {
				if (this.enlistEndTime) {
					if (this.enlistEndTime < e.detail.value)
						return req.msg('报名开始时间不能大于结束时间')
				}
				this.enlistStartTime = e.detail.value
			},
			enlistEndTimeChange(e) {
				if (this.enlistStartTime) {
					if (this.enlistStartTime > e.detail.value)
						return req.msg('报名结束时间不能小于开始时间')
				}
				this.enlistEndTime = e.detail.value
			},
			startTimeChange(e) {
				if (this.endTime) {
					if (this.endTime < e.detail.value)
						return req.msg('活动开始时间不能大于结束时间')
				}
				this.startTime = e.detail.value
			},
			endTimeChange(e) {
				if (this.startTime) {
					if (this.startTime > e.detail.value)
						return req.msg('活动结束时间不能小于开始时间')
				}
				this.endTime = e.detail.value
			},
			chooseLocation() {
				var tha = this;
				uni.chooseLocation({
					success: function(res) {
						if (res.name) {
							tha.address = res.name;
							tha.reverseGeocoder(res);
							console.log('地址数据》》》：', res);
						}
					}
				});
			},
			reverseGeocoder(location) {
				// #ifdef H5
				location = location.latitude + ',' + location.longitude
				let url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=';
				this.$jsonp(url, {
					key: req.public.mapLBSKEY,
					location: location,
					output: 'jsonp'
				}).then(data => {
					console.log('解析后的地址地址数据：', data);
					data = data.result
					this.region = [data.ad_info.province, data.ad_info.city, data.ad_info.district]
					this.regionCode = [data.ad_info.adcode.substring(0, 2) + '0000', data.ad_info.adcode.substring(
						0, 4) + '00', data.ad_info.adcode]
					this.longitude = data.ad_info.location.lng
					this.latitude = data.ad_info.location.lat
				}).catch(err => {
					console.log(err);
				});
				// #endif
				// #ifndef H5
				QQMapWX.initMap();
				QQMapWX.reverseGeocoder(location, data => {
					console.log('解析后的地址地址数据：', data);

					this.region = [data.ad_info.province, data.ad_info.city, data.ad_info.district]
					this.regionCode = [data.ad_info.adcode.substring(0, 2) + '0000', data.ad_info.adcode.substring(
						0, 4) + '00', data.ad_info.adcode]
					this.longitude = data.ad_info.location.lng
					this.latitude = data.ad_info.location.lat
				});
				//#endif
			},
			bindRegionChange(event) {
				console.log(event)
				this.region = event.detail.value
				this.regionCode = event.detail.code
			},
			powerChange(e) {
				this.isAllSee = e.detail.value
			},
			showPop(){
				this.isShowPop = true;
			},
			hidePop(){
				this.isShowPop = false;
				this.getCheckNum()
			},
			submit() {
				if (!this.pic) {
					return req.msg('请上传封面图')
				}
				if (this.fileList.length == 0) {
					return req.msg('请上传活动轮播图')
				}
				if (!this.title) {
					return req.msg('请填写活动名称')
				}
				if (!this.brief) {
					return req.msg('请填写活动简介')
				}
				if (!this.text) {
					return req.msg('请填写活动详情')
				}
				if (!this.enlistStartTime) {
					return req.msg('请选择报名开始时间')
				}
				if (!this.enlistEndTime) {
					return req.msg('请选择报名结束时间')
				}
				if (!this.startTime) {
					return req.msg('请选择活动开始时间')
				}
				if (!this.endTime) {
					return req.msg('请选择活动结束时间')
				}
				// if (!this.house) {
				// 	return req.msg('请填写活动地址')
				// }
				// if (this.regionCode.length == 0) {
				// 	return req.msg('请选择活动所在城市')
				// }
				// if (!this.address) {
				// 	return req.msg('请填写详细地址')
				// }
				
				let areaCodeList = []
				if(!this.isAllSee){
					this.industryList.map(item=>{
						item.children.map(it=>{
							if(it.isActive){
								areaCodeList.push({
									areaCode:it.value
								})
							}
						})
					})
					if(areaCodeList.length==0){
						return req.msg('请选择活动生效区域')
					}
				}else{
					areaCodeList.push({
						areaCode:this.companyTreeList[0].value
					})
				}

				let dataP = {
					pic: this.pic,
					fileList: JSON.stringify(this.fileList.map(item => {
						return {
							url: item
						}
					})),
					title: this.title,
					brief: this.brief,
					text: this.text,
					personLimit: this.personLimit,
					enlistStartTime: this.enlistStartTime,
					enlistEndTime: this.enlistEndTime,
					startTime: this.startTime,
					endTime: this.endTime,
					house: this.house,
					province: this.regionCode[0],
					city: this.regionCode[1],
					country: this.regionCode[2],
					areaAdd: this.region.join(','),
					address: this.address,
					lng: this.longitude,
					lat: this.latitude,
					areaCodeList:areaCodeList
				}
				let prices = [{
					title: "VIP",
					marketMoney: 0,
					money: 0,
					vipMoney: 0,
					vipModels: [],
					personCount: 1,
					isDefault: 0
				}]
				dataP.prices = prices
				dataP.extForm = this.extForm?this.extForm:null
				let url = '/api/match/save'
				if (this.id) {
					dataP.id = this.id
					url = '/api/match/update'
					uni.showModal({
						title: '提示',
						content: '修改活动将重新审核，确定修改？',
						success: (res) => {
							if (res.confirm) {
								req.postRequest(url, dataP, res => {
									req.msg('创建成功')
									let pages = getCurrentPages();
									var prevPage = pages[pages.length - 2];
									if (prevPage) {
										prevPage.$vm.isLoad = true
										prevPage.$vm.form.page = 1
										prevPage.$vm.getPageList()
									}
									setTimeout(() => {
										uni.navigateBack()
									}, 1000)
								})
							}
						}
					})
				} else {
					req.postRequest(url, dataP, res => {
						req.msg('创建成功')
						let pages = getCurrentPages();
						var prevPage = pages[pages.length - 2];
						if (prevPage) {
							prevPage.$vm.isLoad = true
							prevPage.$vm.form.page = 1
							prevPage.$vm.getPageList()
						}
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
				}
			},
			formatTime(date) {
				date = new Date(date.replace(/-/g, '/'))
				return util.formatTime(date).t3
			},
			
			jian(){
				if(this.personLimit>0) this.personLimit = this.personLimit-1
				if(this.personLimit==0) this.personLimit = -1
			},
			jia(){
				if(this.personLimit==-1) this.personLimit = 1
				else this.personLimit = this.personLimit+1
			}
		},
		mounted() {

		}
	}
</script>

<style>
	@import "./activityEdit.css";
</style>