<template>
<!--  v-if 解决数据回显问题-->
  <el-cascader v-if="show" ref="cascader" v-model="cascaderValue" :props="props" v-bind="options" @change="handleChange"></el-cascader>
</template>
<script>

import { CountryDeptList } from "@/api/system/region";
export default {
  name: 'regionCascaderSelect',
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    //回显数据
    value: {
      type: [Array, String, Object],
      default: () => []
    },
    valueProp: {
      type: String,
      default: 'id'
    },
    //是否严格的遵守父子节点不互相关联  true:可以选择任意一级。flase:选择最后一级
    checkStrictly: {
      type: Boolean,
      default: true,
    },
    opts: {
      type: Object,
      default: () => ({})
    },
    //选中节点的数据
    checked: {
      type: Object,
      default: null
    },
    endLevel: {
      type: [Number, String],
      default: 4
    },
    startLevel: {
      type: [Number, String],
      default: 0
    },
  },
  watch: {
    checkStrictly(newVal){
      this.props.checkStrictly = newVal;
    },
    value:{
      handler(newVal, oldVal){
        if (this.isCascaderValueChange){
          this.isCascaderValueChange = false;
          return;
        }
        // console.log('newVal --> ', newVal);
        this.setCascaderValue(newVal);
      },
      immediate: true,  //刷新加载 立马触发一次handler
      deep: true
    }
  },
  mounted(){
    let defaultOpts = {
      placeholder: '请选择所属区划',
      'popper-class': 'cascader-popper region-cascader',
      clearable: true
    };
    this.options = {
      ...defaultOpts,
      ...this.opts
    };
    this.props.checkStrictly = this.checkStrictly;
  },
  data(){
    return {
      options: {},
      show: true, //为了解决数据回显问题引入
      cascaderValue: [],//级联组件的值
      isCascaderValueChange: false,//是否为级联组件主动触发的change事件
    }
  },
  computed: {
    props(){
      return {
        lazy: true,
        checkStrictly: true,
        lazyLoad: async (node, resolve) => {
          const { level } = node;
          let params = level === 0 ? '' : {parentId: node.data.nodeData.id};
          let response= await CountryDeptList(params);
          let code = response.code;
          let data = response.data || response.rows;
          if (code !== 200) {
            this.$message.error('获取行政区划数据失败！');
            resolve([]);
            return;
          }
          let res = data.map(item => {
            let value = String(item[this.valueProp]);
            let disabled = level < this.startLevel;
            let endLevel =  this.endLevel;
            return {
              disabled,
              label: item.name,
              value,
              leaf: level >= endLevel,
              nodeData: item
            }
          });
          resolve(res);
        },
      }
    }
  },
  created() {
  },
  methods: {
    handleChange(value){
      this.isCascaderValueChange = true;
      this.$emit('changeValue', value);
      //将被选中的节点的信息传递出去 👇
      let checkedNode = this.$refs.cascader.getCheckedNodes();
      checkedNode = checkedNode.length > 0 ? checkedNode[0]['data']['nodeData'] : null;
      this.$emit('update:checked', checkedNode);
    },
    setCascaderValue(newVal){
      this.show = false;
      let values = newVal || [];
      if (typeof values === 'string') {
        //如果赋值是 json 格式
        values = JSON.parse(values);
      }
      this.cascaderValue = [...values];
      this.$nextTick(() => {
        this.show = true;
      });
    },
    getCheckedNodes(){
      return this.$refs.cascader.getCheckedNodes();
    },
  }
}
</script>
<style lang="scss">

</style>
