<template>
  <el-select :value="value" :placeholder="placeholder" clearable @change="handleCarCompanyChange">
    <el-option v-for="item in list" v-bind="item" :key="item.value" />
  </el-select>
</template>

<script>
import { queryCurrentSubOrgList, queryProtocalOrgByList } from '@/api/management'

export default {
  name: 'CarCompany',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 默认选中第一项
    default: {
      type: [String, Function],
      default: ''
    },
    // 类型，1：车企 0：所有
    type: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      list: []
    }
  },
  mounted() {
    this.queryProtocalOrgByList()
  },
  methods: {
    /**
     * 查询车厂列表
     */
    async queryProtocalOrgByList() {
      const data = await (this.type === 1 ? queryProtocalOrgByList : queryCurrentSubOrgList)()
      // 如果查询出来了车企
      if (data && data.length > 0) {
        this.list = data.map(item => {
          return {
            value: item.uuid,
            label: item.organName
          }
        })
      }
      // 如果当前需要默认选中
      if (this.default) {
        this.handleCarCompanyChange(typeof this.default === 'function' ? this.default(this.list) : this.default)
      }
    },

    /**
     * 车厂切换方法
     * @param v 当前方法
     */
    handleCarCompanyChange(v) {
      this.$emit('input', v)
      this.$emit('change', v)
    }
  }
}
</script>
