<script setup lang="ts">
import type { GroupRule } from '@/types'
import { PriceTag, Plus, CloseBold } from '@element-plus/icons-vue'
import { useGroup } from '@/composables/useAllData'

const rule = defineModel<GroupRule>({ default: { current_logic_operate: 'and', items: [] } })

const { buttonText = '添加条件' } = defineProps<{
  buttonText?: string
}>()

const { groupList } = useGroup()

// 获取逻辑运算符名称
function getLogicalName(value: 'and' | 'or') {
  return value === 'or' ? '或' : '且'
}

// 切换逻辑运算符
function toggleOperate(rule: GroupRule) {
  rule.current_logic_operate = rule.current_logic_operate === 'or' ? 'and' : 'or'
}

// 添加条件
function handleAdd(items: any[]) {
  items.push({ tag_id: '' })
}

// 删除
function handleRemove(items: any[], index: number) {
  items.splice(index, 1)
}
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <slot name="header">
        <el-button circle color="#567722" :icon="PriceTag"></el-button>
        群组满足以下条件
      </slot>
    </template>
    <div class="rule" v-if="rule.items.length">
      <div class="rule-operator">
        <span @click="toggleOperate(rule)">{{ getLogicalName(rule.current_logic_operate) }}</span>
      </div>
      <div class="rule-list">
        <el-row justify="space-between" class="rule-item" v-for="(item, index) in rule.items" :key="index">
          <div>
            群组 等于
            <el-form-item>
              <el-select v-model="item.tag_id" style="width: 300px">
                <el-option
                  v-for="option in groupList"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-button text :icon="CloseBold" @click="handleRemove(rule.items, index)"></el-button>
        </el-row>
      </div>
    </div>
    <el-button text :icon="Plus" @click="handleAdd(rule.items)">{{ buttonText }}</el-button>
  </el-card>
</template>

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