<template>
	<view>
		<!-- 顶部操作条 -->
		<cu-custom :bgColor="'bg-main-color'" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{mode === 1 ? '新增' : '编辑'}}店铺</block>
		</cu-custom>
		<!-- 地址信息form -->
		<view class="bg-white margin-top-sm">
			<form @submit="submit">
				<view style="padding: 0 30rpx;">
					<view  class="padding-tb-sm flex justify-between align-center">
						<text>店铺门头</text>
						<text style="font-size: 20rpx;">1张门头照+3张店内照 (至少1张，门头照排前)</text>
					</view>
					<view>
						<div class="grid col-3 grid-square">
							<view class="bg-img" v-for="(item,index) in imgList" :key="index"
								@tap="viewImage($event, imgList)" :data-url="item">
								<image :src="item" mode="aspectFill"></image>
								<view class="cu-tag bg-red" @tap.stop="delImg($event, imgList)" :data-index="index">
									<text class='cuIcon-close'></text>
								</view>
							</view>
							<view class="solids" @tap="chooseImage" v-if="imgList.length < 6">
								<text class='cuIcon-cameraadd'></text>
							</view>
						</div>
						
					</view>
				</view>
				<!-- #ifndef H5 || APP-PLUS || MP-ALIPAY -->
				<view class="cu-form-group">
					<view class="title">联系地址</view>
					<picker :mode="'multiSelector'" @change="regionChange" @columnchange="regionColChange" :value="multiIndex" :range-key="'areaName'" :range="areaList">
						<view class="picker">
							{{formData.area && formData.area.length ? formData.area[0].areaName + '-' + formData.area[1].areaName + '-' + formData.area[2].areaName + '-' + formData.area[3].areaName : '请选择'}}
						</view>
					</picker>
				</view>
				<!-- #endif -->
				<view class="cu-form-group">
					<view class="title">详细地址</view>
					<input name="address" v-model="formData.address"></input>
					<view class="text-blue" @click="getLocation">定位上传</view>
				</view>
				<view class="cu-form-group">
					<view class="title">门店名称</view>
					<input name="shopName" v-model="formData.shopName"></input>
				</view>
				<view class="cu-form-group">
					<view class="title">门店电话</view>
					<input name="phone" v-model="formData.phone" placeholder="请输入门店客户接待电话"></input>
				</view>
				<!-- 底部操作栏 -->
				<view class="cu-bar tabbar border shop fixed-bottom-bar">
					<button class="cu-btn bg-main-color long-btn margin-lr-sm shadow-blur" form-type="submit">保存</button>
				</view>
			</form>
		</view>
		
		
		<!-- <view class="cu-modal" :class="isLocationShow?'show':''">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white justify-end solid-bottom">
					<view class="content">提示</view>
					<view class="action" @click="isLocationShow = false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left bg-white">
					<view>
						点击确定定位，会按你当前位置上传。（添加店铺本次定位上传时，请在店铺内操作）！
					</view>
				</view>
				<view class="cu-bar bg-white solid-top">
					<view class="action margin-0 flex-sub text-black" @tap="isLocationShow = false">关闭</view>
					<view class="action margin-0 flex-sub text-main-color solid-left"
						@click="getLocation">确定定位</view>
				</view>
			</view>
		</view> -->
		
		<!-- 前往授权设置 -->
		<!-- <view class="cu-modal" :class="isShowPrivSetting?'show':''">
			<view class="cu-dialog">
				<view class="padding-xl text-left">
					<view>需先授权定位功能才可正常使用功能</view>
				</view>
				<view class="cu-bar bg-white">
					<navigator class="modal-bottom-oper margin-0 flex-sub text-black" open-type="exit"
						target="miniProgram">拒绝授权
					</navigator>
					<button class="cu-btn modal-bottom-oper margin-0 flex-sub text-main-color bg-white solid-left"
						open-type="openSetting" @opensetting="authLocationCallback">前往授权</button>
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				areaList: [],
				multiIndex: [0, 0, 0],
				formData: {
				},
				mode: 1, // 1为新增，0为修改
				imgList: [],
				isLocationShow: false,
				isShowPrivSetting: false
			}
		},
		onLoad(options) {
			let params = JSON.parse(decodeURIComponent(options.params));
			this.mode = params ? params.mode : this.mode;
			console.log(this.mode)
			if (this.mode === 0) {
				// 修改
				this.fillForm(params.addressInfo);
			} else {
				this.formData = {
					area: [],
					shopName: '',
					address: '',
					phone: '',
					provinceId: '',
					provinceName: '',
					cityId: '',
					cityName: '',
					countryId: '',
					countryName: '',
					streetId: '',
					streetName: '',
					longitude: '',
					latitude: ''
				}
			}
			this.loadData();
		},
		methods: {
			chooseImage(e) {
				uni.chooseMedia({
					count: 1, //默认9
					mediaType: ['image'],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						uni.showLoading({
							title: '上传中',
							mask: true
						});
						res.tempFiles.forEach((fileObj, index) => {
							this.$request.uploadFile(fileObj.tempFilePath).then((url) => {
								this.imgList.push(url);
								if (index === res.tempFiles.length - 1) {
									uni.hideLoading();
								}
							});
						});
					}
				});
			},
			viewImage(e, imgList) {
				uni.previewImage({
					urls: imgList,
					current: e.currentTarget.dataset.url
				});
			},
			delImg(e, imgList) {
				uni.showModal({
					title: '',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			async loadData() {
				// this.areaList = await this.$api.data('areaList');
				this.loadAreaList();
			},
			fillForm(addressInfo) {
				this.formData = addressInfo && Object.keys(addressInfo).length > 0 ? addressInfo : this.formData;
				this.imgList = addressInfo.imageUrl ? addressInfo.imageUrl.split(',') : []
			},
			// async authLocationCallback(res) {
			// 	if (res.detail.authSetting['scope.userLocation']) {
			// 		this.isShowPrivSetting = false;
			// 		this.getLocation();
			// 	}
			// },
			async getLocation() {
				// let res = await wx.getSetting();
				// console.log(res);
				// if (res && !res.authSetting['scope.userLocation']) {
				// 	wx.authorize({
				// 		scope: 'scope.userLocation',
				// 		success: () => {
				// 		  this.getLocation()
				// 		},
				// 		fail: () => {
				// 		  this.isShowPrivSetting = true;
				// 		}
				// 	  });
				// 	return;
				// }
				// const res = await this.$request.GetCurrentLocation()
				wx.chooseLocation({
				    success: async (res1) => {
				      const res = await this.$request.TransformLocation(res1)
					  console.log(res);
					  this.formData.area = [res.provinceArea, res.cityArea, res.countryArea, res.streetArea]
					  this.formData.provinceId = res.provinceArea.areaId;
					  this.formData.provinceName = res.provinceArea.areaName;
					  this.formData.cityId = res.cityArea.areaId;
					  this.formData.cityName = res.cityArea.areaName;
					  this.formData.countryId = res.countryArea.areaId;
					  this.formData.countryName = res.countryArea.areaName;
					  this.formData.streetId = res.streetArea.areaId;
					  this.formData.streetName = res.streetArea.areaName;
					  this.formData.latitude = res.latitude;
					  this.formData.longitude = res.longitude;
					  this.isLocationShow = false
				    },
				    fail: (err) => {
				      console.error('选择位置失败', err);
					 //  uni.showModal({
					 //  	title: '提示',
					 //  	content: '定位获取失败，请确认是否开启定位',
					 //  	cancelText: '取消',
					 //  	confirmText: '重试',
					 //  	success: res => {
					 //  		if (res.confirm) {
					 //  			this.getLocation();
					 //  		}
						// }
					 //  })
				    }
				});
			},
			async loadAreaList(idArr) {
				let areaList = await this.$request.areaListByStep();
				areaList = areaList.data;
				let col1Code = idArr ? idArr[0] : areaList[0].areaCode;
				let subAreaList = await this.$request.areaListByStep({ parentCode: col1Code });
				subAreaList = subAreaList.data;
				let col2Code = idArr ? idArr[1] : subAreaList[0].areaCode;
				let subSubAreaList = await this.$request.areaListByStep({ parentCode: col2Code });
				subSubAreaList = subSubAreaList.data;
				let col3Code = idArr ? idArr[2] : subSubAreaList[0].areaCode;
				let subSub2AreaList = await this.$request.areaListByStep({ parentCode: col3Code });
				subSub2AreaList = subSub2AreaList.data;
				this.areaList.push(areaList);
				this.areaList.push(subAreaList);
				this.areaList.push(subSubAreaList);
				this.areaList.push(subSub2AreaList);
			},
			regionChange(e) {
				this.multiIndex = e.detail.value;
				let chosenArea = [];
				for(let i = 0; i < this.areaList.length; i++) {
					chosenArea.push(this.areaList[i][this.multiIndex[i]]);
				}
				this.formData.area = chosenArea;
				this.formData.provinceId = chosenArea[0].areaId;
				this.formData.provinceName = chosenArea[0].areaName;
				this.formData.cityId = chosenArea[1].areaId;
				this.formData.cityName = chosenArea[1].areaName;
				this.formData.countryId = chosenArea[2].areaId;
				this.formData.countryName = chosenArea[2].areaName;
				this.formData.streetId = chosenArea[3].areaId;
				this.formData.streetName = chosenArea[3].areaName;
			},
			async regionColChange(e) {
				let colObj = e.detail;
				if (colObj.column == 0) {
					let subSubAreaList = [], subSub2AreaList = [];
					// 通过一级查询二级，通过二级查三级
					let subAreaList = await this.$request.areaListByStep({parentCode: this.areaList[0][colObj.value].areaCode});
					subAreaList = subAreaList.data;
					if (subAreaList && subAreaList.length) {
						subSubAreaList = await this.$request.areaListByStep({parentCode: subAreaList[0].areaCode});
						subSubAreaList = subSubAreaList.data;
						if(subSubAreaList && subSubAreaList.length) {
							subSub2AreaList = await this.$request.areaListByStep({parentCode: subSubAreaList[0].areaCode});
							subSub2AreaList = subSub2AreaList.data;
						}
					}
					this.areaList[1] = subAreaList
					this.areaList[2] = subSubAreaList
					this.areaList[3] = subSub2AreaList
					this.multiIndex = [colObj.value, 0, 0, 0];
				} else if (colObj.column == 1) {
					let subSub2AreaList = []
					// 通过二级查三级
					let subSubAreaList = await this.$request.areaListByStep({parentCode: this.areaList[1][colObj.value].areaCode});
					subSubAreaList = subSubAreaList.data;
					if (subSubAreaList && subSubAreaList.length) {
						subSub2AreaList = await this.$request.areaListByStep({parentCode: subSubAreaList[0].areaCode});
						subSub2AreaList = subSub2AreaList.data;
					}
					this.areaList[2] = subSubAreaList
					this.areaList[3] = subSub2AreaList
					this.multiIndex = [this.multiIndex[0], colObj.value, 0, 0];
				} else if (colObj.column == 2) {
					// 通过二级查三级
					let subSubAreaList = await this.$request.areaListByStep({parentCode: this.areaList[2][colObj.value].areaCode});
					subSubAreaList = subSubAreaList.data;
					this.areaList[3] = subSubAreaList;
					this.multiIndex = [this.multiIndex[0], this.multiIndex[1], colObj.value, 0];
				}
			},
			validateForm(addressInfo) {
				console.log(addressInfo);
				if(this.imgList.length === 0) {
					uni.showToast({
						title: '请至少上传一张门头图',
						icon: 'none',
						mask: true
					})
					return false
				}
				if(!addressInfo.latitude || !addressInfo.longitude) {
					uni.showToast({
						title: '请先点击定位上传',
						icon: 'none',
						mask: true
					})
					return false
				}
				
				if(!addressInfo.area || addressInfo.area.length === 0) {
					uni.showToast({
						title: '请选择联系地址',
						icon: 'none',
						mask: true
					})
					return false
				}
				
				if (!addressInfo.address) {
					uni.showToast({
						title: '请填写详细地址',
						icon: 'none',
						mask: true
					})
					return false
				}
				if (!addressInfo.shopName) {
					uni.showToast({
						title: '请输入门店名称',
						icon: 'none',
						mask: true
					})
					return false
				}
				if (!this.$validate.validContactNum(addressInfo.phone)) {
					uni.showToast({
						title: '联系号码格式错误',
						icon: 'none',
						mask: true
					})
					return false
				}
				return true;
			},
			async submit(e) {
				const confirmFormData = {...this.formData}
				console.log(confirmFormData);
				let formValid = this.validateForm(confirmFormData);
				if (formValid) {
					let isSuccess = false;
					if (this.mode === 1) {
						let res = await this.$request.addShopAddressList({
							...this.formData,
							imageUrl: this.imgList.toString(),
							workerId: this.$request.getCurUserInfo().workerId
						});
						if (res.code === 0) {
							isSuccess = true;
						}
					} else if (this.mode === 0) {
						let res = await this.$request.editShopAddressList({
							...this.formData,
							imageUrl: this.imgList.toString(),
							workerId: this.$request.getCurUserInfo().workerId,
						});
						if (res.code === 0) {
							isSuccess = true;
						}
					}
					if (isSuccess) {
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							mask: true
						})
						uni.navigateBack()
					} else {
						uni.showToast({
							title: '保存失败',
							icon: 'error',
							mask: true
						})
					}
				}
			}
		}
	}
</script>

<style>
</style>
