<template>
  <div class="date-cell">
    <van-cell v-if="disabled" :required="required" :title="title" :label="label"/>
    <van-cell :required="required" :title="title" :label="label" is-link  @click="clickItem"/>
    <van-popup v-model="showPicker" round lazy-render position="bottom" :close-on-popstate="true" get-container="#app">
      <van-picker
        v-bind="$attrs"
        show-toolbar
        :value-key="prop.label"
        v-model="selected"
        :columns="columns"
        @confirm="pickerConfirm"
        @cancel="cancelPicker"
      />
    </van-popup>
  </div>
</template>

<script>
import {getDict} from "@/api/toConsult";
export default {
  props:{
    //禁用
    disabled:{
      type: [Boolean,String],
      default: false,
    },
    //双向绑定的数据
    value:{
      type: [String,Number],
      default: null,
    },
    required:{
      type: [Boolean,String],
      default: false,
    },
    //字典表
    dict:{
      type: String,
      default: null,
    },
    //标题
    title:{
      type: String,
      default: null,
    },
    //父组件给的列表数据
    dataList:{
      type: Array,
      default: ()=>[],
    },
    //自定义字段
    prop:{
      type: Object,
      default: ()=>(
        {
          label:'dictLabel',
          value:'dictValue'
        }
      ) ,
    }
  },
  data(){
    return{
      showPicker:false,
      selected:null,
      label:'',
      columns: [],
    }
  },
  watch:{
    dict:{
      handler(val){
        if(!val) return;
        if(this.dataList.length) return;
        this.queryDict();
      },
      immediate: true
    },
    dataList:{
      handler(val){
        if(this.dict) return;
        this.columns = this.dataList;
      },
      immediate: true
    },
    value:{
      handler (val) {
        console.log(val, '6666')
        if(!val){
          this.selected = null;
          this.label = null;
        }else{
          setTimeout(()=>{
            this.columns.forEach(v=> {
              console.log(v[this.prop.value], '7777')
              if (v[this.prop.value] === val) {
                this.selected = v;
                this.label = v[this.prop.label];
              }
            })
          },200)
          // this.selected = val;
          // this.label = val.dictLabel;
        }
      },
      immediate:true
    }
  },
  methods:{
    queryDict(){
      console.log(this.dict,'this.dict')
      getDict( this.dict ).then(res => {
        let { code, data, msg } = res;
        if (code == 200) {
         this.columns = data;
        }
      })
    },
    cancelPicker(){
      this.showPicker = false;
    },
    pickerConfirm(val){
      this.selected = val;
      this.label = val[this.prop.label];
      this.showPicker = false;
      this.$emit('change',this.selected[this.prop.value])
    },
    clickItem(){
      this.showPicker = true;
    },
  },
  model:{
    prop: 'value',
    event: 'change',
  }
}
</script>

<style scoped>

</style>
