/*
* 该文件，处理组件一些通用的方法，不要每个组件里都copy一次
*   author： 转山
*   date：   2020-11-25
* */


/*
*   desc：计算层级算法(已废弃)
* */
export function computeIndex() {
    let temp = document.querySelectorAll('.zIndexByJs');
    for (let i = 0; i < temp.length; i++) {
        let _currentValue = temp[i].getAttribute('B-zIndex');
        if (!_currentValue) {
            let _previousValue = null;
            let _nextValue = null;
            if (temp[i - 1]) _previousValue = temp[i - 1].getAttribute('B-zIndex');
            if (temp[i + 1]) _nextValue = temp[i + 1].getAttribute('B-zIndex');

            if (_previousValue && _nextValue) {
                temp[i].setAttribute('B-zIndex', ((Number(_previousValue) + Number(_nextValue)) / 2).toString());
            } else if (_previousValue || _nextValue) {
                if (_previousValue) {
                    temp[i].setAttribute('B-zIndex', (Number(_previousValue) + 1000).toString());
                }

                if (_nextValue) {
                    temp[i].setAttribute('B-zIndex', (Number(_nextValue) / 2).toString());
                }
            } else {
                temp[i].setAttribute('B-zIndex', '1000');
            }
        }
    }
}

/**
 * 校验数据格式类型
 * @author 转山
 * @date   2020-09-16
 */
export const is = (() => {
    let is = {
        types: ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument", "function", "FormData"]
    };
    is.types.forEach(x => {
        is[x] = function (obj) {
            let temp;
            if (x === "function") {
                temp = typeof obj === x;
            } else {
                temp = Object.prototype.toString.call(obj) === "[object " + x + "]";
            }
            return temp;
        };
    });

    is.getType = function (obj) {
        let output = null;
        if (typeof obj === 'function') {
            output = 'function';
        } else {
            const re = new RegExp(is.types.join('|'));
            let temp = re.exec(Object.prototype.toString.call(obj));
            if (temp && temp[0]) {
                output = temp[0];
            }
        }
        return output;
    };
    return is;
})();

export function judgeEnv() {
    let output = {
        env: '',
        isDowngrade: false
    };
    if (global.document) {
        if (global.__SmallApp_env_run_type) {
            if (global.__SmallApp_env_run_type === 2) {
                output.env = 'Service';
                output.isDowngrade = true;
            } else if (global.__SmallApp_env_run_type === 5) {
                output.env = 'Render';
            } else if (global.__SmallApp_env_run_type === 6) {
                output.env = 'Render';
                output.isDowngrade = true;
            }
        } else {
            output.env = 'Render';
        }
    } else {
        output.env = 'Service';
    }
    return output;
}

/**
 * 样式字符串文本转对象
 * */
