<template>
  <view class="">
    <u-picker :show="show" :title="title" :columns="columns" keyName="label" ref="uPicker"
                @confirm="recyclePersonConfirm" @change="recyclePersonChange" @cancel='close'></u-picker>
  </view>
</template>

<script>
export default {
  name: 'personPicker',
  data() {
    return {
        show: false,
        columns: [],
    }
  },
  props: {
    title: {
      type: String,
      default: '请选择',
    },
  },
  emits: ['selectPerson'],
  methods: {
    open() {
        this.show = true;
        this.recyclePersonClick();
    },
    close() {
        this.columns = [];
        this.show = false;
    },
    recyclePersonConfirm({ columnIndex, value, values,index }) {
        this.$emit('selectPerson', value[value.length - 1] ? value[value.length - 1] : value[value.length - 2]);
        this.close();
    },
    recyclePersonChange(e) {
        const {
              columnIndex,
              value,
              values,
              picker = this.$refs.uPicker
          } = e
          // 当前项不是用户，且有子级，添加下一层
          if(!value[columnIndex].isUser){
            picker.setColumnValues(columnIndex+1, value[columnIndex].children);
          }else{
            // 当前是用户且同等级的其他项有子级，则添加下一层空数据
            values[columnIndex].forEach((item, index) => {
              if(!item.isUser){
                picker.setColumnValues(columnIndex+1, []);
              }
            })
          }
        },
    recyclePersonClick() {
        uni.$u.api.getCustomerManagerAllList().then(res => {
            this.columns = [res.data] || [];
            
            // 如果第一层只有一个选项，自动处理下一层级
            if (res.data && res.data.length === 1) {
                // 如果当前项不是用户且有子级，添加下一层
                if (!res.data[0].isUser && res.data[0].children && res.data[0].children.length > 0) {
                    this.columns.push(res.data[0].children);
                }
            }
        })
    },
  }
}
</script>

<style lang="scss" scoped>
</style>