<script setup>
import { SemiSelect } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useEvent } from '../composables/useEvent'
import { getEventFunnel, saveEventFunnel } from '../api'

const emit = defineEmits(['update:modelValue'])
const { eventList } = useEvent()
const rules = ref([])

async function fetchConfig() {
  const res = await getEventFunnel()
  rules.value = res.data.items
}
onMounted(() => {
  fetchConfig()
})

function handleAdd() {
  rules.value.push({ id: '0', event_id: '', sort: 0, name: '' })
}

function handleRemove(index) {
  rules.value.splice(index, 1)
}

async function handelSubmit() {
  const paramsRules = rules.value.map((item, index) => {
    return { ...item, sort: index + 1 }
  })
  await saveEventFunnel({ rules: paramsRules })
  ElMessage.success('保存成功')
  emit('update:modelValue', false)
}
</script>

<template>
  <el-dialog title="创建营销漏斗分析" width="600" @closed="$emit('update:modelValue', false)">
    <el-button type="primary" @click="handleAdd">添加漏斗步数</el-button>
    <div class="rule-item" v-for="(item, index) in rules" :key="index">
      <el-button type="primary">{{ index + 1 }}</el-button>
      <el-input v-model="item.name" :placeholder="'漏斗第' + (index + 1) + '步名字'"></el-input>
      <el-select placeholder="请选择事件" v-model="item.event_id">
        <el-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-button :icon="SemiSelect" @click="handleRemove(index)"></el-button>
    </div>
    <template #footer>
      <el-button type="primary" @click="handelSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.rule-item {
  margin: 10px 0;
  gap: 10px;
  display: flex;
}
</style>