export function styleToObj(styleText, isNeedToHump = true) {
    if (!styleText) return;
    let output = {};
    let styleArr = styleText.split(';');
    styleArr.forEach(x => {
        if (/:/.test(x)) {
            let _kv = x.split(':');
            switch (_kv[0]) {
            case 'margin':
                let _tempArrMargin = _kv[1].replace(/(^\s*)|(\s*$)/g, "").split(' ');
                if (_tempArrMargin.length === 1) {
                    output['marginTop'] = _tempArrMargin[0];
                    output['marginLeft'] = _tempArrMargin[0];
                    output['marginRight'] = _tempArrMargin[0];
                    output['marginBottom'] = _tempArrMargin[0];
                } else if (_tempArrMargin.length === 2) {
                    output['marginTop'] = _tempArrMargin[0];
                    output['marginLeft'] = _tempArrMargin[1];
                    output['marginRight'] = _tempArrMargin[1];
                    output['marginBottom'] = _tempArrMargin[0];
                } else if (_tempArrMargin.length === 4) {
                    output['marginTop'] = _tempArrMargin[0];
                    output['marginRight'] = _tempArrMargin[1];
                    output['marginBottom'] = _tempArrMargin[2];
                    output['marginLeft'] = _tempArrMargin[3];
                }
                break;
            case 'padding':
                let _tempArrPadding = _kv[1].replace(/(^\s*)|(\s*$)/g, "").split(' ');
                if (_tempArrPadding.length === 1) {
                    output['paddingTop'] = _tempArrPadding[0];
                    output['paddingLeft'] = _tempArrPadding[0];
                    output['paddingRight'] = _tempArrPadding[0];
                    output['paddingBottom'] = _tempArrPadding[0];
                } else if (_tempArrPadding.length === 2) {
                    output['paddingTop'] = _tempArrPadding[0];
                    output['paddingLeft'] = _tempArrPadding[1];
                    output['paddingRight'] = _tempArrPadding[1];
                    output['paddingBottom'] = _tempArrPadding[0];
                } else if (_tempArrPadding.length === 4) {
                    output['paddingTop'] = _tempArrPadding[0];
                    output['paddingRight'] = _tempArrPadding[1];
                    output['paddingBottom'] = _tempArrPadding[2];
                    output['paddingLeft'] = _tempArrPadding[3];
                }
                break;
            case 'border':
                let _tempArrBorder = _kv[1].replace(/(^\s*)|(\s*$)/g, "").split(' ');
                if (_tempArrBorder.length === 3) {
                    output['borderWidth'] = _tempArrBorder[0];
                    output['borderStyle'] = _tempArrBorder[1];
                    output['borderColor'] = _tempArrBorder[2];
                }
                break;
            case 'font-family':
                output['fontFamily'] = _kv[1].replace(/"|'|(^\s*)|(\s*$)/g, "");
                break;
            default:
                let _leftKey = _kv[0].replace(/\r|\n|\\s| /g, '');
                if (!/^-/.test(_leftKey)) {
                    if (!/var/.test(_kv[1])) {
                        if (/border.+radius/.test(_kv[0])) {
                            // 特殊处理ios，浏览器会将border-radius一拆4，导致ios客户端不认
                            if (!output['borderRadius']) {
                                output['borderRadius'] = _kv[1].replace(/(^\s*)|(\s*$)/g, "");
                            }
                        } else {
                            if (isNeedToHump) {
                                output[toHump(_leftKey)] = _kv[1].replace(/(^\s*)|(\s*$)/g, "");
                            } else {
                                output[_leftKey] = _kv[1].replace(/(^\s*)|(\s*$)/g, "");
                            }

                        }
                    }
                }
            }
        }
    });
    return output;
}

// 下划线转换驼峰
export function toHump(name) {
    return name.replace(/\-(\w)/g, function (all, letter) {
        return letter.toUpperCase();
    });
}

// 驼峰转换下划线
export function toLine(name) {
    return name.replace(/([A-Z])/g,"-$1").toLowerCase();
}

// 版本对比
export function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }

    return 0;
}

// 将客户端的数据转成style对象 （cover-view使用）
export function naDataToObj(el, data, extraParam) {
    let _elStyle = el.getAttribute('style');
    let _temp = {};
    let _outputStr = ''
    let _outputObj = {};
    if (data.width) {
        _temp['--width'] = data.width + 'px';
    }

    if (data.height) {
        if (extraParam && extraParam.type === 'textarea' && extraParam.autoHeight) {
            _temp['height'] = data.height + 'px';
        } else {
            _temp['--height'] = data.height + 'px';
        }
    }

    if (extraParam && extraParam.type === 'cover-view') {
        if (extraParam.setWidth) {
            _temp['width'] = 'var(--width)';
        }

        if (extraParam.setHeight) {
            _temp['height'] = 'var(--height)';
        }
    }

    // 优先级最高
    if (data["setStyle"]) {
        for (let key in data["setStyle"]) {
            _temp[toLine(key)] = data["setStyle"][key];
        }
    }

    if (_elStyle) {
        _outputObj = Object.assign(styleToObj(_elStyle, false), _temp);
    } else {
        _outputObj = Object.assign({}, _temp);
    }

    for (let key in _outputObj) {
        _outputStr += `${key}:${_outputObj[key]};`
    }

    el.setAttribute('style', _outputStr);
}
