<template>
	<view>
		<block v-if="config.Many_Store == 1">
		<!--pages/nearby/nearby.wxml-->
		<view class="ssbox bgfff dflex">
			<view class="search dflex">
				<view class="section" v-if="layerModel!=1">
					<picker mode="region" @change="bindRegionChange" :value="region" :custom-item="customItem">
						<view class="picker dflex">
							<!-- {{region[2]?region[2]:''}} -->
							{{regions}}
							<image src="/static/pages/images/bico.png"></image>
						</view>
					</picker>
					<!-- <template>
						<view class="container">
							<uni-data-picker placeholder="请选择班级" popup-title="请选择所在地区" :localdata="dataTree"
								v-model="classes" @change="onchange" @nodeclick="onnodeclick"
								@popupopened="onpopupopened" @popupclosed="onpopupclosed">
							</uni-data-picker>
						</view>
					</template> -->
				</view>
				<image src="/static/pages/images/ssico.png"></image>
				<input placeholder="搜索您想要找的网点" class="flex" :value="searchTitle" @input="search" @confirm="confirm"
					confirm-type="search"></input>
				<image src="/static/pages/images/clear.png" @tap="clearInput" v-if="searchTitle!=''"></image>
			</view>
			<view class="sousuo" @tap="confirmSearch">搜索</view>
		</view>
		<!-- <map id="myMap" class="map" latitude="{{point.latitude}}" longitude="{{point.longitude}}" markers="{{markers}}" show-location></map> -->
		<view class="tit">当前地址</view>
		<view class="pdlr20">
			<view class="location bgfff dflex r10">
				<view class="title">{{address}}</view>
				<view class="loca dflex" @tap="initLocation" v-if="layerModel!=1">
					<image src="/static/pages/images/wzico.png"></image>获取定位
				</view>
				<block v-if="layerModel==1">
					<view class="dflex dwsb">
						<view class="shibai">!</view><text>定位失败</text>
					</view>
				</block>
			</view>
		</view>
		</block>
		<view class="tit">附近网点</view>
		<view class="list pdlr20">
			<block v-for="(item, index) in pageList" :key="index">
				<view class="li r10">
					<image src="/static/pages/images/dangqian.png" class="dangqian" v-if="merchant.id==item.id"></image>
					<view class="cont" @tap="chooseMerchant(item.id,index)" :data-index="index">
						<view class="dizhi dflex">
							<view class="ddflex name flex" :style="'color:' + (item.isChoose ? '#999' : '#333')">
								<image
									:src="item.type==1?'/static/pages/images/store.png':'/static/pages/images/self.png'">
								</image>{{item.title}}
							</view>
							<view class="d-type" v-if="item.type != 4">{{item.type == 1 ? '归属门店' : item.type == 2 ? '上次下单' : item.type == 3 ? '总店' : item.type == 5 ? '小店' : ''}}</view>
						</view>
						<view class="ddflex">
							<view class="dizhi fflex">
								<view class="time dflex" v-if="item.businessTime">
									<image src="/static/pages/images/nearbytime.png"></image>
									<text>{{item.businessTime}}</text>
								</view>
								<view class="weizhi dflex">
									<image src="/static/pages/images/dwico1.png"></image><text>{{item.address}}</text>
								</view>
							</view>
							<view class="yue" v-if="item.range > 0">
								<image src="/static/pages/images/position_a_icon.png"></image>
								<text
									v-if="item.range!=50000">{{item.range > 1 ? item.range +'km' : item.mDistance+'m'}}</text>
							</view>
						</view>
					</view>
					<view class="bottom dflex">
						<view class="bottom_left dflex">
							<image src="/static/pages/images/nearby_icon.png" class="mr20" @tap="goNavigation"
								:data-index="index"></image>
							<image src="/static/pages/images/nearby_icon1.png" @tap="makePhoneCall" :data-index="index">
							</image>
						</view>
						<view class="dflex bottom_right" @tap="tonearbyDet" :data-index="index">查看详情<image
								src="/static/pages/images/nearby_icon_left.png"></image>
						</view>
					</view>
				</view>
			</block>
			<block>
				<view class="nodata" v-if="pageList.length < 1">
					<image :src="picUrlss+'empty_dd.png'"></image>
					<text>该地区暂无网点</text>
				</view>
			</block>
			<view class="mask" @tap="closeLayer" :hidden="isShow" v-if="!isChoose"></view>
			<view class="kjpop" :hidden="isShow" v-if="!isChoose">
				<view class="top">
					<image src="/static/pages/images/mengdianxuanze.png"></image>
				</view>
				<view class="cont">
					<text>已切换至：</text>
					<view class="title">{{title}}</view>
					<view class="btn" @tap="closeLayer">我知道了</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	const req = require("../../utils/request.js");
	var QQMapWX = require("../../utils/qqmap.js");
	const api = require("../../utils/api.js");
	// import uniDataPicker from "../../uni_modules/uni-data-picker/components/uni-data-picker/uni-data-picker";
	export default {
		data() {
			return {
				picUrlss: req.public.picUrls,
				form: {
					page: 1,
					limit: 10,
					province: '',
					city: '',
					country: '',
				},
				pageList: [],
				isLoad: true,
				address: '',
				point: {},
				region: [],
				regions: '',
				searchTitle: '',
				history: [],
				isShow: true,
				addressIshow: false,
				isChoose: false,
				type: "",
				layerModel: "",
				location: "",
				merchant: "",
				merchantId: "",
				freshen: false,
				title: "",
				customItem: '全部',
				config: {}
			};
		},

		components: {
			// uniDataPicker
		},
		props: {},
		onLoad: function(options) {
			// 实例化API核心类
			QQMapWX.initMap();
			// console.log(options);
			let _ts = this;
			this.query = options;
			if (options.isChoose) {
				this.setData({
					isChoose: true
				});
			}
			if (options.type) {
				this.setData({
					type: options.type
				});
			}
			this.getstore();
		},
		onReachBottom() {
			this.form.page++;
			this.getList();
		},
		onShow: function() {
			let _ts = this;
			let config = JSON.parse(req.getStorage('configRes'))
			this.config = config
			if(config.Many_Store == 1){
				this.initLocation(() => {
					if (_ts.point) {
						_ts.form.lat = _ts.point.latitude;
						_ts.form.lng = _ts.point.longitude;
						// _ts.form.regionCode = _ts.point.regionCode;
						
						// console.log(_ts.point, _ts.point.latitude, _ts.point.regionCode);
						_ts.getList();
					} else {
						_ts.getList();
					}
				}); // this.showMap()
			}else{
				_ts.getList();
			}
			let history = req.getStorage('HISTORYS');
			this.setData({
				history: history
			});
		},
		methods: {
			async initLocation(success) {
				let _ts = this;

				await req.getLocation(res => {
					// console.log(res);

					if (res == 1) {
						_ts.setData({
							layerModel: res
						});

						uni.showModal({
							title: '温馨提示',
							content: '获取定位失败，请前往设置打开定位权限',
							showCancel: false,
							success(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
									uni.openSetting({
										success(res) {
											// console.log(res
											// 	.authSetting); // res.authSetting = {
										}

									});
								}
							}

						});
					} else {
						_ts.setData({
							layerModel: 0
						});
					}

					QQMapWX.reverseGeocoder(res, data => {
						console.log('QQMapWX==' + JSON.stringify(data));

						if (data) {
							res.regionCode = data.ad_info.adcode;

							_ts.setData({
								address: data.address,
								'region[0]': data.address_component.province,
								'region[1]': data.address_component.city,
								'region[2]': data.address_component.district,
								regions: data.address_component.district,
								location: data.location
							});

							_ts.setData({
								point: res
							});

							if (success && typeof success === 'function') {
								success.call(this);
							}
						} else {
							_ts.setData({
								layerModel: 1
							});

							_ts.confirmSearch();
						}
					});
				});
			},
			/**
			 * @param {Object} regionCode
			 */
			getList() {
				// console.log("执行", this.isLoad);
				if (!this.isLoad) return false;
				this.isLoad = false;
				let that = this;
				if(!that.form.province){
					delete that.form.province
				}
				if(!that.form.city){
					delete that.form.city
				}
				if(!that.form.country){
					delete that.form.country
				}
				// if (regionCode != undefined) {
				// 	this.form.regionCode = regionCode;
				// 	this.form.page = 1;
				// }

				this.form.isBusiness = 1; // this.data.form.regionCode=this.data.regionCode

				req.getRequest('/api/merchant/listV2', this.form, data => {
					if (data && data.length >= 10) this.isLoad = true;
					// console.log("执行", this.isLoad);
					let res;
					console.log('门店列表==',data)
					res = data.map(it => {
						it.isChoose = false;
						if (it.range > 0) it.range = parseFloat(it.range).toFixed(2), it.mDistance =
							parseFloat(it.mDistance).toFixed(0);
						if (this.isChoose && it.isGoods == 0 && JSON.parse(req.getStorage('configRes'))
							.Is_Store_Price_Stock == 0) it.isChoose = true;
						return it;
					});
					res = data.filter(it => it.isGoods != 0);
					console.log('门店列表1==',res)
					if (that.form.page > 1) {
						res = that.pageList.concat(data);
					} // if(!this.query.Timely_delivery_open){
					// }else{
					//   res=res.filter(it=>it.isDefault!=1)
					// }
					// if(JSON.parse(req.getStorage('configRes')).Is_Store_Price_Stock==1&&res){
					//   res=res.filter(it=>it.isDefault!=1)
					// }


					if (!req.getStorage('defaultMerchant')) {
						api.defaultMerchant(req, "", data => {
							// console.log(data);
						});
					}

					that.setData({
						pageList: res
					});

					if (res.length <= 0) {
						this.setData({
							addressIshow: true
						});
					} else {
						this.setData({
							addressIshow: false
						});
					}

					// console.log(res);
				});
			},

			chooseMerchant(id, index) {
				// if(id==this.merchant.id) return false
				let page = this.pageList[index];

				if (this.isChoose) {
					if (page.isGoods == 0) return req.msg('该门店不能自提');
					let pages = getCurrentPages();
					var prevPage = pages[pages.length - 2];
					if (page.type == 5) {
						prevPage.$vm.setData({
							merchant: page,
							merchantId: page.merchantDTO.id,
							['query.merchantId']: page.merchantDTO.id,
							['query.shopId']: page.id,
							freshen: true
						});
					} else {
						prevPage.$vm.setData({
							merchant: page,
							merchantId: page.id,
							['query.merchantId']: page.id,
							['query.shopId']: '',
							freshen: true
						});
					}
					// 海报分享切换
					if (prevPage.$vm.scene) {
						prevPage.$vm.setData({
							switch: false
						});
					}
					// 切换门店
					if (this.type == 1) {
						prevPage.setData({
							['query.merchantId']: page.id
						});
					}
					// console.log(prevPage.$vm)

					uni.navigateBack();
				}
				var timestamp = Date.parse(new Date());
				if (page.type == 5) {
					page.time = timestamp + 1 * 60 * 1000
					page.merchantDTO.time = timestamp + 1 * 60 * 1000
					req.setStorage('smallShop', page);
					req.setStorage('MERCHANT', page.merchantDTO);
				} else {
					page.time = timestamp + 1 * 60 * 1000
					req.setStorage('MERCHANT', page);
					req.removeStorage('smallShop');
				}

				this.setData({
					title: page.title,
					isShow: false
				});
				this.getstore(); // wx.navigateBack();
			},

			// showMap() {
			//   req.getRequest('/api/merchant/list', { page: 1, limit: 100 }, data => {
			//     // console.log(data)
			//     data.forEach(res => {
			//       this.setData({
			//         'markers[0].latitude': res.lat,
			//         'markers[0].longitude': res.lng,
			//         'markers[0].iconPath': '/pages/images/location.png'
			//       })
			//     })
			//   })
			// },
			bindRegionChange: function(e) {
				let that = this;
				console.log('picker发送选择改变，携带值为', e.detail);
				let code = e.detail.code;
				that.isLoad = true;
				that.form.page = 1;
				// that.getList(e.detail.code[2]);
				if(code.length == 1){
					that.form.province = code[0];
					that.form.city = '';
					that.form.country = '';
					that.region = e.detail.value[0];
					that.regions = that.region.toString('');
				}else if(code.length == 2){
					that.form.province = code[0];
					that.form.city = code[1];
					that.form.country = '';
					that.region = [e.detail.value[0],e.detail.value[1]];
					that.regions = that.region[1].toString('');
				}else{
					that.form.province = code[0];
					that.form.city = code[1];
					that.form.country = code[2];
					that.region = [e.detail.value[0],e.detail.value[1],e.detail.value[2]];
					that.regions = that.region[2].toString('');
				}
				that.getList();
				// this.setData({
				// 	region: e.detail.value
				// 	'form.regionCode': e.detail.code[2]
				// });
			},

			getstore() {
				if (this.isChoose) return false;
				let merchant;

				if (req.getStorage('smallShop')) {
					merchant = req.getStorage('smallShop');
				} else {
					merchant = req.getStorage('MERCHANT');
				}
				let pages = getCurrentPages();
				var prevPage = pages[pages.length - 2];
				prevPage.$vm.setData({
					freshen: true
				});
				this.setData({
					merchant: merchant
				});
			},

			// 查看详情
			tonearbyDet(event) {
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				uni.navigateTo({
					url: '/pages/nearbyDetails/nearbyDetails?id=' + page.id
				});
			},

			//拨打电话
			makePhoneCall(event) {
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				uni.makePhoneCall({
					phoneNumber: page.phone
				});
			},

			//搜索
			search(e) {
				// console.log(e.detail.value);
				this.searchTitle = e.detail.value;
				this.setData({
					searchTitle: e.detail.value
				}); // return e.detail.value.replace(/\s+/g, '').replace(/[^\u4e00-\u9fa5a-zA-Z0-9\w]/g, '');
			},

			//清除输入框
			clearInput() {
				this.setData({
					searchTitle: ''
				});
			},

			confirmSearch() {
				let value = this.searchTitle;
				this.toSearch(value, true);
			},

			confirm() {
				let value = this.searchTitle;
				this.toSearch(value, true);
			},

			toSearch(value, isSave) {
				this.isLoad = isSave;
				let form = this.form;
				form.page = 1;
				form.title = value;
				form.isBusiness = 1; // form.regionCode=''

				req.getRequest('/api/merchant/listV2', form, res => {
					// console.log("1")
					let data;
					data = res.map(it => {
						it.isChoose = false;
						if (it.range > 0) it.range = parseFloat(it.range).toFixed(1);
						if (this.isChoose && it.isGoods == 0) it.isChoose = true;
						return it;
					});
					data = data.filter(it => it.isGoods != 0);

					if (!req.getStorage('defaultMerchant')) {
						api.defaultMerchant(req, "", data => {
							// console.log(data);
						});
					} // req.setStorage('defaultMerchant',data.filter(it=>it.isDefault==1))
					// if(JSON.parse(req.getStorage('configRes')).Is_Store_Price_Stock==1&&data){
					//   data=data.filter(it=>it.isDefault!=1)
					// }


					this.setData({
						pageList: data
					});

					if (data.length <= 0) {
						this.setData({
							addressIshow: true
						});
					} else {
						this.setData({
							addressIshow: false
						});
					}
				});
			},

			closeLayer() {
				this.setData({
					isShow: true
				});
				uni.navigateBack();
			},

			goNavigation(event) {
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				let plugin = requirePlugin('routePlan');
				let key = req.public.mapLBSKEY; //使用在腾讯位置服务申请的key

				let referer = req.getStorage('appName'); //调用插件的app的名称

				// console.log("名称====" + referer);
				let endPoint = JSON.stringify({
					//终点
					'name': page.title,
					'latitude': page.lat,
					'longitude': page.lng
				});
				uni.navigateTo({
					url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
				});
			}

		}
	};
</script>
<style>
	@import "./nearby.css";
</style>
