<template>
    <div class="kf-3dc-atom w-100 h-100" :style="buttonStyle" ref="buttonBox" v-show="props.show" :class="'vivify ' + buttonClass">
        <div class="kf-3dc-atom-item"
             :class="[props.currValueIndex===index?'kf-3dc-atom-item-active':'']"
             v-show="btnDataList?.length > 0" v-for="(item, index) in btnDataList" :key="item + index + btnVersion"
             :style="getStyle(item,index)" @click="handleClick(item, $event,index)">
            {{ item }}
        </div>
    </div>
</template>

<script>
import {
    onMounted,
    ref,
    getCurrentInstance,
    computed,
    watch,
    nextTick,
} from "vue";
import styleManager from "../utils/style.vue";
import eventManager from "../utils/event";
import propManager from "../utils/props";
import pageModel from "../model/page";
import dataModel from "@/components/ui/model/data";
import stateManager from "@/components/ui/utils/state";
import colorModel from "../model/color";
import  themeModel from '../model/theme'

export default {
    name: "kfButtonGroup",
    props: {
        props: {
            type: Object,
            default: () => {},
        },
        eventList: {
            type: Array,
            default: () => [],
        },
        eventScript: {
            type: String,
        },
    },
    widgetConfig: {
        parent: "base",
        rank: 3,
        label: {
            zh: Kf.t('ButtonGroup')
        },
        display: true,
        category: Kf.t('Foundation'),
        component: "kfButtonGroup",
        version: 1,
        icon: "icon-anniu",
        defaultSize: {
            x: 180,
            y: 32,
        },
        imgName: "kfButtonGroup",
        state: {
            isAdd: false,
            isCondition: false,
        },
    },
    setup(props) {
        let btnVersion=ref(0)
        let bindDevice = null,
            bindModel = null;
        let newData = ref("");
        let buttonBox = ref(null);
        let buttonStyle = ref({});
        const { proxy } = getCurrentInstance();
        let defaultHandler = ref({});
        let buttonClass = ref("");
        watch(themeModel.currTheme,() =>{
            btnVersion.value++
        })
        onMounted(() => {
            refreshEvents();
            defaultSel();
            buttonStyle.value = styleManager.updateStyle(proxy);
            buttonClass.value = styleManager.updateClass(proxy);
            let currValIndex = propManager.getCurrValue(
                props,
                "currValueIndex"
            );
            if (currValIndex === undefined) {
                pageModel.updateSelectionPropValue("currValueIndex", 0);
            }
        });
        const refreshEvents = function (firstTime = false) {
            eventManager.registerEvent(proxy);
        };

        let dataVersion = ref(0);
        const updateData = function () {
            dataVersion.value = new Date().getTime();
        };

        const btnDataList = computed(() => {
            const { deviceId, deviceData } = props.props;
            if (!deviceId || deviceId == "") {
                return props.props.btnDataList;
            }
            if (!bindDevice) {
                bindDevice = dataModel.getDataSourceByDeviceId(deviceId);
                bindModel = dataModel.getDeviceModelByDevice(bindDevice);
            }
            if (!bindDevice || !bindModel) {
                return props.props.btnDataList;
            }
            if (deviceId && deviceData && bindModel) {
                const prop = bindModel.properties.find(
                    (p) => p.name === deviceData
                );
                if (prop?.enumItems && prop.enumItems.length > 0) {
                    const enums = prop.enumItems;
                    props.props.btnDataList = enums.map(
                        (enu) => enu.label.zhCN
                    );
                }
            }
            if ((dataVersion.value > 0 || props.props.pageType===1) && props.props.deviceData) {
                let changeData = dataModel.getData(props.props, false, false);
                if (changeData != undefined) {
                    newData.value = changeData;
                }
            }
            return props.props.btnDataList;
        });

        const doControl = (index) => {
            let list = props.props.btnDataList;
            const { deviceId, deviceData } = props.props;
            if (!deviceId || deviceId == "") {
                return;
            }
            if (!bindDevice) {
                bindDevice = dataModel.getDataSourceByDeviceId(deviceId);
                bindModel = dataModel.getDeviceModelByDevice(bindDevice);
            }
            if (!bindDevice || !bindModel) {
                return;
            }
            if (deviceId) {
                if (deviceData && typeof deviceData === "string" && bindModel) {
                    const prop = bindModel.properties.find(
                        (p) => p.name === deviceData
                    );
                    if (prop?.controllable && prop?.enumItems) {
                        let value = "";
                        // if (index + 1 >= list.length) {
                        //     value = list[0];
                        // } else {
                        //     value = list[index + 1];
                        // }
                        value = prop.enumItems[index].value;
                        dataModel.doControl(
                            props,
                            bindDevice,
                            bindModel,
                            value,
                            deviceData
                        );
                    }
                }
            }
        };

        watch(newData, (newValue, oldValue) => {
            nextTick(() => {
                // stateManager.onDataChange(props, newValue);
                let index = props.props.btnDataList.findIndex(
                    (item) => item === newValue
                );
                if (index >= 0) {
                    pageModel.updatePropValue("currValue", newValue, props);
                    pageModel.updatePropValue("currValueIndex", index, props);
                }
            });
        });

        const defaultSel = function () {
            if (props?.props?.currValue) {
                doSelected(props.props.currValue);
            }
        };
        /*  watch(props, (newValue, oldValue) => {
      refreshEvents();
      buttonStyle.value = styleManager.updateStyle(proxy)
        buttonClass.value=styleManager.updateClass(proxy)
    });*/

        pageModel.watchProps(props, watch, proxy, (changes) => {
            if (styleManager.styleChanged("kfButtonGroup", changes)) {
                buttonStyle.value = styleManager.updateStyle(proxy);
            }
            if (styleManager.classChanged("kfButtonGroup", changes)) {
                buttonClass.value = styleManager.updateClass(proxy);
            }
            if (changes && changes["currValue"]) {
                doSelected(props.props.currValue);
            }
            if (changes && changes["deviceId"]) {
                // 组件绑定的数据ID变化，需要请求新的设备数据和对应的物模型
                bindDevice = dataModel.getDataSourceByDeviceId(
                    props.props.deviceId
                );
                if (bindDevice) {
                    bindModel = dataModel.getDeviceModelByDevice(bindDevice);
                }
            }
        });
        const handleClick = function (value, event, index) {
            try {
                pageModel.updatePropValue("currValue", value, props);
                pageModel.updatePropValue("currValueIndex", index, props);
                eventHandler.value.click(value, event, value);
                doControl(index);
            } catch (e) {
                console.error(e);
            }
        };
        const eventHandler = computed(() => {
            return eventManager.loadEventHandler(
                defaultHandler,
                undefined,
                props.props.pageName
            );
        });

        const doSelected = function (value) {
            if (eventHandler.value?.selected) {
                eventHandler.value.selected(value, event, value);
            }
        };

        const getStyle = function (item, index) {
            let style = {};
            if (props.props) {
                style.backgroundColor = props.props.unSelectedbg
                    ? props.props.unSelectedbg
                    : "transparent";
                style.borderColor = props.props.unSelectedBorderColor
                    ? props.props.unSelectedBorderColor
                    : "transparent";
                style.borderWidth = props.props.unSelectedBorderWidth
                    ? props.props.unSelectedBorderWidth + "px"
                    : "0";
                style.borderStyle = props.props.unSelectedBorderStyle
                    ? props.props.unSelectedBorderStyle
                    : "none";
                style.color = props.props.unSelectedColor
                    ? colorModel.getColor(props.props.unSelectedColor)
                    : "#e4e4e4";
                style.borderRadius = props.props.unSselectedBorderRadius
                    ? props.props.unSselectedBorderRadius + "px"
                    : "0px";
                /*if (props.props?.autoAdjust == "auto" || props.props?.flexDirection=='row') {
                    style.width = 100 / props.props.btnDataList.length + "%";
                }else{
                    style.width='100%'
                }*/
                style.width='100%'
                let currVal = propManager.getCurrValue(props, "currValue");
                let currValIndex = propManager.getCurrValue(
                    props,
                    "currValueIndex"
                );
                /*if(currValIndex===undefined){
                    currValIndex=0;
                }*/
                if (currValIndex == index) {
                    style.backgroundColor = props.props.selectedbg
                        ? colorModel.getColor(props.props.selectedbg)
                        : "transparent";
                    style.color = props.props.selectedColor
                        ? colorModel.getColor(props.props.selectedColor)
                        : "#e4e4e4";
                    style.borderRadius = props.props.selectedBorderRadius
                        ? props.props.selectedBorderRadius + "px"
                        : "0";
                    style.borderColor = props.props.selectedBorderColor
                        ? props.props.selectedBorderColor
                        : "transparent";
                    style.borderWidth = props.props.selectedBorderWidth
                        ? props.props.selectedBorderWidth + "px"
                        : "0";
                    style.borderStyle = props.props.selectedBorderStyle
                        ? props.props.selectedBorderStyle
                        : "none";
                }
            }
            return style;
        };

        return {
            buttonBox,
            buttonStyle,
            handleClick,
            defaultHandler,
            eventHandler,
            getStyle,
            buttonClass,
            updateData,
            btnDataList,
            btnVersion
        };
    },
};
</script>

<style lang="scss">
.kf-3dc-atom {
    border-width: 0;
    border-style: solid;
    display: flex;
    padding: 0;
    flex-direction: row;
    overflow: hidden;
    transition: all 0.2s linear 0s;
    .kf-3dc-atom-item {
        height: 100%;
        background: transparent;
        border: none;
        display: flex;
        justify-content: center;
        align-items: center;
        color: inherit;
        font-size: inherit;
        border-radius: 0;
        font-family: inherit;
        cursor: pointer;
    }
}
</style>
