<template>
    <div class="ui-checkbox-group" :class="ui">
        <template v-for="item in checkboxDatas" :key="item.key">
            <el-checkbox :checked="item.checked" size="large" @change="onCheckboxChange($event, item)">{{item.name}}</el-checkbox>
        </template>
    </div>
</template>

<script setup>
import {ref, nextTick, watch} from 'vue'
import { ElCheckbox } from 'element-plus'
import { isNullAll, deepClone, getIndex } from "vue-utils-plus"
const props = defineProps({
    ui: {
        type: String,
        default: ''
    },
    datas: {
        type: Array,
        default: () => ([])
    },
    objs: {
        type: Array,
        default: () => ([])
    },
    val: {
        type: [String,Number],
        default: ''
    },
    keyname: {
        type: [String,Number],
        default: ''
    },
})

//变量
const checkboxDatas = ref([])

//渲染完成
nextTick(() => {
    setInitDatas(deepClone(props.datas), deepClone(props.objs))
})

//监听表头
watch(() => [
    props.val
], ([val]) => {
    setModelVal(val)
})

//处理初始数据
const setInitDatas = (datas, objs) => {
    for (let i = 0; i < datas.length; i++) {
        objs.push({key: String(datas[i]), name: datas[i]})
    }
    checkboxDatas.value = objs
    setModelVal(props.val)
}

//处理数据
const setModelVal = (val) => {
    const datas = deepClone(checkboxDatas.value)
    if (!isNullAll(val)) {
        const arr = String(val).split(',')
        for (let i = 0; i < arr.length; i++) {
            const item = String(arr[i])
            const index = getIndex(datas, 'key', item)
            datas[index].checked = true
        }
    }
    checkboxDatas.value = datas
}

//事件
const emit = defineEmits(['change'])

//当绑定值变化时触发的事件
const onCheckboxChange = (val, item) => {
    item.checked = val
    getCheckedValue()
}

//取选中的值
const getCheckedValue = () => {
    let valString = '';
    const datas = checkboxDatas.value
    for (let i = 0; i < datas.length; i++) {
        if (datas[i].checked) {
            const key = String(datas[i].key)
            valString = valString ? `${valString},${key}`: key
        }
    }
    //事件返回
    emit('change', {
        key: props.keyname,
        val: valString
    })
}
</script>
