<template>
  <km-list-selector :options="listData" v-bind="$attrs" :read-only="readOnly" v-on="$listeners" />
</template>

<script>
import findAncestorComponent from '@/common/services/find-ancestor-component'
import PageService from '@/common/services/page-service'
import components from './_import-components/km-business-area-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: 'KmBusinessAreaPicker',
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    /**
     * 只读
     */
    readOnly: {
      required: true,
      type: Boolean,
      default: false,
    },
  },
  data() {
    return { listData: [] }
  },
  created() {
    // 只读模式不调接口
    if (!this.readOnly) {
      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: {
    // 获取业务领域接口
    getData() {
      const params = {
        columns: 'id,name',
        expressions: [],
        formId: 'kmDomain',
        maxResults: -1,
        startPosition: 0,
      }
      PageService.getList(params).then((res) => {
        this.listData = res.data.data
      })
    },
  },
}
</script>

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