<!--
  组件功能： 省市县三级联动选择 
  @author terrfly
  @site https://www.jeequan.com
  @date 2022/11/30 13:25
-->
<template>
	<uni-data-picker :localdata=" type=='mccAli'? mccAli : areaCodeData" v-model="vdata.selectedVal" @change="changeFunc">
		<template #default="{data, error, options}">
			<view v-if="error" class="error">
				<text>{{error}}</text>
			  </view>
			  <view v-else-if="data.length" class="selected">
				  <text  style="font-size: 32rpx;">{{data.map(v=>v.text).join('/')}}</text>
			  </view>
			  <view v-else>
				<text :class="{'place-style':!vdata.selectedVal}" style="font-size: 32rpx;">请选择</text>
			  </view>
		  </template>
	</uni-data-picker>
</template>

<script setup>
import { reactive, ref, onMounted, watch } from 'vue'
import dataKit from '@/commons/utils/dataKit.js'
import areaCodeData from "./areaCodeData.json" // 地址
import mccAli from "@/commons/JSON/mccAli.json"

// emit 父组件使用： v-model="val" 进行双向绑定。
const emit = defineEmits(['update:areacodeList'])

// 定义组件参数 
const props = defineProps({
	
	// 省市县， 三级 数组  支持双向绑定。 
	areacodeList: { type: Array, default: () => [] },
	// json 类型
  type:{type:String}
})
  
// 当前组件参数 
const vdata = reactive({

	selectedVal: '', 

})

onMounted(() => {
	if(props.areacodeList.length > 0 ){
		vdata.selectedVal = props.areacodeList[2]
	}
})

// 切换时 
watch(() => props.areacodeList, (newVal, oldVal) => {
  if(Array.isArray(newVal)){
    vdata.selectedVal = newVal[newVal.length - 1] 
  }else if(typeof newVal =='string'){
    vdata.selectedVal  = [newVal]
  }
})

function changeFunc(e){
	let data = []

	if(e.detail.value && e.detail.value.length > 0 ){
		emit("update:areacodeList",e.detail.value.map(v=> v.value) )
	}else{
		emit("update:areacodeList", [] )
	}
}




// 根据最后一位的（县级编码 搜索展开全部内容 ）
function resetBySingleAreacode(areacode){

  if(!areacode){
    return 
  }
  
  let p3 = dataKit.recursionTreeData(areaCodeData, (r => r.value == areacode))
  if(!p3){
      return false
  }

  let p2 = dataKit.recursionTreeData(areaCodeData, (r => r.value == p3[1].value))
  if(!p2){
      return false
  }

  let p1 = dataKit.recursionTreeData(areaCodeData, (r => r.value == p2[1].value))
  if(!p1){
      return false
  }
  
  emit("update:areacodeList", [p1[0].value, p2[0].value, p3[0].value])
  
}

/** 根据省市县areaCode 获取省市县名称数据 **/
function getNameListBySingleAreacode(areacode){
	
	if(!areacode){
	  return 
	}
	
	let p3 = dataKit.recursionTreeData(areaCodeData, (r => r.value == areacode))
	if(!p3){
	    return false
	}
	
	let p2 = dataKit.recursionTreeData(areaCodeData, (r => r.value == p3[1].value))
	if(!p2){
	    return false
	}
	
	let p1 = dataKit.recursionTreeData(areaCodeData, (r => r.value == p2[1].value))
	if(!p1){
	    return false
	}
	
	return [p1[0].text, p2[0].text, p3[0].text]
	
}


defineExpose({resetBySingleAreacode, getNameListBySingleAreacode})
</script>
<style scoped lang="scss">
	.place-style{
		color: #b3b3b3;
		
	}
	
</style>