import { isArray, isObject } from 'cbkfe-utils';
import ReactDom, { unmountComponentAtNode } from 'react-dom';
import React, { Component, createRef } from 'react';
import CommonHeader from '../CommonHeader';
import classNames from 'classnames';
import './style';

const closeMountComponentAtNode = (ele) => {
    ReactDom.unmountComponentAtNode(ele);
    if (ele && ele.parentNode) {
        ele.parentNode.removeChild(ele);
    }
};

/**
 * @saleRuleList { object }  购买须知列表数据
 * @hideTitles { object }  需要隐藏的列表 ，之所以给一个列表，是因为不同单子在不同情况下拿到的购买须知具体板块不一样，可能刚好你设定的字段碰巧没有
 * @hiddenKey { number } 从第几个开始隐藏
 * @isServiceDescription { boolean } true代表展示服务说明页的样式
 */
export default class PurchaseNotes extends Component {

    state = {
        hiddenText: '收起',
        hiddenIndex: 0,
        initHiddenList: '',   // 默认
        initHiddenIndex: '',
        bottomPutaway: false, // 底部展示收起  true为收起，false为展开
        saleRuleList: [],
        hideTitles: [],
        hiddenKey: '',
        param: {}
    }

    bottomBtnRef = createRef(null);

    componentDidMount() {
        this.handleDealSaleRules();
    }

    hiddenTextListFromShowTitles(source, showTitles) {
        return new Promise(resolve => {
            showTitles = [...showTitles];
            if (!isArray(showTitles, true)) return [];
            let showIndex = -1;
            let baseIndex = -1; // 这个是用来在自动计算的时候保持底线的，也就是初始默认展示几个那就展示几个，不管超不超屏幕
            source.forEach((rule, index) => {
                try {
                    let title = rule.title.title;
                    if (showTitles.includes(title)) {
                        showTitles = showTitles.filter(item => item !== title);
                        showIndex = index;
                    }
                } catch (error) { }
            });
            baseIndex = showIndex;
            const renderByIndex = () => {
                let div = document.createElement('div');
                document.body.appendChild(div);
                let renderSource = source.slice(0, showIndex + 1);
                const domRef = createRef(null);
                let dom = <div ref={domRef} style={{ visibility: 'hidden', position: 'fixed', top: 0, left: 0, height: '100vh', width: '100vw' }}>
                    <div className="purchase-container purchase-container--preview">
                        {renderSource.map((saleRule, index) => <div key={index}>{this.renderItem(saleRule)}</div>)}
                    </div >
                </div>;
                ReactDom.render(dom, div, () => {
                    let resultDom = document.querySelector('.purchase-container--preview');
                    const _resolve = (resultIndex) => {
                        closeMountComponentAtNode(div);
                        resolve({
                            hiddenTextList: source.slice(resultIndex + 1).map(item => item.title && item.title.title),
                            hiddenIndex: resultIndex + 1
                        });
                    };
                    if (resultDom.scrollHeight > window.screen.availHeight) {
                        if (showIndex === baseIndex) { // 默认给的几个模块超了 没关系！！！
                            _resolve(showIndex);
                        } else { // 如果默认展示的模块没超，但是增量的模块超出了，那么就回退一位
                            _resolve(showIndex - 1);
                        }
                    } else if (resultDom.scrollHeight === window.screen.availHeight) {
                        _resolve(showIndex);
                    } else if (showIndex < source.length - 1) {
                        closeMountComponentAtNode(div);
                        showIndex += 1;
                        renderByIndex();
                    }
                });
            };
            renderByIndex();

        });
    }

    // 处理SaleRules
    handleDealSaleRules = async (data) => {
        const { saleRuleList, hideTitles, hiddenKey, showTitles } = this.props;
        let hiddenIndex = 0;
        let hiddenTextList = [];

        // 通过给需要隐藏的板块进行隐藏
        if (!saleRuleList) return;
        if (isArray(showTitles, true)) {
            const result = await this.hiddenTextListFromShowTitles(saleRuleList, showTitles);
            hiddenIndex = result.hiddenIndex;
            hiddenTextList = result.hiddenTextList;
        } else if (isArray(hideTitles, true)) {
            let isFind = false;
            isArray(saleRuleList, true) && saleRuleList.forEach((saleRuleItem, index) => {
                hideTitles.forEach((hiddenItem) => {
                    if (saleRuleItem.title.title === hiddenItem || isFind) {
                        hiddenTextList.push(saleRuleItem.title.title);
                        !hiddenIndex && (hiddenIndex = index);
                        isFind = true;
                    }
                });
            });
        } else if (hiddenKey) {
            hiddenIndex = hiddenKey;
            isArray(saleRuleList, true) && saleRuleList.forEach((saleRuleItem, index) => {
                if (index >= hiddenKey) {
                    hiddenTextList.push(saleRuleItem.title.title);
                }
            });
        }

        // 处理超过三个就展示等
        let dealInitHiddenList = Array.from(new Set(hiddenTextList));
        if (dealInitHiddenList.length > 3) {
            dealInitHiddenList = dealInitHiddenList.slice(0, 3);
            dealInitHiddenList[2] = dealInitHiddenList[2] + '等';
        }

        this.setState({
            param: data,
            initHiddenList: dealInitHiddenList,
            initHiddenIndex: hiddenIndex,
            hiddenIndex: hiddenIndex,
            bottomPutaway: false,
            hiddenText: dealInitHiddenList.join('、'),
        });
    }

