<template>
<view>
	<view class="map-box">
		<map class="map" id="map1" ref="map1" @regionchange="regionChange" :latitude="latitude" :longitude="longitude" :markers="covers" @markertap="clickMap" :scale="mapScale" :circles="circles"></map>
		<!-- <view class="store" @click="showStore"><image src="../../static/images/sj_map_ico.png"></image></view>
		<view class="ibn" @click="showCab"><image src="../../static/images/jg_map_ico.png"></image><view class="count ddflex">12</view></view> -->
		<view class="nearby-box ddflex">
			<view class="nearby-yuan"></view>
			<image src="../../static/images/fj_loca.png" class="loca"></image>
			<view class="nearby">
				<view class="nearby-text ddflex" @click="jumpUrl('/card/cardList/cardList')">附近<image src="/static/pages/images/more.png"></image></view>
				<view class="gan"></view>
			</view>
		</view>
		<view class="side">
			<view class="li ddflex" @click="getLoca"><image src="../../static/images/side_ico3.png"></image></view>
		</view>
	</view>
	<view class="cabinet" :style="'bottom:' + cabBottom">
		<view class="register-box">
			<view class="register-title ddflex fflex" @click.stop="jumpUrl('/card/cardDetail/cardDetail?id='+cabInfo.id)">
				<image class="register-title-icon" :src="cabInfo.avatar?cabInfo.avatar:'/static/images/userimg.png'"></image>
				<view class="flex" style="min-width: 0;">
					<view class="ddflex">
						<view class="card-name fflex tover">{{cabInfo.realName?cabInfo.realName:''}}</view>
						<uni-rate class="ddflex" color="#999999" active-color="#FF4600" :readonly="true" size="16" allow-half :value="cabInfo.evaluateScore?cabInfo.evaluateScore/2:5" />
					</view>
					<view class="ddflex" style="margin-top: 4rpx;">
						<view class="card-tag">{{cabInfo.jobName}}</view>
						<view class="card-tag">入司{{cabInfo.inDate?monthDayDiff(cabInfo.inDate):'1年'}}</view>
					</view>
					<view class="card-area ddflex">
						<image src="/static/pages/images/dzico.png"></image>
						<view class="flex tover">{{cabInfo.address}}</view>
						<view style="color: #A1A1A1;margin-left: 10rpx;">距离{{cabInfo.distance>1000?((cabInfo.distance/1000).toFixed(2)+'km'):(cabInfo.distance+'m')}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- @click="jumpUrl('/card/cardList/cardList')" -->
		<view class="found-more ddflex" @click="jumpUrl('/card/cardList/cardList')">
			<image src="../../static/images/found_more.png"></image>
			寻找更多保险顾问
		</view>
	</view>
	
	<canvas v-if="canvasShow" class="canvas" style="width:80px;height:92px;" canvas-id="logoIcon"></canvas>
	<!-- <update-userinfo :update-info="isUpdateInfo" :update-mobile="isUpdateMobile" v-if="isShowUpdate" @closeUpdate="closeUpdate" @updateInfo="updateInfo" @updateMobile="updateMobile"></update-userinfo> -->
</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const QQMapWX = require("../../utils/qqmap.js");
export default {
	data() {
		return {
			picUrlss: req.public.picUrls,
			userInfo: {},
			map: '',
			latitude: '23.027923',
			longitude: '113.753815',
			mapScale: 16,
			circles: [],
			covers: [],
			cabList: [],//机柜列表
			cabInfo: {},//机柜详情
			cabBottom: '-100%',
			storeList: [],//门店列表
			storeInfo: {},//门店详情
			storeBottom: '-100%',
			isAuth: false,//是否实名认证
			markerId: '',
			orderCount: '',//订单数
			isShowUpdate: false,//是否显示更新信息弹窗
			// isUpdateInfo: false,//更新用户信息
			isUpdateMobile: false,//绑定手机号
			realInfo: {},//实名认证信息
			config: {},//配置信息
			popadv: '',//弹窗广告
			topadv: '',//顶部广告
			isShowPopAdv: false,
			isShowTopAdv: false,
			canvasShow:false
		}
	},
	async onLoad(options) {
		if(options.userId){
			req.setStorage('pidCode',options.userId);
		}
		// req.silenceLogin(options.userId, '');
		this.map = uni.createMapContext("map1", this);
		let locations = req.getStorage('loctionAddressMap');
		QQMapWX.initMap();
		req.getLocation(res => {
			const to = {
				latitude: res.latitude,
				longitude: res.longitude
			};
			req.setStorage('loctionAddressMap',to)
			this.latitude = res.latitude;
			this.longitude = res.longitude;
			this.map.moveToLocation(to,res=>{})
			QQMapWX.reverseGeocoder(to,async resp => {
				await this.getCabList();
			});
		});
	},
	onShow() {
		this.getConfig();
		// this.userInfo.authState = 1;
	},
	onHide() {
		this.hideStore();
		this.hideCab();
	},
	methods: {
		hidePopAdv(){
			this.isShowPopAdv = false;
		},
		hideTopAdv(){
			this.isShowTopAdv = false;
		},
		banJump(item){
			app.globalData.clickBanner(item)
		},
		getConfig(){
			req.getRequest('/api/other/config',{},data=>{
				req.setStorage('configRes',JSON.stringify(data));
				this.config = data;
			})
		},
		addNearby(){
			let cover = [];
			let obj = {
				column: 0,
				type: 2,
				latitude: req.getStorage('loctionAddressMap').location.lat,
				longitude: req.getStorage('loctionAddressMap').location.lng,
				width: 75,
				height: 99,
				iconPath: '/static/images/nearby.png',
				// joinCluster: true
			}
			cover.unshift(obj);
			return cover;
		},
		async getLoca(){
			this.map.moveToLocation({latitude:this.latitude,longitude:this.longitude},res=>{})
			// this.covers = [];
			// this.latitude = req.getStorage('loctionAddressMap').location.lat;
			// this.longitude = req.getStorage('loctionAddressMap').location.lng;
			// await this.getCabList();
		},
		async regionChange(e){
			// console.log('视野发生变化时触发',e)
			// if(e.type == 'end' && e.causedBy == 'drag'){
			// 	this.covers = [];
			// 	this.latitude = e.detail.centerLocation.latitude;
			// 	this.longitude = e.detail.centerLocation.longitude;
			// 	await this.getCabList();
			// }
		},
		async clickMap(e){
			console.log('e==',e.detail)
			let markerId = e.detail.markerId
			let oldIndex = this.covers.findIndex(item=>item.did==this.cabInfo.id)
			let index = this.covers.findIndex(item=>item.id==markerId)
			// if(this.markerId == this.covers[markerId-1].column && this.markerId != 0) return false;
			this.cabBottom = '-100%';
			this.storeBottom = '-100%';
			this.getCabInfo(index);
			let covers = [];
			// this.covers = []
			if(this.covers&&this.covers.length>0){
				
				for(let i=0;i<this.covers.length;i++){
					let it = this.covers[i]
					if(i == index || i == oldIndex){
						console.log('i 当前转换的下标',i,index,oldIndex,it.id==markerId)
						let markerLogo = await this.getMarkerLogo(it.logo,it.id==markerId?2:null)
						let obj = {
							latitude: it.latitude,
							longitude: it.longitude,
							width: 80,
							height: 92,
							logo:it.logo,
							id:it.id,
							did:it.did,
							// iconPath: '/static/images/jg_map_ico.png',
							// 'https://img.zhiqiyun.com/test/2023/07/27/ec50eeee1ab3358d9ba397c86ae8fcc6.jpeg'
							iconPath: markerLogo//显示的图标     
							// radius: it.column_4[0].radius,//检索的半径，单位为米
							// joinCluster: true
						}
						covers.push(obj)
					}else{
						covers.push(it)
					}
				}
			}
			this.covers = JSON.parse(JSON.stringify(covers))
			this.$forceUpdate()
			// console.log('covers==',this.covers[markerId-1])
			// console.log('this.circles=',this.circles[0])
		},
		timeRange(beginTime, endTime) {
			let strb = beginTime.split(":");
			if (strb.length != 2) {
				return false;
			}
			let stre = endTime.split(":");
			if (stre.length != 2) {
				return false;
			}
			let b = new Date();
			let e = new Date();
			let n = new Date();
			b.setHours(strb[0]);
			b.setMinutes(strb[1]);
			e.setHours(stre[0]);
			e.setMinutes(stre[1]);
			if (n.getTime() - b.getTime() >= 0 && n.getTime() - e.getTime() < 0) {
				return true;
			} else {
				return false;
			}
		},
		captureTime(time,isTime){
			return util.captureTime(time,isTime)
		},
		getCabList(){
			let that = this;
			let form = {
				latitude: this.latitude,
				longitude: this.longitude,
				page:1,
				limit:10
				// distance: 2000
			}
			return new Promise(async(resolve,reject)=>{
				req.getRequest('/api/visiting/card/cardInfoList',form,async res=>{
					this.cabList = res.list;
					this.getCabInfo(0)
					let data = {list:[]}
					data.list = res.list.map(item=>{
						let obj = {
							userId:item.id,
							latitude:item.latitude,
							longitude:item.longitude,
							logo:item.avatar
						}
						return obj
					})
					let covers = this.covers; //this.addNearby();
					if(data.list&&data.list.length>0){
						for(let i=0;i<data.list.length;i++){
							let it = data.list[i]
							let markerLogo = await this.getMarkerLogo(it.logo)
							let obj = {
								id:i+1,
								did:it.userId,
								latitude: it.latitude,
								longitude: it.longitude,
								width: 80,
								height: 92,
								logo:it.logo,
								// iconPath: '/static/images/jg_map_ico.png',
								// 'https://img.zhiqiyun.com/test/2023/07/27/ec50eeee1ab3358d9ba397c86ae8fcc6.jpeg'
								iconPath: markerLogo//显示的图标     
								// radius: it.column_4[0].radius,//检索的半径，单位为米
								// joinCluster: true
							}
							covers.push(obj);
						}
					}
					// if(covers.length > 0){
					// 	covers.map((it,index)=>{
					// 		it.id = Number(index+1);
					// 		return it;
					// 	})
					// }
					that.covers = covers
					resolve();
				})
			})
		},
		getCabInfo(index){
			this.cabInfo = this.cabList[index];
			this.cabBottom = 0;
		},
		routePlan(type){
			let that = this;
			let plugin = requirePlugin('routePlan');
			let key = req.public.mapLBSKEY;  //使用在腾讯位置服务申请的key
			let referer = '线上会客厅系统';   //调用插件的app的名称
			let endPoint = '';
			if(type == 1){
				endPoint = JSON.stringify({  //终点
				  'name': that.cabInfo.devName,
				  'latitude': that.cabInfo.latitude,
				  'longitude': that.cabInfo.longitude
				});
			}else{
				endPoint = JSON.stringify({  //终点
				  'name': that.storeInfo.name,
				  'latitude': that.storeInfo.latitude,
				  'longitude': that.storeInfo.longitude
				});
			}
			console.log('endPoint==',endPoint)
			wx.navigateTo({
			  url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
			});
		},
		callPhone(number){
			uni.makePhoneCall({
				phoneNumber: number
			})
		},
		hideCab(){
			this.cabBottom = '-100%';
			this.markerId = '';
		},
		showCab(){
			this.isShowCab = true;
		},
		jumpUrl(url){
			if (!req.isLogins(true)) return false;
			uni.navigateTo({
				url: url
			})
		},
		
		monthDayDiff(date) {
			return util.monthDayDiff(date)
		},
		
		
		// 获取markerLogo
			getMarkerLogo(url,type){
				// 多次绘图时重置canvas
				this.canvasShow = true
				let that = this
				return new Promise(async(re,rj)=>{
					let mapBgUrl = 'https://img.zhiqiyun.com/test/2023/07/27/2d30f06817365b83a5f78c455fce8974.png'
					if(type&&type==2) mapBgUrl = 'https://img.zhiqiyun.com/test/2023/07/27/ad0bfade8dcffa6b20c045a53945dea3.png'
					// console.log('mapBgUrl',mapBgUrl)
					const avatarp = this.getImageInfo(url); // 获取小程序码图
					const mapBg = this.getImageInfo(mapBgUrl); // 获取小程序码图
					Promise.all([avatarp,mapBg]).then(([avatar,mapIcon]) => {
					const ctx = uni.createCanvasContext('logoIcon', this); // 绘制背景，填充满整个canvas画布
					let width = 80,
						height = 92; //默认背景
					// ctx.setFillStyle('transparent');
					// ctx.fillRect(0, 0, width, height); // 画布背景
					ctx.drawImage(mapIcon.path, 0, 0, width, height); //绘制图片
					// ctx.save();
					// ctx.restore();
					// ctx.beginPath();
					const avatarW = width-28;
					that.roundRect(ctx, 14, 12, avatarW, avatarW, avatarW/2);
					ctx.clip(); //裁剪
					ctx.drawImage(avatar.path, 14, 12, avatarW, avatarW);
					ctx.restore();
					ctx.draw(false, function() {
						uni.canvasToTempFilePath({
							canvasId: 'logoIcon',
							success: function(res) {
								// console.log('ctx.draw',res.tempFilePath)
								that.canvasShow = false
								re(res.tempFilePath)
							},
							fail: function(res) {
								console.log(res)
								rj()
							}
						}, that);
					});
					})
				})
			},
			getImageInfo(url) {
				// console.log('getImageInfo',url)
				return new Promise((resolve, reject) => {
					if (!url) {
						resolve();
						return false;
					}
							
					uni.getImageInfo({
						src: url,
						success: resolve,
						fail: reject
					});
				});
			},
			/**
			*
			 * @param {CanvasContext} ctx canvas上下文
			 * @param {number} x 圆角矩形选区的左上角 x坐标
			 * @param {number} y 圆角矩形选区的左上角 y坐标
			 * @param {number} w 圆角矩形选区的宽度
			 * @param {number} h 圆角矩形选区的高度
			 * @param {number} r 圆角的半径
			 */
			roundRect: function(ctx, x, y, w, h, r) {
				// 开始绘制
				ctx.beginPath(); // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
				// 这里是使用 fill 还是 stroke都可以，二选一即可
						
				ctx.setFillStyle('white'); // ctx.setStrokeStyle('transparent')
				// 左上角
						
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); // border-top
						
				ctx.moveTo(x + r, y);
				ctx.lineTo(x + w - r, y);
				ctx.lineTo(x + w, y + r); // 右上角
						
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); // border-right
						
				ctx.lineTo(x + w, y + h - r);
				ctx.lineTo(x + w - r, y + h); // 右下角
						
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); // border-bottom
						
				ctx.lineTo(x + r, y + h);
				ctx.lineTo(x, y + h - r); // 左下角
						
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); // border-left
						
				ctx.lineTo(x, y + r);
				ctx.lineTo(x + r, y); // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
						
				ctx.fill(); // ctx.stroke()
						
				ctx.closePath(); // 剪切
						
				ctx.clip();
			}
	},
}
</script>

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