<template>
	<view class="form">
		<u-form :model="form" ref="uForm">
			<view class="upload">
				<view style="padding-left: 20rpx;margin-top: 20rpx;">
					<u-upload :fileList="fileList1" :auto-upload="false" @afterRead="afterRead" @delete="deletePic" name="1"
						multiple :maxCount="5"></u-upload>
				</view>
				<!-- <u-upload max-count="5" upload-icon="photo"></u-upload> -->
				<text class="count">发布房源图片({{imageLength}}/5)</text>
			</view>
			<u-form-item label="标题" label-position="top" border-bottom="true" prop="title" label-width="auto">
				<u-input v-model="form.title" placeholder="请输入标题以便吸引人的注意哦" placeholder-class="input-class"
					border="none"></u-input>
			</u-form-item>
			<u-form-item label="区域" label-position="top" border-bottom="true" right-icon="arrow-right" prop="region"
				label-width="auto">
				<text @click="show1 = true" class="checkedtext" v-if="form.region">{{form.region}}</text>
				<text @click="show1 = true" class="checktext" v-else>请选择所属区域</text>
				<view class="arrow-icon">
					<u-icon name="arrow-right" size="30px" @click="show1 = true"></u-icon>
				</view>
				<u-picker :columns="[regionColumns]" ref="regionPicker" :show="show1" :closeOnClickOverlay="true"
					@close="show1 = false" v-model="form.region" @confirm="regionConfirm"
					@change="changeRegionHandler"></u-picker>
			</u-form-item>
			<u-form-item label="地址" label-position="top" border-bottom="true" prop="address" label-width="auto">
				<u-input v-model="form.address" placeholder="请输入店铺地址" placeholder-class="input-class" border="none"
					@focus="changeAddressFocus" @blur="changeAddress"></u-input>
			</u-form-item>
			<u-form-item label="行业" label-position="top" border-bottom="true" class="picker" label-width="auto"
				prop="business">
				<text @click="show2 = true" class="checkedtext"
					v-if="form.business">{{form.business}}-{{form.commercial}}</text>
				<text @click="show2 = true" class="checktext" v-else>请选择店铺行业与业态</text>
				<view class="arrow-icon">
					<u-icon name="arrow-right" size="30px" @click="show2 = true"></u-icon>
				</view>
				<u-picker mode="region" :show="show2" :closeOnClickOverlay="true" @close="show2 = false" ref="uPicker"
					:columns="[Classcolumns]" v-model="form.business" @confirm="tradeConfirm" @change="changeHandler"></u-picker>
			</u-form-item>
			<u-form-item label="面积" label-position="top" border-bottom="true" label-width="auto" prop="area">
				<u-input v-model="form.area" placeholder="请输入店铺面积" placeholder-class="input-class" border="none"
					type="number"></u-input>
			</u-form-item>
			<u-form-item label="租金（元/月）" label-position="top" border-bottom="true" label-width="auto" prop="rent">
				<u-input v-model="form.rent" placeholder="请输入店铺租金" placeholder-class="input-class" border="none"
					type="number"></u-input>
			</u-form-item>
			<u-form-item label="转让费（万元）" label-position="top" border-bottom="true" label-width="auto" prop="transferFee">
				<u-input v-model="form.transferFee" placeholder="请输入店铺转让费" placeholder-class="input-class" type="number"
					border="none"></u-input>
			</u-form-item>
			<u-form-item label="联系人" label-position="top" border-bottom="true" label-width="auto" prop="contact">
				<u-input v-model="form.contact" placeholder="请输入联系人姓名" placeholder-class="input-class" border="none"></u-input>
			</u-form-item>
			<u-form-item label="手机号码" label-position="top" border-bottom="true" label-width="auto" prop="mobile">
				<u-input v-model="form.mobile" placeholder="请输入联系人手机号码" placeholder-class="input-class" border="none"
					type="number"></u-input>
			</u-form-item>
			<u-form-item label="详情介绍" label-position="top" border-bottom="true" label-width="auto" prop="content">
				<u-input v-model="form.content" placeholder="请输入介绍详情" placeholder-class="input-class" border="none"></u-input>
			</u-form-item>
		</u-form>
		<view class="bug-figure"></view>
		<u-button @click="submit" color="linear-gradient(to right, #E86262, #CC3333)" :size="normal" shape="circle"
			class="submit-btn">发布</u-button>
		<view class="bug-figure"></view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				imageLength: 0,
				fileList1: [],
				regionColumns: [],
				regionSecondColumns: [],
				regionId: [],
				regionCheckId: '',
				form: {
					title: '',
					region: '',
					address: '',
					business: '',
					commercial: '',
					area: '',
					rent: '',
					transferFee: '',
					mobile: '',
					content: '',
					images: [],
					longitude: '',
					latitude: '',
					id: '',

				},
				Classcolumns: [],
				ClassCheckId: '',
				Karmacolumns: [],
				pid: [],
				show1: false,
				show2: false,
				show3: false,
				rules: {
					'title': [{
						required: true,
						message: '请输入标题',
						trigger: ['change', 'blur']
					}],
					'business': [{
						required: true,
						message: '请选择行业',
						trigger: ['change']
					}],
					'region': [{
						required: true,
						message: '请选择地区',
						trigger: ['change']
					}],
					'commercial': [{
						required: true,
						message: '请选择业态',
						trigger: ['change']
					}],
					'contact': [{
						required: true,
						message: '请输入姓名',
						trigger: ['change', 'blur']
					}],
					'transferFee': [{
						required: true,
						message: '请输入转让金',
						trigger: ['change', 'blur']
					}],
					'content': [{
						required: true,
						message: '请输入介绍',
						trigger: ['change', 'blur']
					}],
					'area': [{
						required: true,
						message: '请输入面积',
						trigger: ['change', 'blur']
					}],
					'rent': [{
						required: true,
						message: '请输入租金',
						trigger: ['change', 'blur']
					}],
					'address': [{
						required: true,
						message: '请输入地址',
						trigger: ['change', 'blur']
					}],
					'mobile': [{
							required: true,
							message: '请输入电话号码',
						},
						{
							validator: (rule, value, callback) => {
								if (value) {
									return this.$u.test.mobile(value);
								} else {
									return true
								}
							},
							message: '号码不正确',
							trigger: ['change', 'blur'],
						}
					]

				},
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			preview(e) {
				// console.log('预览', e);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
					this.imageLength = fileListLen
				}
			},
			uploadFilePromise(filePath) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync('loginToken')
					const a = uni.uploadFile({
						url: this.$api.uploadImgUrl,
						filePath: filePath,
						name: 'file',
						header: {
							"Content-Type": "multipart/form-data",
							'Authorization': token
						},
						success: (res) => {
							resolve(JSON.parse(res.data).data.url)
						}
					});
				})
			},
			handleSearchAddress() {
				uni.navigateTo({
					url: '/pages/publish/chooseAddress/chooseAddress'
				})
			},
			submit() {
				this.$refs.uForm.validate().then(res => {
					const temp = []
					if (this.fileList1.length > 0) {
						this.fileList1.map(item => {
							const url = item.url
							// console.log('url', url, this.$api.imgUrl);
							temp.push(url.replace(this.$api.imgUrl, ''))

						})
					}
					// console.log('images---', temp.join(','));
					if (this.form.latitude && this.form.longitude) {
						console.log('经纬度都存在');
					} else {
						uni.$u.toast('请输入准确地址')
						return false
					}

					let data = {
						...this.form,
						address: this.form.region.split('-')[1] + this.form.address,
						region: this.form.region.split('-')[0],
						images: temp.join(',')
					}
					// console.log('提交表单信息', data);
					this.$api.publishTransfer(data).then(res => {
						// console.log('发布店铺转让', res);
						if (res.data.code == 1) {
							uni.$u.toast(res.data.msg)
							uni.reLaunch({
								url: '/pages/my/my'
							})
						} else {
							uni.$u.toast(res.data.msg)
						}
					})
				}).catch(errors => {
					console.log("失败信息:" + JSON.stringify(errors))
					// uni.$u.toast('校验失败')
				})
			},
			chooseCommercial() {
				if (!this.form.business) {
					uni.$u.toast('请先选择行业')
					return false
				} else {
					this.show3 = true
				}
			},
			changeAddressFocus() {
				if (!this.form.region) {
					uni.$u.toast('请先选择区域')
					return false
				}
			},
			changeAddress(e) {
				// console.log('changeAddress', e);
				this.getAddressList(e)
			},
			changeRegionHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.regionPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					this.regionCheckId = this.regionId[index]
					const that = this
					uni.request({
						url: 'https://apis.map.qq.com/ws/district/v1/getchildren?id=' + that.regionCheckId + '&key=' +
							that.$api.key,
						success(res) {
							that.regionSecondColumns = res.data.result[0].map(item => item.fullname)
							picker.setColumnValues(1, that.regionSecondColumns)
						},
						fail(err) {
							console.log('请求区域失败：', err);
						}
					})
				}
			},
			getRegionList() {
				var that = this
				uni.request({
					url: 'https://apis.map.qq.com/ws/district/v1/getchildren?id=' + uni.getStorageSync('city_code') + '&key=' +
						that.$api.key,
					success(res) {
						that.regionColumns = res.data.result[0].map(item => item.fullname)
						that.regionId = res.data.result[0].map(item => item.id)
						var that1 = that
						uni.request({
							url: 'https://apis.map.qq.com/ws/district/v1/getchildren?id=' + that1.regionId[0] + '&key=' +
								that1.$api.key,
							success(res) {
								that1.regionSecondColumns = res.data.result[0].map(item => item.fullname)
								that1.$refs.regionPicker.setColumnValues(1, that1.regionSecondColumns)
							},
							fail(err) {
								console.log('请求区域失败：', err);
							}
						})
					},
					fail(err) {
						console.log('请求区域失败：', err);
					}
				})
			},
			getAddressList(value) {
				if (!this.form.region) {
					uni.$u.toast('请先选择区域')
					return false
				}

				var that = this
				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?address=' + that.form.region + value + '&key=' +
						that.$api.key,
					success(res) {
						// console.log('地址转经纬度', that.form.region, res.data);
						if (res.data.message == "query ok") {
							// console.log('lat', res.data.result.location.lat);
							that.form.latitude = res.data.result.location.lat
							// console.log('lng', res.data.result.location.lng);
							that.form.longitude = res.data.result.location.lng
						} else {
							uni.$u.toast('请输入准确地址')
						}
					},
					fail(err) {
						console.log('请求区域失败：', err);
					}
				})
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				// console.log(e);
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					this.ClassCheckId = this.pid[index]
					this.$api.getClassList(this.ClassCheckId).then(res => {
						// console.log(res);
						this.Karmacolumns = res.data.data.map((item) => {
							return item = item.name
						})
						picker.setColumnValues(1, this.Karmacolumns)
					})

				}
			},
			tradeConfirm(e) {
				this.show2 = false
				this.form.business = e.value[0]
				this.form.commercial = e.value[1]
			},
			karmaConfirm(e) {
				this.show3 = false
			},
			regionConfirm(e) {
				this.show1 = false
				this.form.region = e.value[0] + '-' + e.value[1]
			},
			getDetail(type, id) {
				// console.log('type, id', type, id);
				this.$api.getShopDetail(type, id).then(res => {
					// console.log(',re', res);
					const data = res.data.data
					if (res.data.code == 1) {
						this.form = {
							title: data.tt,
							region: data.area1,
							address: data.adress,
							business: data.trade1,
							commercial: data.trade2,
							area: data.mianji,
							rent: data.zujin,
							transferFee: data.zhuanrangfei,
							mobile: data.mobile,
							content: data.content,
							// images: data.pics,
							id: id,
							contact: data.lianxiren,
							longitude: data.lng,
							latitude: data.lat,
						}
						var arr = [];
						var arr1 = [];
						let obj = {}
						arr = data.pics.split(",")
						arr.map(item => {
							obj = this.$api.imgUrl + item
							arr1.push(obj)
						})
						data.pics = arr1
						this.fileList1 = data.pics.map(item => {
							return {
								url: item
							}
						})
					}
				})
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad(options) {
			// console.log('修改转让', options);
			if (options.item) {
				console.log('修改');
				if (options.id) {
					this.getDetail(1, options.id)
				}
			} else {
				console.log('发布');
			}
			this.getRegionList()
			this.$api.getClassList().then(res => {
				// console.log(res.data.data.length);
				this.Classcolumns = res.data.data.map((item) => {
					return item = item.name
				})
				this.pid = res.data.data.map((item) => {
					return item = item.id
				})
				this.$api.getClassList(9).then(res => {
					this.Karmacolumns = res.data.data.map((item) => {
						return item = item.name
					})
					this.$refs.uPicker.setColumnValues(1, this.Karmacolumns)
				})
			})
		},
		computed: {
			isChecked(index) {
				if (index.length > 0)
					return true;
				else
					return false;
			}
		}
	}
</script>
<style lang="scss">
	.count {}

	.form {
		margin-left: 20px;
		margin-right: 20px;
	}

	.input-class {
		font-size: 30rpx;
		font-weight: 1px;
		border-style: none;

	}

	.upload {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #F8F8F8;

		// height: 300rpx;
		// margin-right: 20px;
		.count {
			margin-bottom: 30px;
		}
	}

	.submit-btn {
		width: 80%;
	}

	.bug-figure {
		height: 100rpx;
	}

	.checkbox1 {
		display: flex;
		justify-content: space-between;
	}

	.checktext {
		margin-top: 5rpx;
		font-size: 30rpx;
		font-weight: 1px;
		color: #c1c4c7;
	}

	.checkedtext {
		margin-top: 5rpx;
		font-size: 28rpx;
		font-weight: 1px;
		border-style: none;
	}

	.picker {
		display: flex;
		justify-content: space-between;
	}

	.arrow-icon {
		position: absolute;
		right: 10rpx;
		transform: translateY(-20rpx);
	}
</style>