<!--
@ 作者: 秦东
@ 时间: 2023-12-07 13:25:29
@ 备注: 百度地图
-->
<template>
	<div>
		<el-form-item
			v-bind="data.item"
			:prop="tProp || data.name"
			:class="config.className"
			:rules="itemRules"
			:label="getLabel(data.item as FormItem)"
		>	
			<input  v-model="value" type="hidden" />
			<input  v-model="lngLat" type="hidden" />
			<el-input v-model="address" >
				<template #append>
					<el-button class="fa fa-map-marker" @click="openPickMap" />
				</template>
			</el-input>
			<div :id="mapId" ref="myBaiduMapView" class="smallMapView"></div>
		</el-form-item>
		<PickMap v-if="mapShow" v-model:mapshow="mapShow" :address="address" :lnglat="lngLat" @updatemapinfo="updateMapInfo" />
	</div>

</template>
<script lang='ts' setup>
import { 
	constControlChange,
    constFormProps,
} from '@/api/DesignForm/utils'
import validate from '@/api/DesignForm/validate'
import { FormItem, FormList } from '@/api/DesignForm/types'

import PickMap from './pickmap.vue'


const props = withDefaults(
    defineProps<{
		data: FormList
		tablekey: any
		modelValue?: any // 子表和弹性布局时时有传
		tProp?: string // 子表时的form-item的prop值，用于子表校验用
    }>(),
    {}
)
const emits = defineEmits<{
    (e: 'update:modelValue', numVal: any): void
}>()
let mapId = "baiduMapView"+ Math.ceil(Math.random());
const mapShow = ref(false)
const address = ref<string>();				//行政组织树数据
const lngLat = ref<string>();				//行政组织树数据
const formProps = inject(constFormProps, {}) as any
const type = computed(() => {
    return formProps.value.type
})
const config = computed(() => {
    return props.data.config || {}
})

const changeEvent = inject(constControlChange, '') as any

const value = computed({
    get() {
		if (props.tProp) {
			// 表格和弹性布局
			return props.modelValue
		} else {
			return formProps.value.model[props.data.name]
		}
    },
    set(newVal: any) {
		if (props.tProp) {
			emits('update:modelValue', newVal)
		}
		updateModel(newVal)
    }
})
const updateModel = (val: any) => {
	let controlAttribute = ""
	if(props.data.control){
		if(props.data.control.type){
			controlAttribute = props.data.control.type
		}
	}
    changeEvent &&
    changeEvent({
        key: props.data.name,
        value: val,
        data: props.data,
        tProp: props.tProp,
		type: props.data.type,
		attribute: controlAttribute
    })
}



const getLabel = (ele: FormItem) => {
    const showColon = formProps.value.showColon ? '：' : ''
    if (ele) {
    	return ele.showLabel ? '' : ele.label + showColon
    } else {
      	return ''
    }
}

// 返回当前item项的校验规则
const itemRules = computed(() => {
    let temp
    const itemR: any = props.data.item?.rules || []
    const customR = formatCustomRules()
    // 如果三个都没有设置，则返回undefined
    if (itemR?.length || customR?.length) {
      	temp = [...customR, ...itemR]
    }
    return temp
})
// 处理自定义校验规则，将customRules转换后追加到rules里
const formatCustomRules = () => {
    const rulesReg: any = {}
    validate &&
    validate.forEach(item => {
        rulesReg[item.type] = item.regExp
    })

    // 获取校验方法 父级使用provide方法注入
    const temp: any = []
    props.data.customRules?.forEach((item: any) => {
		if (!item.message && item.type !== 'methods') {
			return // 方法时允许提示信息为空
		}
		let obj = {}
		if (item.type === 'required') {
			obj = { required: true }
		} else if (item.type === 'rules') {
			// 自定义表达式
			obj = { pattern: item.rules }
		} else if (item.type === 'methods') {
			// 方法时
			const methods: any = item.methods
			if (methods) {
			obj = { validator: inject(methods, {}) }
			}
		} else if (item.type) {
			obj = { pattern: rulesReg[item.type as string] }
		}
		// 这里判断下防某些条件下重复push的可能或存重复校验类型
		let message: any = { message: item.message }
		if (!item.message) {
			// 当使用validator校验时，如果存在message字段则不能使用 callback(new Error('x'));的提示
			message = {}
		}
		temp.push(
			Object.assign(
				{
					trigger: item.trigger || 'blur'
				},
				obj,
				message
			)
		)
    })
    return temp
}
const drawingBaiduMap = ref<any>(null)
const mapObject = ref<any>()

