<template>
  <el-select
    v-model="adGroupId"
    filterable
    remote
    :remote-method="searchAdGroupName"
    :style="{ width }"
    clearable
    collapse-tags
    :multiple="multiple"
    @change="changeAdGroup"
    placeholder="请选择广告组">
    <el-option v-for="info in adGroupList" :key="info.adGroupId" :label="info.adGroupName" :value="info.adGroupId"></el-option>
  </el-select>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { getAdGroupList } from './api'

interface Props {
  modelValue: string | string[]
  query: {
    profileId: string
    campaignType: string
    campaignId: string
  }
  width: string,
  multiple: boolean
}
const props = withDefaults(defineProps<Props>(), {
  width: '',
  multiple: false
})
const adGroupId = ref(props.multiple ? (Array.isArray(props.modelValue) ? props.modelValue : []) : (typeof props.modelValue === 'string' ? props.modelValue : ''))
const adGroupList = ref([])
const emits = defineEmits(['update:modelValue', 'change-ad-group'])

const searchAdGroupName = async (adGroupName: string) => {
  if (!adGroupName) {
    return
  }
  const { profileId, campaignType, campaignId } = props.query
  await setAdGroupList({ profileId, campaignType, campaignId, adGroupName })
}
const changeAdGroup = () => {
  emits('update:modelValue', adGroupId.value)
  emits('change-ad-group', adGroupId.value)
}

const setAdGroupList = async (params: any) => {
  if(!params.campaignId) return
  const resp = await getAdGroupList(params)
  adGroupList.value = resp.data
  if(adGroupList.value.length === 1) {
    adGroupId.value = adGroupList.value[0].adGroupId
    changeAdGroup()
  }
}

watch(
  [() => props.query.campaignType, () => props.query.campaignId],
  async () => {
    await setAdGroupList(props.query)
  },
  { immediate: true }
)
watch(
  () => props.modelValue,
  () => { adGroupId.value = props.multiple ? (Array.isArray(props.modelValue) ? props.modelValue : []) : (typeof props.modelValue === 'string' ? props.modelValue : '') }
)

</script>

<style scoped></style>
