<template>
  <a-tree-select :show-search="true" :allow-clear="true" :tree-data="datas" v-model:value="value"
    :mode="multiple ? 'multiple' : undefined" :disabled="see || disabled" tree-node-filter-prop="label" :treeLine="true"
    :fieldNames="fieldNames" class="paas-select" :tree-default-expand-all="open" :placeholder="placeholder" style="width: 100%;" v-bind="$attrs"></a-tree-select>
</template>
<script>
export default {
  name: "PaasTree",
  inheritAttrs: false, // 禁用自动继承，手动控制透传
  props: {
    placeholder: {
      type: String,
      default: "",
    },
    multiple: {
      default: false,
    },
    fieldNames: {
      type: Object,
      default: { children: 'children', title: 'label', key: 'value' }
    },
    disabled: {
      default: false,
    },
    open: {
      type: Boolean,
      default: false,
    },
    modelValue: {
    },
    params: {},
    url: "",
    listToTree: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      value: null,
      datas: [],
      isInternalUpdate: false, // 防止watch重复触发
    }
  },
  mounted() {
    this.getTreeData();
    if (this.modelValue) {
      if (typeof this.modelValue === 'string' && this.modelValue.includes(',')) {
        this.value = this.modelValue.split(',');
      } else {
        this.value = Array.isArray(this.modelValue) ? this.modelValue : [this.modelValue];
      }
    } else {
      this.value = this.modelValue;
    }
  },
  computed: {
    see() {
      return this.$store.forms.see;
    }
  },
  watch: {
    modelValue(newValue) {
      this.isInternalUpdate = true;
      if (newValue == null) newValue = "";

      let valueList = [];
      if (Array.isArray(newValue)) {
        newValue.forEach(value => {
          if (value == "") return;
          valueList.push(String(value));
        });
        this.value = valueList;
      } else if (typeof newValue === 'string' && newValue?.includes(",")) {
        newValue.split(",").forEach(value => {
          if (value == "") return;
          valueList.push(String(value));
        });
        this.value = valueList;
      } else {
        if (this.multiple && !!newValue) {
          this.value = [String(newValue)];
        } else {
          this.value = String(newValue);
        }
      }
      this.$nextTick(() => {
        this.isInternalUpdate = false;
      });
    },
    value(newVal) {
      // 防止外部modelValue变化导致的重复触发
      if (this.isInternalUpdate) {
        return;
      }
      this.$emit("update:modelValue", newVal);
    }
  },
  methods: {
    async getTreeData() {
      let res = await this.$post(this.url, { page: { current: 1, size: 1000000 }, ...this.params });
      if (this.listToTree) {
        this.datas = this.$listToTree(res.data.data.rows);
      } else {
        this.datas = res.data.data.rows;
      }
    },
  },
};
</script>

<style>
.paas-select {
  min-width: 180px;
}
</style>
