<template>
  <el-select
    v-model="campaignId"
    filterable
    remote
    :remote-method="searchCampaignName"
    :style="{ width }"
    clearable
    @change="changeCampaign"
    placeholder="请选择广告活动">
    <el-option v-for="info in campaignList" :key="info.campaignId" :label="info.campaignName" :value="info.campaignId"></el-option>
  </el-select>
</template>

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

interface Props {
  modelValue: string
  query: {
    profileId: string
    campaignType: string
  }
  width: string
}

const props = withDefaults(defineProps<Props>(), {
  width: '',
})
const campaignId = ref(props.modelValue)
const emits = defineEmits(['update:modelValue', 'change'])
const campaignList = ref([])

const setCampaignList = async (params: any) => {
  const resp = await getCampaignList(params)
  campaignList.value = resp.data
}

const searchCampaignName = async (campaignName: string) => {
  if (!campaignName) return
  await setCampaignList({ profileId: props.query.profileId, campaignType: props.query.campaignType, campaignName })
}

const changeCampaign = () => {
  emits('update:modelValue', campaignId.value)
  emits('change', campaignId.value)
}


watch(
  () => props.query.campaignType,
  async () => {
    await setCampaignList(props.query)
  },
  { immediate: true }
)
watch(
  () => props.modelValue,
  () => { campaignId.value = props.modelValue }
)
</script>

<style scoped></style>
