<template>
    <div class="kf-light-container w-100 h-100 flex-column-between-start pr" v-show="props.show" :style="cardStyle" ref="lightBox"
         :class="'vivify '+ buttonClass">
        <div class="kf-light-title" v-if="props.isShowTitle" ref="lightTitleBox">{{title}}</div>
        <div class="kf-light-cons flex-row-between-center" :class="[!props.isShowTitle?'pt16':'pt0']" ref="lightContentBox">
            <div class="kf-light-cons1 pr" v-if="computeData?.switch?.enumItems">
                <div class="kf-light-cons1-i"></div>
                <div class="kf-light-cons2" v-for="(item,index) in computeData.switch.enumItems"
                     v-show="computeData.switch.defaultValue==item.value"
                     :class="[computeData.switch.defaultValue?'kf-light-cons2-active':'']"
                     @click="changeSwitch(item,index,computeData.switch)" :key="item.value+index">
                    {{ item.label.zhCN }}</div>
            </div>
            <div class="kf-light-cons3 pr" v-if="computeData?.brightness">
                <div class="kf-light-cons3-slider pr">
                    <el-slider v-model="computeData.brightness.defaultValue" :min="computeData.brightness.minimum"
                               @change="changeBrightness" :max="computeData.brightness.maximum" placement="right" :show-tooltip="false" />
                    <!--                    <div class="kf-light-cons3-slider-span">{{data.brightness.value}}</div>-->
                </div>
                <i class="iconfont icon-ai251 kf-light-cons3-i"></i>
            </div>
        </div>
        <!--        <div class="kf-light-btn" @click="handleEdit($event)">颜色设定</div>-->

        <div class="kf-light-color-box" v-show="showColor" :style="colorStyle">
            <div class="kf-light-color-box-header flex-row-between-center">灯光颜色设定
                <i class="iconfont icon-close" @click="showColor=false"></i>
            </div>
            <div class="kf-light-colors pr">
                <div class="kf-light-colors-dot"></div>
            </div>
            <div class="kf-light-colors-value flex-row-between-center" v-if="computeData?.temperature">
                {{computeData.temperature.label.zhCN}}
                <div class="kf-light-cons3-slider1 pr">
                    <el-slider v-model="computeData.temperature.defaultValue" :min="computeData.temperature.minimum"
                               :max="computeData.temperature.maximum" placement="right" :show-tooltip="false" />
                </div>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: "kfLight",
    props: {
        props: {
            type: Object,
            default: () => {},
        },
        eventList: {
            type: Array,
            default: () => [],
        },
        eventScript: {
            type: String,
        },
    },
    widgetConfig: {
        parent: "base",
        rank: 6,
        label: {
            zh: "灯光",
        },
        category: "业务",
        component: "kfLight",
        display: true,
        version: 1,
        icon: "icon-anniu",
        defaultSize: {
            x: 296,
            y: 130,
        },
        minSize:{
            width: 296,
            height: 130,
        },
        imgName: "kfLight",
        state: {
            isAdd: false,
            isCondition: false,
        },
    },
    setup(props) {
        let bindDevice = null,
            bindModel = null;
        let cardStyle = ref({});
        let buttonClass = ref("");
        let lightBox = ref(null);
        let lightContentBox = ref(null);
        let lightTitleBox = ref(null);
        const { proxy, type } = getCurrentInstance();
        let defaultSize = type.widgetConfig.defaultSize;
        let defaultHandler = ref({});
        let title = ref("办公室-A01-灯光001");

        let model = ref({
            brightness: {
                enumItems: null,
                name: "brightness",
                format: "dataLabel",
                defaultValue: 0,
                controllable: true,
                maximum: 100,
                minimum: 0,
                unit: "%",
                label: { en: "Brightness", zhCN: "亮度", zhTW: null },
                value: 100,
            },
            switch: {
                name: "switch",
                enumItems: [
                    {
                        value: true,
                        label: { en: "On", zhCN: "开", zhTW: "開" },
                    },
                    {
                        value: false,
                        label: { en: "Off", zhCN: "关", zhTW: "關" },
                    },
                ],
                format: "switch",
                defaultValue: false,
                value: false,
                controllable: true,
                label: { en: "Switch", zhCN: "开关", zhTW: null },
            },
            color: {
                enumItems: null,
                format: "color",
                defaultValue: "#FFFFFF",
                controllable: false,
                label: { en: "Color", zhCN: "颜色", zhTW: null },
                value: "#FFFFFF",
            },
            temperature: {
                enumItems: null,
                format: "dataLabel",
                defaultValue: 0,
                controllable: false,
                maximum: 100,
                minimum: 0,
                unit: "K",
                label: { en: "Temperature", zhCN: "色温", zhTW: null },
                value: 50,
            },
        });

        let dataVersion = ref(0);

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

        onMounted(() => {
            refreshEvents();
            cardStyle.value = styleManager.updateStyle(proxy);
            buttonClass.value = styleManager.updateClass(proxy);
            lightBox.value.style.setProperty(
                "--onColor",
                props.props["onColor"] != undefined && props.props["onColor"]
                    ? props.props["onColor"]
                    : "#305792"
            );
            buttonClass.value = styleManager.updateClass(proxy);
        });

        onUnmounted(() => {
            model = null;
        });

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

        pageModel.watchProps(props, watch, proxy, (changes) => {
            if (styleManager.styleChanged("kfLight", changes)) {
                cardStyle.value = styleManager.updateStyle(proxy);
            }
            if (styleManager.classChanged("kfLight", changes)) {
                buttonClass.value = styleManager.updateClass(proxy);
            }
            watchDecviceIdChange(changes);
            if (props.props?.title != "") {
                title.value = props.props.title;
            }
            if (changes && changes["isShowTitle"] != undefined) {
                if (props.props.isShowTitle) {
                    pageModel.updatePropValue("height", defaultSize.y);
                } else {
                    pageModel.updatePropValue("height", defaultSize.y - 40);
                }
            }
            lightBox.value.style.setProperty(
                "--onColor",
                props.props["onColor"] != undefined && props.props["onColor"]
                    ? props.props["onColor"]
                    : "#305792"
            );
        });

        watch(props, (newValue, oldValue) => {
            buttonClass.value = styleManager.updateClass(proxy);
            // refreshEvents();
            //cardStyle.value = styleManager.updateStyle(proxy);
        });
        const eventHandler = computed(() => {
            return eventManager.loadEventHandler(
                defaultHandler,
                undefined,
                props.props.pageName
            );
        });

        const loadTitle = function () {
            if (bindDevice) {
                title.value = bindDevice.deviceName;
            } else {
                title.value = "办公室-A01-灯光001";
            }
        };

        const computeData = computed(() => {
            if (!bindDevice && props.props.deviceId) {
                bindDevice = dataModel.getDataSourceByDeviceId(
                    props.props.deviceId
                );
                if (bindDevice) {
                    bindModel = dataModel.getDeviceModelByDevice(bindDevice);
                    loadTitle();
                    updateModel();
                }
            }
            if (dataVersion.value > 0) {
                let newData = dataModel.getData(props.props, false, true);
                if (newData && newData.length > 0) {
                    const deviceData = props.props?.deviceData;
                    if (deviceData && Array.isArray(deviceData)) {
                        for (let i = 0; i < deviceData.length; i++) {
                            const key = deviceData[i];
                            if (newData[i] != undefined && model.value[key] && model.value[key].hasOwnProperty("defaultValue")) {
                                model.value[key].defaultValue = newData[i];
                            }
                        }
                    }
                }
            }
            return model.value;
        });

        const updateModel = () => {
            if (bindDevice && bindModel) {
                const properties = bindModel?.properties;
                if (properties) {
                    for (let i = 0; i < properties.length; i++) {
                        let property = properties[i];
                        if (model.value.hasOwnProperty(property.name)) {
                            if (property?.type === "boolean") {
                                // 物模型填写的问题，导致boolean 是string
                                property.defaultValue = Boolean(
                                    property.defaultValue
                                );
                            }
                            Object.assign(model.value[property.name], property);
                        }
                    }
                }
            }
        };

        const watchDecviceIdChange = (changes) => {
            if (
                changes &&
                changes["deviceId"] &&
                changes["deviceId"] != undefined
            ) {
                bindDevice = dataModel.getDataSourceByDeviceId(
                    props.props.deviceId
                );
                if (bindDevice) {
                    bindModel = dataModel.getDeviceModelByDevice(bindDevice);
                    if (bindModel) {
                        let deviceData = bindModel.properties.map(
                            (p) => p.name
                        );
                        props.props.deviceData = deviceData;
                        updateModel();
                    }
                    loadTitle();
                }
            }
        };

        const changeSwitch = function (item, index, datas) {
            model.value["switch"].defaultValue = !item.value;
            dataModel.doControl(
                props,
                bindDevice,
                bindModel,
                model.value["switch"].defaultValue,
                "switch"
            );
        };

        const changeBrightness = function (val) {
            model.value["brightness"].defaultValue = val;
            dataModel.doControl(
                props,
                bindDevice,
                bindModel,
                model.value["brightness"].defaultValue,
                "brightness"
            );
        };

        let showColor = ref(false);
        let colorStyle = ref({});

        const handleEdit = function (event) {
            event.stopPropagation();
            colorStyle.value.left = event.clientX - event.layerX + "px";
            colorStyle.value.top = event.clientY - event.layerY + "px";
            showColor.value = true;
        };

        return {
            showColor,
            colorStyle,
            cardStyle,
            eventHandler,
            value: 30,
            title,
            computeData,
            changeSwitch,
            handleEdit,
            changeBrightness,
            lightBox,
            lightContentBox,
            lightTitleBox,
            buttonClass,
            updateData,
        };
    },
};
</script>

