import * as React from 'react';
import * as PropTypes from 'prop-types';
import ShopEmpty from '../common/empty/empty'
import CptCode from "./config";

declare global {
    interface Window {
        imgBaseUrl: string
    }
}

class MUtil {
    static daySecond = 24 * 60 * 60;
    static hourSecond = 60 * 60;
    /*
    * 手机端：根据组件代码解析成相应的组件
    * @params:
    *  type:组件代码
    *  data:组件参数
    * */
    static transInReactNode(data: any, type?: any) {
        let ReactNode = null;
        if (data && data.cptCode && data.cptType) {
            let cptCode = data.cptCode;
            let cptType = data.cptType;
            let TagName = CptCode[cptCode][cptType];
            if (TagName) {
                ReactNode = <TagName {...data}></TagName>
            }
        }
        return ReactNode;
    }

    /*
    * 判断参数是否为空
    * */
    static hasContent(data: any): boolean {
        if (Object.prototype.toString.call(data) === '[object Array]') {
            if (data.length > 0) {
                return true;
            }
        }
        if (Object.prototype.toString.call(data) === '[object Object]') {
            if (Object.keys(data).length === 0) {
                return false
            } else {
                return true
            }
        }

        return false;
    }

    /*
    * 判断是否是数组
    * */
    static isArray(data) {
        if (Object.prototype.toString.call(data) === '[object Array]') {
            return true;
        }
        return false;
    }

    /*
    * 判断是否是空数组
    * */
    static isEmptyArray(data) {
        if (this.isArray(data)) {
            if (data.length == 0) {
                return true;
            }
        }
        return false;
    }

    /*
    * 全局图片地址前缀
    * */
    static baseUrl(url) {
        return url;
    }

    // 分，换算成元
    static centTransformOut(num: any) {
        let price = null;
        num = parseFloat(num) / 100;
        if (isNaN(num) || num < 0) {
            price = 0.00;
        } else {
            price = num;
        }
        price = price.toFixed(2);
        return price;
    }

    // 分，单位换算
    static centChange(num: any) {
        num = Number(num);
        if (isNaN(num) || num < 0) {
            num = 0;
        }
        let str = num.toString(), unit = "";
        if (str.length >= 7 && str.length < 11) {
            str = num / 1000000;
            unit = "万"
        } else if (str.length >= 11) {
            str = num / 10000000000;
            unit = "亿"
        } else {
            str = num / 100;
        }
        str = str.toFixed(2);
        return {
            str: str,
            unit: unit
        }
    }

    static initParams(data, source) {
        let obj = {};
        for (var key in source) {
            if (key != 'content') {
                obj[key] = source[key];
            }
        }
        let newObj = Object.assign(obj, data);
        return newObj;
    }

    static groupFixed(range, callback) {

        let containers = document.getElementsByClassName('shop-tabs-container-left');
        for (let i = 0; i < containers.length; i++) {
            let el: any = containers[i];
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            let offset = el.offsetTop - scrollTop;

            let wrapperEl = el.getElementsByClassName('shop-tabs-wrapper')[0];

            //判断左侧分组列表是否固定到顶部
            if (offset <= 0) {
                wrapperEl.classList.remove('shop-tabs-absolute');
                wrapperEl.classList.add('shop-tabs-fixed')
            } else {
                wrapperEl.classList.remove('shop-tabs-fixed');
                wrapperEl.classList.remove('shop-tabs-absolute')
            }

            // 当前分组尾部距离顶部的距离小于左侧分组高度时,fix改成absolute
            let totalHeight = el.offsetTop + el.clientHeight;
            let remainHeight = totalHeight - scrollTop;
            let letHeight = wrapperEl.clientHeight;
            if (remainHeight <= letHeight) {
                wrapperEl.classList.remove('shop-tabs-fixed');
                wrapperEl.classList.add('shop-tabs-absolute')
            }

            // 页面滚动时左侧分组自动定位到当前商品分组
            var topRange = 0;
            if (range) {
                topRange = range;
            }
            var panels = el.getElementsByClassName('shop-tabs-panel');
            for (let j = 0; j < panels.length; j++) {
                var panelItem = panels[j];

                if (panelItem.offsetTop + el.offsetTop - topRange - scrollTop < 0 && panelItem.getElementsByClassName('shop-tabs-title').length > 0) {

                    if (callback) {
                        callback(j);
                    }
                }
            }
        }
    }


    goTarget(target) {
        var timer = null;
        var lastPos = 0;

        function goMove() {
            var currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
            currentPosition = currentPosition;
            if (lastPos == currentPosition) { //页面高度不够长，未滑动到指定位置的时候，已经滑动到底部了
                window.scrollTo(0, target);
                clearInterval(timer);
                console.log('move to ' + target);
                return;
            }
            lastPos = currentPosition;
            if (Math.abs(currentPosition - target) < 20) {
                window.scrollTo(0, target);
                clearInterval(timer);
                return;
            }
            if (currentPosition - target > 20) {
                currentPosition -= 20;
                window.scrollTo(0, currentPosition);
            } else {
                currentPosition += 20;
                window.scrollTo(0, currentPosition);
            }
        }

        timer = setInterval(goMove, 10);
    }


    /**
     * DDD,*H,*M,*S
     * @param timeInSecond
     */
    static second2Date(timeInSecond):any{
        let day: any = Math.floor(timeInSecond / MUtil.daySecond);
        let remainInDay = timeInSecond - day * MUtil.daySecond;
        let hour: any = Math.floor(remainInDay / MUtil.hourSecond);

        let remainInHour = remainInDay - hour * MUtil.hourSecond;
        let minute: any = Math.floor(remainInHour / 60);

        let second: any = Math.floor(remainInHour - minute * 60);

        if (isNaN(day) || day < 0) {
            day = 0;
        }
        if (isNaN(hour) || hour < 0) {
            hour = 0;
        }
        if (isNaN(minute) || minute < 0) {
            minute = 0;
        }
        if (isNaN(second) || second < 0) {
            second = 0;
        }

        return {day: day,
            hour: hour,
            minute: minute,
            second: second}
    }

