<template>
  <div>
    <a-tree-select
      v-if="editable"
      :value="idValue"
      :get-popup-container="() => this.$parent.$el"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      placeholder="请选择"
      :tree-data="computedTreeData"
      allow-clear
      :tree-default-expand-all="defaultExpandAll"
      :replace-fields="replaceFields"
      @change="onChange"
    >
    </a-tree-select>
    <span v-else>{{ getDisplayValue(value) }}</span>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import findAncestorComponent from '@/common/services/find-ancestor-component'
import components from './_import-components/km-tree-select-import'

const processArrayInStr = {
  getDisplayValue(arr) {
    return arr.map((v) => v.name).join(', ')
  },
  parseBackendValue: (v) => JSON.parse(v),
  toBackendValue: (v) => JSON.stringify(v),
}
export default {
  name: 'KmTreeSelect',
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: {
      type: [Array, String],
      default: undefined,
    },
    editable: {
      type: Boolean,
      default: true,
    },
    treeDataUrl: {
      required: true,
      type: String,
      default: '',
    },
    // 默认展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      replaceFields: {
        title: 'text',
        value: 'id',
        key: 'id',
      },
      treeData: [],
    }
  },
  computed: {
    idValue() {
      if (this.value) {
        if (Array.isArray(this.value)) {
          return this.value[0].id
        } else {
          return JSON.parse(this.value)[0].id
        }
      } else {
        return undefined
      }
    },
    // 为了远程数据还未加载时显示text新增的
    computedTreeData() {
      if (this.treeData.length === 0) {
        if (this.value) {
          if (Array.isArray(this.value)) {
            return this.value.map((item) => {
              return { id: item.id, text: item.name }
            })
          } else {
            return JSON.parse(this.value).map((item) => {
              return { id: item.id, text: item.name }
            })
          }
        } else {
          return []
        }
      } else {
        return this.treeData
      }
    },
  },

  created() {
    // 只读模式不调接口
    if (this.editable) {
      this.loadData()
    }

    // 自动处理 parseBackendValue 等
    const item =
      findAncestorComponent(this, 'SdFormItemInner') ||
      findAncestorComponent(this, 'SdFormItemTdInput')
    if (!item || Array.isArray(item.name)) return
    this.SdFormContext.fieldOptions[item.name] = {
      ...this.SdFormContext.fieldOptions[item.name],
      ...processArrayInStr,
      dataType: 'array',
    }
    this.SdFormContext.fieldOptions = { ...this.SdFormContext.fieldOptions }
    this.SdFormContext.parseBackendValue(item.name)
  },
  inject: {
    SdFormContext: { default: () => ({}) },
  },
  methods: {
    loadData() {
      const req = {
        url: this.treeDataUrl,
        method: 'get',
      }
      return axios(req).then((res) => {
        if (res.data) {
          this.treeData = res.data
        }
      })
    },

    onChange(value, label, extra) {
      const treeValue = [{ id: value, name: label[0] }]
      if (value === undefined) {
        this.$emit('change')
      } else {
        this.$emit('change', treeValue)
      }
    },

    getDisplayValue(arr) {
      if (Array.isArray(arr)) {
        return arr[0].name
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
