<!-- webview only --><!-- slot -->
<template>
    <div
        class="bili-bton-default zIndexByJs"
        :data-zIndex="zIndex"
    >
    </div>
</template>

<script>
    export default {
        name: 'Bili__BCardButton',
        props: {
            "type": {// 按钮预置的样式
                type: String,
                default: "pink"
            },
            "source-from": { // 业务预置来源，必填,不可修改
                type: String,
                default: ''
            },
            "bili-from": { // bilibili 预置来源，必填,不可修改,仅iOS
                type: String,
                default: ''
            },
            "gameId": { // 游戏Id, 可读可写
                type: String,
                default: ""
            },
            "zIndex": {
                type: Number,
                default: 0
            },
            "extra": { // 上报参数、埋点统计
                type: Object,
                default: {}
            },
            "reserveUrl": { // 降级url， 仅iOS
                type: String,
                default: ""
            },
            "id": {
                type: String,
                default: ""
            }
        },
        // 监控属性变化
        watch: {
           type(value) {
               if(value == this.type) {
                   return;
               } else {
                    this._attrUpdate('type', value);
               }
           },
           gameId(value) {
                if(value == this.type) {
                    return;
                } else {
                    this._attrUpdate('gameId', value);
                }
           }
        },
         data(){
            return {
                isRGBReg: /^rgb/i,
                rgbReg:  /\d+/gi,
                styles: {}
            }
        },
        mounted() {
            const APPID = window.__smallAppFE.APPID;
            const isInternalSmallApp = APPID.indexOf('bilinternal') === 0 || APPID.indexOf('biliwidget') === 0;
            if(!isInternalSmallApp) {
                console.warn('not support this component')
                return
            }
            const that = this;
            // 引入层级算法，自动保持层级
            SmallApp.computeIndex();
            SmallApp.waitStyleOver().then(()=>{
                that.styles = that._computeStyle();
                that.cardAttr = that._getAttrs();
                SmallApp.nativeComponent({
                    ...that._getBasicData(),
                    actionType: "create",
                    styles: that.styles,
                    cardAttr: that.cardAttr
                });
            });

            this._watchStyle();
        },
        beforeDestroy() {
            SmallApp.postMessage({
                ...this._getBasicData(),
                actionType: "destroy",
                id: this._uid,
                customId: this.id,
            });
        },
        methods: {
            updateStyles() {
                let positionInfo = this.$el.getBoundingClientRect();
                let styleInfo = window.getComputedStyle(this.$el);
                let isFixed = styleInfo.getPropertyValue("position") === "fixed";
                const newStyles = {
                    x: isFixed ? positionInfo.left : positionInfo.left + SmallApp.getScrollData('left'),
                    y: isFixed ? positionInfo.top : positionInfo.top + SmallApp.getScrollData('top'),
                    width: positionInfo.width,
                    height: positionInfo.height,
                    fixed: isFixed,
                    hidden: styleInfo.getPropertyValue("display") === "none",
                    color: this.toHEXColor(styleInfo.getPropertyValue("color")),
                    fontSize: parseFloat(styleInfo.fontSize),
                    borderColor: this.toHEXColor(styleInfo.borderColor),
                    borderWidth: parseFloat(styleInfo.borderWidth),
                    cornerRadius: parseFloat(styleInfo.borderRadius),
                    backgroundColor: this.toHEXColor(styleInfo.backgroundColor)
                };
                const diffStyles = this.diffJson(this.styles, newStyles);
                if (diffStyles) {
                    this.styles = newStyles;
                    SmallApp.nativeComponent({
                        ...this._getBasicData(),
                        actionType: "styleUpdate",
                        styles: diffStyles
                    });
                }
            },
            _watchStyle(){
                const that = this;
                this.observer = new MutationObserver( () => {
                    SmallApp.waitStyleOver().then(()=>{
                        that.updateStyles()
                    });
                });

                this.observer.observe(document.body, {
                    attributes: true,
                    childList: true,
                    characterData: true,
                    subtree: true
                });
            },
            _computeStyle() {
                let styleInfo = global.getComputedStyle(this.$el);
                let positionInfo = this.$el.getBoundingClientRect();
                let isFixed = styleInfo.getPropertyValue("position") === "fixed";
                const result = {
                    x: isFixed ? positionInfo.left : positionInfo.left + SmallApp.getScrollData('left'),
                    y: isFixed ? positionInfo.top : positionInfo.top + SmallApp.getScrollData('top'),
                    width: parseFloat(styleInfo.width),
                    height: parseFloat(styleInfo.height),
                    fixed: isFixed,
                    hidden: styleInfo.getPropertyValue("display") === "none",
                    color: this.toHEXColor(styleInfo.color),
                    fontSize: parseFloat(styleInfo.fontSize),
                    borderColor: this.toHEXColor(styleInfo.borderColor),
                    borderWidth: parseFloat(styleInfo.borderWidth),
                    cornerRadius: parseFloat(styleInfo.borderRadius),
                    backgroundColor: this.toHEXColor(styleInfo.backgroundColor)
                }
                return result;
            },
            _getAttrs(){
                const result = {
                    type: this.type,
                    sourceFrom: this.sourceFrom,
                    biliFrom: this.biliFrom,
                    gameId: this.gameId,
                    reserveUrl: this.reserveUrl,
                    extra: this.extra,
                    id: this.id
                }
                return result;
            },
            _getBasicData(){
                return {
                    type: "native-component",
                    id: this._uid,
                    customId: this.id,
                    name: "gamecardbutton",
                    zIndex: Number(this.$el.getAttribute('B-zIndex'))
                }
            },
            _attrUpdate(key, value) {
                SmallApp.nativeComponent({
                    ...this._getBasicData(),
                    actionType: "attrUpdate",
                    cardAttr: {
                        [key]:  value
                    }
                });
            },
            _styleUpdate(key, value) {
                SmallApp.nativeComponent({
                    ...this._getBasicData(),
                    actionType: "styleUpdate",
                    styles: {
                        [key]: value
                    }
                });
            },
            // handleMessage，作为事件的触发，该方法NA会直接调用。
            handleMessage(message) {
                if (message.type === 'native-component') {
                    this.$emit(message.event.type, message.event.detail);
                }
            },
            toHEX(number){
                const str = '0123456789ABCDEF';
                let temp = '';
                let cur = number % 16;
                temp = str.substr(cur, 1);
                cur = (number - cur) / 16;
                return str.substr(cur, 1) + temp;
            },
            toHEXColor(color){
                if (this.isRGBReg.test(color)) {
                    const [r, g, b] = color.match(this.rgbReg);
                    return '#' + this.toHEX(r) + this.toHEX(g) + this.toHEX(b);
                }
                return color;
            },
            diffJson(oldJson, newJson){
                if (typeof newJson !== "object" || typeof oldJson !== "object") {
                    return newJson;
                }

                let diff = null;
                Object.keys(newJson).forEach((k) => {
                    if (oldJson[k] !== newJson[k]) {
                        if (!diff) {
                            diff = {};
                        }

                        diff[k] = newJson[k];
                    }
                });

                return diff;
            }
        },

    };
</script>

<style lang="less">
    .bili-bton-default {
        width: 66px;
        height: 24px;
        opacity: 0;
        border-style: solid;
        background-color: transparent;
    }
</style>