    /**
     * DDD,HH,MM,SS
     * @param timeInSecond
     */
    static second2FormatDate(timeInSecond):any{
        let {day,hour,minute,second} = MUtil.second2Date(timeInSecond);

        return {
            day: day<10?('0'+day):String(day),
            hour: hour<10?('0'+minute):String(hour),
            minute: minute<10?('0'+minute):String(minute),
            second: second<10?('0'+second):String(second)
        };
    }
    /*
    * 倒计时
    * */
    static calcTimer(remainTime, id): any {
        if (remainTime <= 0) {
            return false;
        }

        let data = MUtil.second2FormatDate(remainTime);
        // let className = this.state.key;
        let el = document.getElementById(id);
        if (el) {
            let dayCon = "<span class='dDayWrapper'>" +
                "<span class='dDay'>" + data.day + "</span>" +
                "<span>天</span>" +
                "</span>";
            let html = "<span class='dTime'>" + data.hour + "</span>:" +
                "<span class='dTime'>" + data.minute + "</span>:" +
                "<span class='dTime'>" + data.second + "</span>";
            if (data.day) {
                html = dayCon + html;
            }
            el.innerHTML = html;

            setTimeout(() => {
                remainTime = remainTime - 1;
                this.calcTimer(remainTime, id)
            }, 1000);
        }
    }

    static calcTimerNew(remainTime, id, flag = 1): any {
        if (remainTime <= 0) {
            return false;
        }
        if (isNaN(remainTime)) {
            remainTime = 0;
        }

        let {day,hour,minute,second} = MUtil.second2Date(flag == 1?remainTime:remainTime/1000);
        if (flag == 1) {
            remainTime = remainTime * 1000;
        }
        let msecond: any = (flag == 1?0:Math.floor((remainTime % 1000) / 100));
        if (isNaN(msecond) || msecond <= 0) {
            msecond = 0;
        }
        let data = {
            day: day<10?("0"+day):String(day),
            hour: hour<10?("0"+hour):String(hour),
            minute: minute<10?("0"+minute):String(minute),
            second: second<10?("0"+second):String(second),
            msecond: String(msecond)
        };

        let el: any = document.getElementsByClassName(id);
        if (el && el[0]) {
            let html = "<span class='shop-timer-time-minute'>" + data.minute + "</span>:" +
                "<span class='shop-timer-time-second'>" + data.second + "</span>" ;

            if(hour > 0 || day > 0)
                html =  "<span class='shop-timer-time-hour'>" + data.hour + "</span>:" + html ;
            if(day > 0)
                html =  "<span class='shop-timer-time-day'>" + data.day + "天 </span>" + html ;

            el[0].innerHTML = html;

            setTimeout(() => {
                remainTime = remainTime - 100;
                this.calcTimerNew(remainTime, id, 2)
            }, 100);
        }

    }

    static timerType() {
        return {
            TIMER_BIG: 'big',
            TIMER_SMALL: 'small',
            TIMER_NULL: 1
        }
    }

    static marketType() {
        return {
            NORMAL: 0,
            GROUPBUY: 2,
            DISTRI: 1,
            BARGAIN: 3,
            MEMBER:6
        }
    }

    static calcNum(num) {
        let numNum = num;
        if (num >= 10000) {
            numNum = num / 10000;
            numNum = numNum.toFixed(1);
            numNum = numNum + '万';
        }

        if (num >= 100000000) {
            numNum = num / 100000000;
            numNum = numNum.toFixed(1);
            numNum = numNum + '亿';
        }

        return numNum;
    }

    /*
    * 计算图片高度，用于百度编辑器有高度的图片
    * */
    static overwriteImg(html) {
        let clientW = document.documentElement.clientWidth || document.body.clientWidth
        if (clientW > 750) {
            clientW = 750
        }
        clientW = clientW - 30;
        let wrapper = document.createElement('div');
        wrapper.innerHTML = html;
        let imgs = wrapper.getElementsByTagName('img');

        for (let i = 0; i < imgs.length; i++) {
            let item = imgs[i];
            let width: any = item.getAttribute('width');
            let height: any = item.getAttribute('height');
            let rate = width / clientW;
            if (rate > 1) {
                height = Number(height / rate);
                width = Number(width / rate);
                height = height.toFixed(0);
                width = width.toFixed(0);
                item.setAttribute('height', height);
                item.setAttribute('width', width);
                item.setAttribute('mode', 'aspectFit')
                // mode='aspectFit'
            }
        }

        return wrapper.innerHTML;
    }

    /*
   * 向右滚动
   * */
    static scrollLeft(el, left, time) {
        let nowScrollLeft = el.scrollLeft;
        let total = left - nowScrollLeft;
        let space = total / time;
        let scrollLeft = nowScrollLeft;
        let timer = setInterval(() => {
            time--;
            scrollLeft += space;
            if (time >= 0) {
                el.scrollLeft = scrollLeft;
            } else {
                clearInterval(timer);
            }
        }, 1)

    }

    /*
    * 向上滚动
    * */
    static scrollTop(el, left, time) {

        let nowScroll = el.scrollTop;
        let total = left - nowScroll;
        let space = total / time;
        let scroll = nowScroll;
        let timer = setInterval(() => {
            time--;
            scroll += space;
            if (time >= 0) {
                el.scrollTop = scroll;
            } else {
                clearInterval(timer);
            }
        }, 1)

    }
}

export default MUtil;