const longitude= ref<number>(117.14272945140574)
const latitude= ref<number>(35.91808471435389)
const loadJScript = () => {
	const script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = 'https://api.map.baidu.com/getscript?v=3.0&ak=ljiKlTAsS7SNVqDM16IUwRVFFhrvbxiF';
	script.onload = () => {
		mapInit(mapObject)
	}
	document.body.appendChild(script);
}
// 初始化地图
const mapInit = (maps:any) => {
	const map = new window.BMap.Map(mapId); // 创建Map实例
	var opts = {type: BMAP_NAVIGATION_CONTROL_LARGE}    
	map.addControl(new BMap.NavigationControl(opts));	//添加控件
	map.addControl(new BMap.ScaleControl());
	map.addControl(new BMap.MapTypeControl());
	map.enableScrollWheelZoom(); // 启用滚轮放大缩小
	const point = new BMap.Point(longitude.value,latitude.value); // 创建点坐标
 	map.centerAndZoom(point, 16);
  	var marker = new BMap.Marker(point);
  	map.addOverlay(marker);
}

watch(value,(val:any)=>{
	console.log("加载地址--4-->",value.value,props.data)
	if(value.value != null && value.value !=  "") {
		let adresAry = value.value.split('|*@*|')
		if(adresAry.length >0){
			address.value = adresAry[0]
			if(adresAry.length >=1){
				lngLat.value = adresAry[adresAry.length-1]
			} 
		}
		console.log("加载地址--2-->",value.value,adresAry,address.value,lngLat.value)
		if(lngLat.value != null && lngLat.value != ""){
			let lnogLate = lngLat.value.split(",");
			if(lnogLate.length >= 2){
				longitude.value = lnogLate[0]
				latitude.value = lnogLate[lnogLate.length - 1]
			}
		}
		console.log("加载地址--31-->",value.value,adresAry,address.value,lngLat.value,longitude.value,latitude.value)
		mapInit(mapObject)
	}
})
watch(()=>address.value,(val:string)=>{
	if(lngLat.value != null && lngLat.value != ""){
		value.value = address.value+"|*@*|"+lngLat.value
	}else{
		value.value = address.value
	}
})
onMounted(()=>{
	console.log("加载地址--1-->",value.value,props.data)
	if(value.value != null && value.value !=  "") {
		let adresAry = value.value.split('|*@*|')
		if(adresAry.length >0){
			address.value = adresAry[0]
			if(adresAry.length >=1){
				lngLat.value = adresAry[adresAry.length-1]
			} 
		}
		console.log("加载地址--2-->",value.value,adresAry,address.value,lngLat.value)
		if(lngLat.value != null && lngLat.value != ""){
			let lnogLate = lnglat.value.split(",");
			if(lnogLate.length >= 2){
				longitude.value = lnogLate[0]
				latitude.value = lnogLate[lnogLate.length - 1]
			}
		}
		console.log("加载地址--3-->",value.value,adresAry,address.value,lngLat.value,longitude.value,latitude.value)
	}
	
	loadJScript()
})

const openPickMap = () => {
	mapShow.value = true
}
//更新地图信息
const updateMapInfo = (ads:string,lng:any,lat:any) =>{
	address.value = ads
	lngLat.value = lng+","+lat
	value.value = ads+"|*@*|"+lng+","+lat
	longitude.value = lng
	latitude.value = lat
	mapInit(mapObject)
}
</script>

<style  lang='scss' scoped>
.smallMapView{
	width:100%;
	height:400px;
}
</style>