    handleButton = () => {
        const { initHiddenList, initHiddenIndex, bottomPutaway } = this.state;
        const { saleRuleList } = this.props;
        this.setState({
            hiddenText: bottomPutaway ? initHiddenList.join('、') : '收起',
            hiddenIndex: bottomPutaway ? initHiddenIndex : saleRuleList.length,
            bottomPutaway: !bottomPutaway
        });
    }

    // 标题
    purchaseNotesTitle(title) {
        if (!title) return;
        return <React.Fragment>
            <header className="title-row">
                <div className="stb-title">{title.title}</div>
            </header>
        </React.Fragment>;
    }

    // 内容部分
    purchaseNotesContext(termItem, itemIndex) {
        if (!isObject(termItem, true)) return;
        const { subTextTitle, subTextTitleIcon, textList, tableList, subTipList, textStyle, subTextStyle } = termItem;
        return <React.Fragment key={itemIndex} >
            {/* 内容副标题 */}
            {
                subTextTitle && subTextTitleIcon ?
                    <header className="title-row_normal">
                        {subTextTitleIcon && <img className="img-size " src={subTextTitleIcon} />}
                        {subTextTitle && <p className="detail-title">{subTextTitle}</p>}
                    </header>
                    :
                    subTextTitle && <header className="title-row_noIcon">
                        <p className="detail-item">{subTextTitle}</p>
                    </header>
            }

            {/* string类型文本展示 */}
            {
                isArray(textList, true) && textList.map((textItem, index) =>
                    <React.Fragment key={index}>
                        <div className="service-description__bottom">
                            <p className={classNames({
                                'detail': textStyle === 1,
                                'detail--noPunctuation': textStyle === 2
                            })}>{textItem}</p>
                        </div>
                    </React.Fragment>)
            }

            {/* 表格 */}
            {
                isArray(tableList, true) && <div className="stb-table__show">
                    <section className="stb-table">
                        <div className="table-context">
                            {
                                tableList.map((pro, index) => {
                                    return <div key={index} className={`stb-table-content ${index === 0 ? 'stb-table__header' : ''}`}>
                                        {pro.map((text, index) => {
                                            return index === 0
                                                ? <span key={index} className="stb-table__firstColumn" dangerouslySetInnerHTML={{ __html: text }} ></span>
                                                : <span key={index} className="stb-table__normalColumn" dangerouslySetInnerHTML={{ __html: text }}></span>;
                                        })}
                                    </div>;
                                })
                            }
                        </div>
                    </section>
                </div>
            }

            {/* 小模块解释部分 */}
            {/* subTextStyle === 2 文案前面无点，样式控制 */}
            {
                isArray(subTipList, true) && <div className="descript-detailList__layout">
                    {subTipList.map((detailItem, detailIndex) =>
                        <p className={classNames({
                            'detail-item': subTextStyle === 1,
                            'detail__item--noPunctuation': subTextStyle === 2,
                        })} key={detailIndex}>{detailItem}</p>)}
                </div>
            }
        </React.Fragment>;
    }

    // 购买须知各板块底部提示部分，现在没有，但因为后端有给字段，先写好，
    purchaseNotesTipsList(tipList) {
        if (!tipList) return;
        return <React.Fragment>
            {tipList.map((tip, index) => <p key={tip + index} className="purchase-note__tip "><span className="purchase-note__tips">*</span>{tip}</p>)}
        </React.Fragment>;
    }

    renderItem(saleRule) {
        if (!saleRule) return;
        return <div className="purchase-note">
            {this.purchaseNotesTitle(saleRule.title)}
            {isArray(saleRule.termList, true) && saleRule.termList.map(this.purchaseNotesContext)}
            {this.purchaseNotesTipsList(saleRule.tipList)}
        </div>;
    }

    getSnapshotBeforeUpdate(preProps, preState) {
        if (preState.bottomPutaway) {
            let rect = this.bottomBtnRef.current.getBoundingClientRect();
            return rect;
        }
        return null;
    }

    componentDidUpdate(preProps, preState, snapshot) {
        if (!isArray(preProps.saleRuleList, true) && isArray(this.props.saleRuleList, true)) {
            this.handleDealSaleRules();
        }
        if (snapshot) {
            let top = snapshot.top;
            window.scrollTo(0, this.bottomBtnRef.current.offsetTop - top);
        }
    }

    render() {
        let { className = '', props, saleRuleList, isServiceDescription, title } = this.props;
        if (!isArray(saleRuleList, true)) return null;

        const { hiddenText, hiddenIndex, bottomPutaway } = this.state;
        // 是否展示底部展开收起
        const isShowbutton = (!!hiddenIndex && hiddenIndex <= saleRuleList.length) && isArray(saleRuleList, true);

        return (
            <div {...props} className={`${isServiceDescription ? 'service-description__sta' : 'purchase-container'}  ${className}`}>
                {!isServiceDescription && <CommonHeader title={title || '购买须知'} />}
                {
                    saleRuleList.map((saleRule, index) =>
                        (!hiddenIndex || index < hiddenIndex) && <div key={index}>
                            {this.renderItem(saleRule)}
                        </div>)
                }
                {
                    isShowbutton &&
                    <div ref={this.bottomBtnRef} className="bottom-layout" role="button" onClick={this.handleButton}>
                        <div className="bottom-text" >{hiddenText}</div>
                        <i className={`iconfont icon--arrow ${bottomPutaway ? 'arrow-up' : 'arrow-down'} `} />
                    </div>
                }
            </div >

        );
    }
}
