<template>
  <div>
    <div :class="titleClass">
      <span class="custom-title-icon"></span>
      条件
    </div>
    <ConditionGroup
      ref="condiGroupRef"
      :disabled="disabled"
      v-for="(info, index) of condiGroups"
      :candidate-fields="candidateFields"
      :data="info"
      :key="info.key"
      :showDelGroupBtn="condiGroups.length > 1 && !disabled"
      @delete-group="delGroup(info.key)" />
  </div>
  <el-button type="success" @click="addConditionGroup" style="margin: 5px auto; display: block" :disabled="disabled">添加条件组</el-button>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import ConditionGroup from './condition-group2.vue'
import { useSymbolOptions } from '/@/components/conditionBuilder/utils'
import XEUtils from 'xe-utils'

interface Props {
  candidateFields: CandidateField[]
  data: ConditionGroupItem[]
  disabled: boolean
  titleClass: string
}
const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  titleClass: 'asj-h3',
  candidateFields: () => {
    return [
      { label: '曝光量', value: 'impressions' },
      { label: '点击量', value: 'clicks' },
      { label: '花费', value: 'spend', prefix: '$' },
      { label: '点击率', value: 'ctr', suffix: '%' },
      { label: '单次点击费用', value: 'cpc', prefix: '$' },
      { label: '转化率', value: 'cr', suffix: '%' },
      { label: '广告订单数', value: 'order' },
      { label: '广告销售额', value: 'sale', prefix: '$' },
      { label: 'ACOS', value: 'acos', suffix: '%' }
    ]
  },
})
const condiGroups = ref(props.data)
const condiGroupRef = ref()
const { getSymbolOptions } = useSymbolOptions(props.candidateFields)

const buildConditionGroup = () => {
  const field = props.candidateFields[0].value
  const symbol = getSymbolOptions(field)[0].value
  return {
    key: Math.random().toString(36).substring(2),
    day: 1,
    exceptDay: 0,
    items: [
      {
        dataType: field,
        dayType: symbol === 'in' || symbol === 'not_in' ? '' : 'sum',
        symbol: symbol,
        num: '',
        ranges: [],
        values: [],
      },
    ],
  }
}
const addConditionGroup = () => {
  condiGroups.value.push(buildConditionGroup())
}
if (condiGroups.value.length === 0) {
  addConditionGroup()
}

const delGroup = (key: string) => {
  XEUtils.remove(condiGroups.value, (item) => item.key === key)
}
const validate = async () => {
  const ret = []
  if (!condiGroupRef.value) return ret
  for (const info of condiGroupRef.value) {
    ret.push(await info.validate())
  }
  // console.log(52, ret)
  return ret
}

watch(
  () => props.data,
  () => {
    condiGroups.value = props.data
  },
  { deep: true }
)

defineExpose({ validate, addConditionGroup })
</script>

<style scoped>
.custom-title-icon {
  padding-right: 10px;
}

.custom-title-icon:before {
  content: '';
  width: 4px;
  height: 15px;
  background: #3569d6;
  position: absolute;
  transform: translateY(25%);
}
</style>