<style lang="scss">
.kf-light-container {
    padding: 0px 8px 16px 8px;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.12);
    background: #1c1c1c;
    //box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);

    .kf-light-title {
        display: flex;
        height: 40px;
        padding: 4px 4px 4px 8px;
        align-items: center;
        gap: 4px;
        align-self: stretch;
        border-bottom: 1px solid rgba(255, 255, 255, 0.12);
        color: rgba(255, 255, 255, 0.9);
        font-family: Open Sans;
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
    }

    .kf-light-cons {
        display: flex;
        height: 68px;
        align-items: flex-start;
        gap: 8px;
        align-self: stretch;

        .kf-light-cons1 {
            width: 40%;
            min-width: 120px;
            display: flex;
            padding: 4px;
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
            align-items: center;
            justify-content: center;
            align-self: stretch;
            border-radius: 8px;
            cursor: pointer;
            border: 1px solid rgba(255, 255, 255, 0.12);

            .kf-light-cons2 {
                display: flex;
                width: 100%;
                height: 100%;
                gap: 4px;
                color: rgba(255, 255, 255, 0.55);
                background: #0c0c0c;
                color: #fff;
                leading-trim: both;
                text-edge: cap;
                font-family: Alibaba PuHuiTi;
                font-size: 16px;
                font-style: normal;
                font-weight: 700;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .kf-light-cons2-active {
                display: flex;
                width: 100%;
                height: 100%;
                gap: 4px;
                color: rgba(255, 255, 255, 0.9);
                background: var(--onColor);
                color: #fff;
                leading-trim: both;
                text-edge: cap;
                font-family: Alibaba PuHuiTi;
                font-size: 16px;
                font-style: normal;
                font-weight: 700;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .kf-light-cons1-i {
                position: absolute;
                width: 24px;
                top: 4px;
                left: calc((100% - 24px) / 2);
                margin-left: auto;
                margin-right: auto;
                height: 4px;
                border-radius: 4px;
                border: 1px solid rgba(255, 255, 255, 0.05);
                background: #166ce4;
                box-shadow: 0px 2px 4px 0px rgba(0, 151, 255, 0.2);
            }
        }

        .kf-light-cons3 {
            display: flex;
            min-height: 48px;
            max-height: 68px;
            padding: 4px;
            align-items: flex-start;
            gap: 4px;
            flex: 1 0 0;
            align-self: stretch;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.12);
            background: transparent;
            .kf-light-cons3-i {
                position: absolute;
                left: 18px;
                height: 100%;
                display: flex;
                align-items: center;
                font-size: 18px;
            }
            .kf-light-cons3-slider {
                display: flex;
                width: 100%;
                height: 100%;
                flex-direction: row;
                justify-content: flex-start;
                align-items: center;
                .el-slider {
                    width: 100%;
                    height: 100%;
                    .el-slider__runway {
                        background: transparent;
                        height: 100%;
                        .el-slider__bar {
                            height: 100%;
                            background: rgba(255, 255, 255, 0.3);
                        }
                        .el-slider__button-wrapper {
                            width: 4px;
                            height: 28px;
                            transform: translateX(-150%);

                            top: calc((100% - 28px) / 2);
                            .el-slider__button {
                                width: 100%;
                                height: 100%;
                                background: rgba(255, 255, 255, 0.16);
                                display: none;
                                border-radius: 4px;
                                border: none;
                                &:hover {
                                    transform: scale(1);
                                }
                            }
                        }
                        &:hover {
                            .el-slider__button {
                                display: flex;
                            }
                        }
                    }
                }
                .kf-light-cons3-slider-span {
                    position: absolute;
                    left: 0;
                    top: 0;
                }
            }
        }
    }

    .kf-light-btn {
        display: flex;
        height: 32px;
        padding: 4px;
        justify-content: center;
        align-items: center;
        align-self: stretch;
        border-radius: 6px;
        border: 1px solid rgba(255, 255, 255, 0.12);
        background: #0c0c0c;
        cursor: pointer;
        &:hover {
            border-color: rgba(0, 0, 0, 0.7);
        }
    }
}
.kf-light-color-box {
    position: fixed;
    display: flex;
    width: 312px;
    padding: 0px 8px 8px 8px;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, 0.12);
    background: #1c1c1c;
    //box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);
    .kf-light-color-box-header {
        display: flex;
        height: 40px;
        padding: 4px 4px 4px 8px;
        align-items: center;
        gap: 4px;
        align-self: stretch;
        border-bottom: 1px solid rgba(255, 255, 255, 0.12);
    }
    .kf-light-colors {
        height: 296px;
        width: 100%;
        background-color: red; /* 对于不支持渐变的浏览器 */
        background-image: conic-gradient(red, yellow, green, blue, red);
        border-radius: 50%;
        .kf-light-colors-dot {
            position: absolute;
            top: 120px;
            cursor: pointer;
            left: 50px;
            border: 1px solid #fff;
            width: 6px;
            height: 6px;
            border-radius: 50%;
        }
    }
    .kf-light-colors-value {
        width: 100%;
        height: 20px;
        .kf-light-cons3-slider1 {
            width: calc(100% - 60px);
            height: 100%;
            .el-slider {
                width: 100%;
                height: 100%;
            }
        }
    }
}
.pt16 {
    padding-top: 16px;
}
.pt0 {
    padding-top: 0;
}
</style>