<template>
<div class="houseSelect">
  <van-field
      class="input-a"
      v-model="fieldValue"
      is-link
      readonly
      label="具体房屋信息"
      placeholder="请选择具体位置"
      @click="show = true"
  />
  <van-popup v-model="show" round position="bottom" class="popup" :get-container="getEl">
    <van-cascader
        :field-names="fieldNames"
        v-model="cascaderValue"
        title="请选择具体位置"
        :options="options"
        @change="onChange"
        @close="show = false"
        @finish="onFinish"
    />
  </van-popup>
</div>
</template>

<script>
export default {
  name: "houseSelect",
  mounted() {
    this.getEstates()
  },
  methods:{
    getEl(){
      return document.getElementsByTagName('body')[0]
    },
    onChange(target){
      if(target.selectedOptions[target.tabIndex].leaf == true){
        // this.form.houseId = String(target.value)
        this.$emit('on-select',String(target.value))
      }else{
        let params = {
          estateUnitId:target.value
        }
        this.$api.getEstates(params).then(res=>{
          target.selectedOptions[target.tabIndex].children = res.content.subs.map(x=>{
            if(!x.leaf){
              return {
                ...x,
                name:x.name+(x.exp?x.exp:''),
                children:[]
              }
            }else{
              return {
                ...x,
                name:x.name+(x.exp?x.exp:''),
              }
            }
          })
        })
      }

    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.show = false;
      this.fieldValue = selectedOptions.map((option) => option.name).join('/');
    },
    getEstates(){
      let params = {
        estateUnitId:1
      }
      this.$api.getEstates(params).then(res=>{
        console.log(res)
        this.options = res.content.subs.map(x=>{
          if(!x.leaf){
            return {
              ...x,
              name:x.name+(x.exp?x.exp:''),
              children:[]
            }
          }else{
            return {
              ...x,
              name:x.name+(x.exp?x.exp:''),
            }
          }
        })
      })
    },
  },
  data(){
    return {
      el:null,
      show:false,
      fieldValue: '',
      cascaderValue: '',
      fieldNames:{
        text:'name',
        value:'id',
        children:'children'
      },
      // 选项列表，children 代表子选项，支持多级嵌套
      options: [
      ],
    }
  },
}
</script>

<style scoped lang="less">
.popup{
  //position: relative;
  z-index: 99999;
}
.input-a{
  //width: 340px;
  padding: 0 15px;
  height: 48px;
display: flex;
//justify-content: center;
align-items: center;
  margin: 0 auto;
  background: #F4F5F6;
  border-radius: 8px;
  opacity: 0.8;
  border: none;
  outline: none;
  line-height: 50px;
}
</style>