<template>
    <div class="kf-3dc-atom-switch w-100 h-100" :style="buttonStyle" :class="'vivify '+ buttonClass" ref="buttonBox" v-show="props.show">
        <el-switch v-model="switchValue" class=""
                   :style="'--el-switch-on-color:'+ onColor+'; --el-switch-off-color: '+ offColor"
                   @change="doControl"></el-switch>
    </div>
</template>

<script>
import {
    onMounted,
    ref,
    getCurrentInstance,
    computed,
    watch,
    watchEffect,
    nextTick,
    onUnmounted,
} from "vue";
import styleManager from "../utils/style.vue";
import eventManager from "../utils/event";
import pageModel from "../model/page";
import serviceModel from "../model/service";
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: "kfSwitch",
    props: {
        props: {
            type: Object,
            default: () => {},
        },
        eventList: {
            type: Array,
            default: () => [],
        },
        eventScript: {
            type: String,
        },
    },
    widgetConfig: {
        parent: "base",
        rank: 4,
        label: {
            zh: Kf.t('Switch')
        },
        category: Kf.t('Foundation'),
        component: "kfSwitch",
        display: true,
        version: 1,
        icon: "icon-anniu",
        defaultSize: {
            x: 60,
            y: 30,
        },
        imgName: "kfSwitch",
        state: {
            isAdd: false,
            isCondition: false,
        },
    },
    setup(props) {
        let buttonClass = ref("");
        let buttonBox = ref(null);
        let buttonStyle = ref({});
        const { proxy } = getCurrentInstance();
        let defaultHandler = ref({});

        let switchValue = ref(false);

        let dataVersion = ref(0);

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


        const onColor=computed(() =>{
            return colorModel.getColor(props.props.onColor)
        })

        const offColor=computed(() =>{
            return colorModel.getColor(props.props.offColor)
        })
        let currBindingData = null,
            bindModel,
            bindDevice;

        onMounted(() => {
            refreshEvents();
            buttonStyle.value = styleManager.updateStyle(proxy);
            buttonClass.value = styleManager.updateClass(proxy);
            loadSwitchBorder();
            changePosition();
        });

        onUnmounted(() => {
            bindModel = null;
            bindDevice = null;
        });
        watch(themeModel.currTheme,() =>{
            loadSwitchBorder();
        })

        const refreshEvents = function () {
            eventManager.registerEvent(proxy);
        };

        pageModel.watchProps(props, watch, proxy, (changes) => {
            if (styleManager.styleChanged("kfSwitch", changes)) {
                buttonStyle.value = styleManager.updateStyle(proxy);
                if (
                    changes["borderColor"] != undefined ||
                    changes["borderWidth"] != undefined ||
                    changes["borderStyle"] != undefined
                ) {
                    loadSwitchBorder();
                }
                if (changes["borderWidth"] != undefined) {
                    changePosition();
                }
            }
            if (
                changes &&
                (changes.hasOwnProperty("x") ||
                    changes.hasOwnProperty("y") ||
                    changes.hasOwnProperty("width") ||
                    changes.hasOwnProperty("height"))
            ) {
                changePosition();
            }
            if (changes && changes.hasOwnProperty("borderShow")) {
                changePosition();
                loadSwitchBorder();
            }
            if (styleManager.classChanged("kfSwitch", changes)) {
                buttonClass.value = styleManager.updateClass(proxy);
            }
            if (changes && changes["deviceId"]) {
                bindDevice = dataModel.getDataSourceByDeviceId(
                    props.props.deviceId
                );
                if (bindDevice) {
                    bindModel = dataModel.getDeviceModelByDevice(bindDevice);
                }
            }
        });

        const changePosition = function () {
            let showBorder = true;
            if (
                props.props.borderShow != undefined &&
                !props.props.borderShow
            ) {
                showBorder = false;
            }
            buttonBox.value.style.setProperty(
                "--switchWidth",
                props?.props?.width ? props.props.width + "px" : "60px"
            );
            buttonBox.value.style.setProperty(
                "--switchHeight",
                props?.props?.height
                    ? showBorder
                        ? "calc(" +
                        props.props.height +
                        "px - " +
                        props.props.borderWidth +
                        "px - " +
                        props.props.borderWidth +
                        "px)"
                        : props.props.height + "px"
                    : "30px"
            );
        };

        const loadSwitchBorder = function () {
            let showBorder = true;
            if (
                props.props.borderShow != undefined &&
                !props.props.borderShow
            ) {
                showBorder = false;
            }
            buttonBox.value.style.setProperty(
                "--switchBorderColor",
                props?.props?.borderColor && showBorder
                    ? colorModel.getColor(props.props.borderColor)
                    : "#00000000"
            );
            buttonBox.value.style.setProperty(
                "--switchBorderStyle",
                props?.props?.borderStyle && showBorder
                    ? props.props.borderStyle
                    : "solid"
            );
            buttonBox.value.style.setProperty(
                "--switchBorderWidth",
                props?.props?.borderWidth && showBorder
                    ? props.props.borderWidth + "px"
                    : "0"
            );
        };
        const doClick = function (event) {
            try {
                eventHandler.value.click(event);
            } catch (e) {
                console.error(e);
            }
        };
        const eventHandler = computed(() => {
            return eventManager.loadEventHandler(
                defaultHandler,
                undefined,
                props.props.pageName
            );
        });

        const computeValue = computed(() => {
            let value = false;
            if (dataVersion.value > 0) {
                let newData = dataModel.getData(props.props, false, true);
                if (newData !== undefined) {
                    switchValue.value = newData;
                    value = newData;
                }
            }
            return value;
        });

        const doControl = (value) => {
            if (!props.props?.deviceId || props.props?.deviceId == "") {
                return;
            }
            if (!bindDevice) {
                bindDevice = dataModel.getDataSourceByDeviceId(
                    props.props.deviceId
                );
            }
            if (bindDevice && !bindModel) {
                bindModel = dataModel.getDeviceModelByDevice(bindDevice);
            }
            if (bindModel && bindModel?.properties) {
                const property = bindModel.properties.find(
                    (p) => p.name === props.props.deviceData
                );
                if (property && property.controllable) {
                    let changeData = {};
                    changeData[property.name] = value;
                    bindDevice.data = changeData;
                    serviceModel.doDeviceControl([bindDevice]);
                }
            }
        };

        watch(computeValue, (newValue, oldValue) => {
            nextTick(() => {
                stateManager.onDataChange(props, newValue);
            });
        });

        return {
            buttonBox,
            buttonStyle,
            doClick,
            defaultHandler,
            eventHandler,
            switchValue,
            buttonClass,
            updateData,
            doControl,
            computeValue,
            offColor,onColor
        };
    },
};
</script>

<style lang="scss">
.kf-3dc-atom-switch {
    border: none !important;
    transition: all 0.2s linear 0s;
    .el-switch {
        width: 100%;
        height: 100%;
        background: inherit;
        border: none;
        display: flex;
        justify-content: center;
        align-items: center;
        color: inherit;
        font-size: inherit;
        border-radius: 0;
        font-family: inherit;

        .el-switch__core {
            width: 100%;
            height: 100%;
            border-color: var(--switchBorderColor);
            border-width: var(--switchBorderWidth);
            border-style: var(--switchBorderStyle);
            border-radius: var(--switchHeight);
        }

        .el-switch__action {
            height: var(--switchHeight);
            width: var(--switchHeight);
            border-radius: var(--switchHeight);
            left: -1px;
            /* aspect-ratio: 1 / 1;
       width: 100%;*/
        }
    }

    /*.el-switch.is-checked{
    .el-switch__core{
      border-color: rgba(255,255,255,0.2);
    }
  }*/
    .el-switch.is-checked {
        .el-switch__core .el-switch__action {
            left: calc(100% - var(--switchHeight) + 1px);
        }
    }
}
</style>