<template>
  <div>
    <a-select
      v-if="editable"
      :get-popup-container="() => this.$parent.$el"
      :value="arrayValue"
      mode="tags"
      :token-separators="[',']"
      :show-arrow="true"
      @change="change"
    >
      <a-select-option v-for="item in listData" :key="item" :value="item">
        {{ item }}
      </a-select-option>
    </a-select>
    <span v-else>{{ getDisplayValue(value) }}</span>
  </div>
</template>

<script>
import findAncestorComponent from '@/common/services/find-ancestor-component'
import PageService from '@/common/services/page-service'
import components from './_import-components/km-tag-picker-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: 'KmTagPicker',
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    /**
     * 已选中的值
     */
    value: {
      type: [Array, String],
      default: undefined,
    },

    editable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return { listData: [] }
  },
  computed: {
    arrayValue() {
      if (this.value) {
        if (Array.isArray(this.value)) {
          return this.value
        } else {
          return JSON.parse(this.value)
        }
      } else {
        return []
      }
    },
  },
  created() {
    // 只读模式不调接口
    if (this.editable) {
      this.getData()
    }

    // 自动处理 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: {
    change(value, ...rest) {
      this.$emit('change', value, ...rest)
    },
    // 获取标签接口
    getData() {
      const params = {
        columns: 'id,name',
        expressions: [],
        formId: 'kmTag',
        maxResults: -1,
        startPosition: 0,
      }
      PageService.getList(params).then((res) => {
        this.listData = res.data.data.map((item) => {
          return item.name
        })
      })
    },

    getDisplayValue(arr) {
      if (Array.isArray(arr)) {
        return arr.join(', ')
      }
    },
  },
}
</script>

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