<!-- 表单内的选择框 -->
<template>
    <view class="zj-uview-select" @click="onClick">
        <!-- uview 1.0 -->
        <!-- <u-input type="select" v-model="inputLabel" :placeholder="header.placeholder" :disabled="!editable"  :select-open="showSelect" input-align="right" :colorType="colorType ? colorType : (editable ? '' : 'info')" @click="editable ? showSelect = true : ''" /> -->
        <!-- <u-select v-model="showSelect" mode="mutil-column-auto" :list="header.list" :default-value="defaultValue" @confirm="onChange" @clear="onClear" /> -->
        
        <!-- uview 2.0 -->
        <u-input type="select" v-model="inputLabel" :placeholder="header.placeholder" :disabled="editable"  :select-open="showSelect" input-align="right" :border="border || 'none'" disabledColor="" suffixIcon="arrow-down" :color="editable ? (color ? color : '') : '#AAA'" @focus="onClick" />
        <!-- [header.list] 注：联动需要手动控制-->
        <!-- <u-picker :show="showSelect" mode="mutil-column-auto" :columns="[header.list]" :default-value="defaultValue" keyName="label" :showToolbar="true" :closeOnClickOverlay="true" @confirm="onChange" @clear="onClear" @cancel="showSelect=false" /> -->
        <u1-select v-model="showSelect" mode="mutil-column-auto" :list="header.list" :default-value="defaultValue" @confirm="onChange" @clear="onClear" />
    </view>
</template>
<!-- :default-value="header.default ? header.default : []" -->


<script>
    // import UInput from "../zj-uview-input/u-input.vue";
    import U1Select from "./u-select.vue";
    export default {
        name: 'zj-uview-select',
        model: {
            prop: 'value',
            event: 'change'
        },
        components: {
            // UInput,
            U1Select,
        },
        props: {
            /** 表头 */
            header: {
                type: Object,
                default: () => ({})
            },
            /** @brief 传入的默认值。组件将监听并更新 */
            default: {
                type: [String, Boolean, Number],
                default: ''
            },
            /** @brief 传入的value值。组件根据该值自动判断数据是否需要更新 */
            value: {
                type: [String, Boolean, Number],
                default: ''
            },
            /** @brief 是否显示父层树。如“浙江省 杭州市 西湖区” */
            showLayer: {
                type: Boolean,
                default: true
            },
            /** @brief 层级间分隔符。默认空格 */
            split: {
                type: String,
                default: ' '
            },
            editable: {
                type: Boolean,
                default: true
            },
            // colorType: '',
            color: '',
            border: {
                type: String,
                default: 'none', // surround | bottom | none
            },
        },
        created() {
            // this.currentHeader = this.header;
        },
        data() {
            return {
                showSelect: false,
                currentHeader: "",
				defaultValue: [],
                inputLabel: this.value,
            }
        },
        methods: {
            /** @brief 监听更新从表单传递过来的value值改变 */
			updateDefault(){
				console.log("updateDefault: inputLabel, default, header:", this.inputLabel, this.default, this.header)
				
				const findResult = this.xFindLabel(this.value, this.header.list);
				console.log("updateDefault: 2", findResult);
				
				this.inputLabel = findResult.label;
				this.defaultValue = findResult.posArr;
			},
            /** @brief 递归查找某个value值，返回对应的label名称。注：val在树图中必须是唯一的 */
			xFindLabel(val, list){
				// console.log("xFindLabel: ", list.length, list, JSON.stringify(list));
				let result = {label: '', posArr: []};
				for(const i in list){
					if(list[i]['value'] == val){
						result.label = list[i]['label'];
						result.posArr.push(i);
						return result;
					}
					if(list[i]['children'] !== undefined){
						result = this.xFindLabel(val, list[i]['children']);
						if(result.posArr.length > 0){
							result.posArr.unshift(i);
							return result;
						}
					}
				}
				return result;
			},
            onClick(e){
                console.log("onClick:", e)
                this.showSelect = true;
            },
            onChange(e){
                // console.log("onChange: "+ JSON.stringify(e))
                let pos = e.length - 1; 
                //显示父层级的值和只显示最后一个值
                this.inputLabel = this.showLayer ? e.map( it => it.label).join(this.split) : e[pos].label;
                this.inputValue = this.showLayer ? e.map( it => it.value).join(this.split) : e[pos].value;
                
                //用于.sync模式的更新
                this.$emit("update:value", this.inputValue); 
                
                setTimeout(()=>{
                    //用于v-madel模式的更新
                    this.$emit("change", this.inputValue);
                    if(this.header.emit){
                        console.log("this.header.emit: "+ this.header.emit)
                        this.$emit("onEmit",{emitName: this.header.emit, emitValue: e});
                    }
                }, 40);
            },
            onClear(e){
                // console.log("onClear: ", JSON.stringify(e))
                this.inputLabel = '';
                this.$emit("update:value", '');
                setTimeout(()=>{
                    this.$emit("change", '');
                    if(this.header.emit){
                        // console.log("this.header.emit: "+ this.header.emit)
                        this.$emit("onEmit",{emitName: this.header.emit, emitValue: ''});
                    }
                }, 40);
            }
        },
        watch:{
            // header(val, old){
            //     currentHeader: val;
            // },
			
            default(val, old){
				// sieyoo 倒底是怎么回事，一个porp数据怎么会有__ob__: Observer 延迟出现呢？在PC端从没发现这类问题！！
				// 已排除网上说的浅拷贝问题（网上说改用深拷贝 asset(), JSON.parse()等）
				setTimeout(()=>{
					this.updateDefault();
				},100)
            },
        }
    }
</script>
<style scoped>
    .zj-uview-select{width: 100%;}
</style>
