<template>
  <div style="width:100%">
    <a-select v-model="project" style="width:100%" mode="multiple" @change="projectChange">
      <a-select-option v-for="(item, i) in optionsData" :key="i" :value="item[field.key]">{{
        item[field.name]
      }}</a-select-option>
      <a-select-option key="2" value="2">被审计单位</a-select-option>
    </a-select>
  </div>
</template>

<script>
import components from './_import-components/audit-project-select-import'

export default {
  name: 'AuditProjectSelect',
  metaInfo: {
    title: 'AuditProjectSelect',
  },
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    options: {
      type: Array,
      default: () => [],
    },
    field: {
      type: Object,
      default: () => ({
        key: 'id',
        name: 'name',
      }),
    },
  },
  data() {
    return {
      project: ['allOptionKey'],
      optionsData: [],
      initObj: {},
    }
  },
  watch: {
    options(val) {
      if (this.options.length) {
        this.optionsData = [this.initObj, ...this.options]
      }
    },
  },
  mounted() {
    this.initObj[this.field.key] = 'allOptionKey'
    this.initObj[this.field.name] = '全部项目'
  },
  methods: {
    projectChange(value) {
      // 如果是value最后一位则清除其他选项否则取消全部选项
      if (value[value.length - 1] === 'allOptionKey') {
        this.project = ['allOptionKey']
        this.$emit(
          'change',
          this.options.map((item) => item[this.field.key])
        )
      } else {
        this.project = value.filter((item) => item !== 'allOptionKey')
        this.$emit('change', this.project)
      }
    },
  },
}
</script>

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