<template>
    <div
        class="field-group"
    >
        <div
            class="operator"
        >
            <!-- 运算符 -->
            <info-select
                v-if="groupIndex !== '0'"
                :row="andOr"
                :modelData="modelData"
            />
            <el-button
                type="text"
                :icon="Plus"
                :disabled="disableAdd"
                @click="addField"
            >{{ $t('addCondition') }}</el-button>
            <el-button
                type="text"
                :icon="Plus"
                :disabled="disableAdd"
                @click="addFieldGroup"
            >{{ $t('addConditionGroup') }}</el-button>
            <el-button
                v-if="!groupIndex.endsWith('0')"
                type="text"
                :icon="Minus"
                @click="removeFieldGroup"
            >{{ $t('deleteConditionGroup') }}</el-button>
            <el-button
                v-if="groupIndex === '0'"
                type="text"
                :icon="Delete"
                @click="clearFieldGroup"
            >{{ $t('clearConditions') }}</el-button>
        </div>
        <template
            v-for="(field, index) of modelData.fields"
        >
            <div
                v-if="field.type === 'Field'"
                :key="field.key"
                class="fields"
            >
                <field-vue
                    :index="index"
                    :field="field"
                    :searchList="searchList"
                    :columnI18n="columnI18n"
                    :validate="validate"
                    @pullSql="$emit('pullSql')"
                />
                <el-tooltip
                    :content="$t('deleteCondition')"
                    effect="light"
                >
                    <el-button
                        v-if="modelData.fields.length > 1"
                        type="text"
                        :icon="Remove"
                        @click="removeField(index)"
                    />
                </el-tooltip>
            </div>
            <field-group
                v-else
                :key="field.key"
                :groupIndex="groupIndex + index"
                :searchList="searchList"
                :columnI18n="columnI18n"
                :modelData="field"
                :rootCount="!!rootCount ? rootCount : count"
                @count="getCount"
                @removeFieldGroup="handleRemoveFieldGroup"
                @pullSql="$emit('pullSql')"
            />
        </template>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onUpdated } from 'vue'
import { Plus, Minus, Remove, Delete } from '@element-plus/icons-vue'
import infoSelect from '../../form/select/index.vue'
import fieldVue from './field.vue'
import { uniqueId } from 'lodash-es'

const props = defineProps({
    modelData: { // FieldGroup
        type: Object,
        default: () => {
            // fields: []
        }
    },
    groupIndex: {
        type: String,
        default: '0' // 如: '01' '110' '122'
    },
    searchList: {
        type: Array,
        default: () => {}
    },
    columnI18n: {
        type: Boolean,
        default: true
    },
    rootCount: {
        type: Number,
        default: NaN
    },
    validate: { // 是否校验
        type: Boolean,
        default: true
    }
})
const emit = defineEmits(['pullSql', 'removeFieldGroup', 'count'])
/* data */
const count = ref(1)
const andOr = {
    label: '',
    model: 'andOr',
    type: 'infoSelect',
    disabled: () => props.groupIndex.endsWith('0'),
    // disabled: () => this.groupIndex === '0',
    clearable: false,
    placeholder: () => 'pleaseSelectOperator',
    options: () => [{
        label: 'and',
        value: 'AND'
    }, {
        label: 'or',
        value: 'OR'
    }],
    i18n: true,
    methods: () => {
        emit('pullSql')
    }
}

/* computed */
const disableAdd = computed(() => {
    return props.rootCount >= 10 || count.value >= 10
})


onUpdated(() => {
    count.value = sum(props.modelData.fields)
})

/* methods */
// 增删group
const addFieldGroup = () => {
    let group = {
        type: 'FieldGroup',
        group: true,
        key: uniqueId('group_'),
        andOr: 'AND',
        fields: [
            {
                type: 'Field',
                group: false,
                key: uniqueId('field_'), // 固定key
                andOr: 'AND',
                name: '',
                oper: '',
                value: ''
            }
        ]
    }
    props.modelData.fields.push(group)
    getCount(1)
}
const clearFieldGroup = () => {
    props.modelData.fields.splice(0)
    emit('pullSql')
}
const removeFieldGroup = () => {
    const count = sum(props.modelData.fields)
    getCount(-count)
    // this.modelData.fields = []
    // 从父级fields中移除
    emit('removeFieldGroup', props.groupIndex.substr(-1))
    emit('pullSql')
}
const handleRemoveFieldGroup  = (index) => {
    props.modelData.fields.splice(index, 1)
}
// 添加条件
const addField = () =>{
    let field = {
        type: 'Field',
        group: false,
        key: uniqueId('field_'), // 固定key
        andOr: 'AND',
        name: '',
        oper: '',
        value: ''
    }
    // this.modelData.fields.push(field)
    const targetIndex = props.modelData.fields.findIndex(f => f.type === 'FieldGroup')
    if (targetIndex >= 0) {
        props.modelData.fields.splice(targetIndex, 0, field)
    } else {
        props.modelData.fields.push(field)
    }
    getCount(1)
}
// 删除条件
const removeField = (index) => {
    props.modelData.fields.splice(index, 1)
    getCount(-1)
    if (index === 0) {
        props.modelData.fields[0].andOr = 'AND' // 新0
    }
    emit('pullSql')
}
const getCount = (num) => {
    count.value += num
    emit('count', num)
}
const sum = (fields) => {
    return fields.reduce((total, item) => {
        let count = 0
        if (item.type === 'FieldGroup') {
            count = sum(item.fields)
        } else {
            count = 1
        }
        return total + count
    }, 0)
}

</script>

<style lang="scss" scoped>
.field-group {
    .field-group { // 从第二层开始
        .fields, .field-group {
            margin-left: 20px;
        }
        .operator {
            margin-bottom: 10px;
        }
    }
    .fields {
        &::after {
            content: "";
            display: block;
            clear: both;
        }
        .field {
            float: left;
            width: calc(100% - 16px);
        }
    }
    .operator {
        display: flex;
        width: calc(100% - 36px);
        .info-select {
            width: 20%;
            margin-right: 5px;
        }
    }
}
</style>
