<script setup lang="ts">
import { Warning } from '@element-plus/icons-vue'
import { ElInput } from 'element-plus'
import UserRule from '@/components/rule/UserRule.vue'
import EventRule from '@/components/rule/EventRule.vue'
import UserActionRule from '@/components/rule/UserActionRule.vue'

const rules = defineModel<Array<any>>({ default: [] })

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const activeIndex = ref(0)

const handleClose = (index: number) => {
  rules.value.splice(index, 1)
  activeIndex.value = 0
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    rules.value.push({
      level: rules.value.length,
      level_name: inputValue.value,
      user_attr_rule: { current_logic_operate: 'and', items: [] },
      event_attr_rule: { current_logic_operate: 'and', items: [] },
      user_action_rule: { current_logic_operate: 'and', items: [] }
    })
    activeIndex.value = rules.value.length - 1
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<template>
  <p class="rule-tips">
    <el-icon><Warning /></el-icon>
    分层标签：将满足不同分层规则的用户打上分层标签，同一用户会被优先匹配在顺序靠前的分层
  </p>
  <div>
    <el-tag
      class="rule-tag"
      v-for="(rule, index) in rules"
      size="large"
      effect="light"
      :type="index !== activeIndex ? 'info' : 'primary'"
      :key="rule.level"
      closable
      :disable-transitions="false"
      @close="handleClose(index)"
      @click="activeIndex = index">
      {{ rule.level_name }}
    </el-tag>
    <el-input v-model="inputValue" class="rule-input" ref="InputRef" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" v-if="inputVisible" />
    <el-button v-else style="width: 100px" @click="showInput"> + 添加分层 </el-button>
  </div>
  <template v-if="rules.length">
    <!-- 用户属性规则 -->
    <UserRule v-model="rules[activeIndex].user_attr_rule" style="margin-top: 20px"></UserRule>
    <!-- 事件属性规则 -->
    <EventRule v-model="rules[activeIndex].event_attr_rule" style="margin-top: 20px"></EventRule>
    <!-- 用户行为序列规则 -->
    <UserActionRule v-model="rules[activeIndex].user_action_rule" style="margin-top: 20px"></UserActionRule>
  </template>
</template>

<style src="@/assets/styles/rule.scss"></style>
