<template>
    <ie-form-picker :label="rule.label" :remark="rule.description">
        <uv-checkbox-group v-model="formModel[rule.fieldName]" @change="checkMutex($event),clearValidate()">
            <uv-checkbox v-for="item in columnsWithMutex" :key="getValue(item)" :label="getLabel(item)"
                         :name="getValue(item)" :customStyle="{width: 'fit-content'}"/>
        </uv-checkbox-group>
    </ie-form-picker>
</template>

<script>
import _ from 'lodash';
import AiFormFieldPicker from "@/pagesOther/pages/ie/components/ai-form/items/templates/ai-form-field-picker.vue";

export default {
    name: "ai-form-field-checkbox",
    extends: AiFormFieldPicker, // 选项与picker一致，但呈现是checkbox-group
    data() {
        return {
            lastChecked: []
        }
    },
    computed: {
        columnsWithMutex() {
            const mutex = this.rule.mutexOption
            return mutex ? [mutex, ...this.columns] : this.columns
        }
    },
    methods: {
        checkMutex(val) {
            const mutex = this.rule.mutexOption
            if (!mutex) return // nothing should be checked.
            let mutexValues = val
            if (this.lastChecked.length < val.length) {
                // only need to check new checked item
                const [newChecked] = _.difference(val, this.lastChecked)
                if (newChecked == mutex) {
                    mutexValues = [mutex]
                } else if (val.includes(mutex)) {
                    mutexValues = _.difference(val, [mutex])
                }
            }

            this.lastChecked = mutexValues
            setTimeout(() => {
                // NOTE: can not set `formModel` properties in `change` event directly,
                // setTimeout make reactive feature available until last interactive completed.
                console.log('check mutex and try to set formModel', this.rule.fieldName, mutexValues)
                this.formModel[this.rule.fieldName] = mutexValues
            }, 50)
        }
    }
}
</script>

<style scoped>
::v-deep .uv-checkbox-group--row {
    flex-wrap: wrap;
    justify-content: flex-end;
    gap: 10px;
    width: fit-content;
}
</style>