﻿function IsSelected(props) {
    const selected = props.IsSelected;
    if (selected) {
        return <span class="icon-x remove-filter"></span>;
    } else
        return <span></span>;
}

function IsDone(props) {
    const done = props.stateDictionary;
    if (done >= 9) {
       
        return <div></div>;
    } else {
       
        return <div class="load-tree"><img class="load-tree-view" src="/Content/Images/Spinner-1s-200px.gif" /></div>;
    }
}

class CatDictionary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            listDictionary: []
        };
    }
    getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    componentDidMount() {
        var dicType = this.props.dictionaryType;
        var currentUrl = encodeURIComponent(window.location.href);
        fetch("/Dictionary/GetDictionaryForFilterSearchAdvanceItem?dictionaryType=" +
            dicType +
            "&seacrhUrl=" +
            currentUrl)
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        isLoaded: true,
                        listDictionary: result
                    });
                    this.props.updateTotalDictionary();
                },
                // Note: it's important to handle errors here
                // instead of a catch() block so that we don't swallow
                // exceptions from actual bugs in components.
                (error) => {
                    this.setState({
                        isLoaded: true,
                        error
                    });
                    this.props.updateTotalDictionary();
                }
            );

    }

    displayLoadingPage() {
        //window["displayLoadingBlockWindow"](true);
    }

    handleDisplayPopupClick(dictionaryType) {
        let ids = [];
        const { error, isLoaded, listDictionary } = this.state;
        const listDictionarys = listDictionary.ListDictionarys;
        listDictionarys.map(i => {
            ids.push(i.Id);
        });
        document.getElementById('DictionaryModal').style.display = "block";
        document.getElementById('ifrMoreDictionary').src =
            "/Dictionary/LoadMoreAdvancedListDictionary?DictionaryType=" +
            dictionaryType + "&PageIndex=1&OrderBy=1" + "&SkipIDs=" +
            ids.join(",") + "&SearchUrl=" + encodeURIComponent(window.location.href);
        
        return false;
    }

    render() {
        const { error, isLoaded, listDictionary } = this.state;
        const listDictionarys = listDictionary.ListDictionarys;
        const pagingFilteringContext = listDictionary.PagingFilteringContext;
        let addMore;
        if (error) {
            return <div></div>;
        } else if (!isLoaded) {
            return <div></div>;
        } else {
            if (pagingFilteringContext.TotalPages >= 2) {
                addMore = <li class="xem_them"><a onClick={() => this.handleDisplayPopupClick(this.props.dictionaryType)}>Xem thêm &gt;&gt;&gt;</a></li>;
            }
            else {
                addMore = <li></li>;
            }
            if (listDictionarys.length == 0) {
                return <div></div>;
            } else {
                const colorStyle = { color: "#201e67" };
                var classType = "fas fa-user-shield";
                var dicType = this.props.dictionaryType;
                switch (dicType) {
                    case "1":
                        classType = "fas fa-user-cog";
                        break;
                    case "3":
                        classType = "fa fa-key";
                        break;
                    case "10":
                        classType = "fa fa-file";
                        break;
                    case "2":
                        classType = "fab fa-buysellads";
                        break;
                    case "9":
                        classType = "fa fa-calendar";
                        break;
                    case "4":
                        classType = "fa fa-mailbox";
                        break;
                    case "5":
                        classType = "fa fa-tags";
                        break;
                    case "6":
                        classType = "fa fa-language";
                        break;
                    case "8":
                        classType = "fa fa-tree";
                        break;
                    case "12":
                        classType = "fa fa-university";
                        break;
                    case "13":
                        classType = "fa fa-cogs";
                        break;
                    default:
                        classType = "fa fa-anchor";
                        break;
                }
                return (
                    <li class="root ">
                        <a data-toggle="collapse" class="icon-btn" data-target={"#tag" + this.props.dictionaryType} style={colorStyle}><i class={classType} aria-hidden="true"></i> {this.props.title} </a>
                        <ul id={"tag" + this.props.dictionaryType} class="sub-filter ">
                            {listDictionarys.map(item => (
                                <li class="lv1">
                                    <a onClick={() => this.displayLoadingPage()}  href={item.UrlLink}>{item.DisplayEntry}  ({item.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                    <IsSelected IsSelected={item.IsSelected} href={item.UrlLink} /></a>
                                </li>
                            ))}
                            {addMore}
                        </ul>
                    </li>
                );
            }
        }
    }
}

class CatObjectLocationDictionary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            listDictionary: []
        };
    }
    getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    componentDidMount() {
        var dicType = this.props.dictionaryType;
        var currentUrl = encodeURIComponent(window.location.href);
        fetch("/Dictionary/GetDictionaryForFilterSearchAdvanceItem?dictionaryType=" +
            dicType +
            "&seacrhUrl=" +
            currentUrl)
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        isLoaded: true,
                        listDictionary: result
                    });
                    this.props.updateTotalDictionary();
                },
                (error) => {
                    this.setState({
                        isLoaded: true,
                        error
                    });
                    this.props.updateTotalDictionary();
                }
            );

    }

    displayLoadingPage() {
        //window["displayLoadingBlockWindow"](true);
    }

    render() {
        const { error, isLoaded, listDictionary } = this.state;
        const listDictionaries = listDictionary.ListDictionarys;
        
        if (error) {
            return <div></div>;
        } else if (!isLoaded) {
            return <div></div>;
        } else {
            if (listDictionaries.length == 0) {
                return <div></div>;
            } else {
                try {
                    const child = listDictionaries.find(e => e.Id == 1);
                    const childOpen = listDictionaries.find(e => e.Id == 11);
                    const childClose = listDictionaries.find(e => e.Id == 12);
                    const adult = listDictionaries.find(e => e.Id == 2);
                    const adultOpen = listDictionaries.find(e => e.Id == 21);
                    const adultClose = listDictionaries.find(e => e.Id == 22);
                    const vehicle = listDictionaries.find(e => e.Id == 3);
                    let empty = true;

                    //console.log(child);
                    //console.log(childOpen);
                    //console.log(childClose);
                    //console.log(adult);
                    //console.log(adultOpen);
                    //console.log(adultClose);
                    //console.log(vehicle);

                    const colorStyle = { color: "#201e67" };
                    var classType = "fa fa-object-group";
                    var classTypeChild = "fa fa-child";
                    var classTypeAdult = "fa fa-male";
                    var classTypeVehicle = "fas fa-truck-moving";

                    if (childOpen.NumberNo == 0 && childClose.NumberNo == 0) {
                        child.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        child.displayStyle = { display: "block" };
                    }

                    if (childOpen.NumberNo == 0) {
                        childOpen.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        childOpen.displayStyle = { display: "block" };
                    }

                    if (childClose.NumberNo == 0) {
                        childClose.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        childClose.displayStyle = { display: "block" };
                    }

                    if (adultOpen.NumberNo == 0 && adultClose.NumberNo == 0) {
                        adult.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        adult.displayStyle = { display: "block" };
                    }

                    if (adultOpen.NumberNo == 0) {
                        adultOpen.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        adultOpen.displayStyle = { display: "block" };
                    }

                    if (adultClose.NumberNo == 0) {
                        adultClose.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        adultClose.displayStyle = { display: "block" };
                    }

                    if (vehicle.NumberNo == 0) {
                        vehicle.displayStyle = { display: "none" };
                    }
                    else {
                        empty = false;
                        vehicle.displayStyle = { display: "block" };
                    }

                    if (empty) return <div></div>;

                    return (
                        <li class="root ">
                            <a data-toggle="collapse" class="icon-btn" data-target={"#tag" + this.props.dictionaryType} style={colorStyle}><i class={classType} aria-hidden="true"></i> {this.props.title} </a>
                            <ul id={"tag" + this.props.dictionaryType} class="sub-filter ">
                                <li class="lv1">
                                    <a style={child.displayStyle}><i class={classTypeChild} aria-hidden="true"></i> {child.DisplayEntry} </a>
                                    <ul class="sub-filter" style={child.displayStyle}>
                                        <li class="lv-1" style={childOpen.displayStyle}>
                                            <a onClick={() => this.displayLoadingPage()} href={childOpen.UrlLink}>{childOpen.DisplayEntry}  ({childOpen.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                        <IsSelected IsSelected={childOpen.IsSelected} href={childOpen.UrlLink} /></a>
                                        </li>
                                        <li class="lv-1" style={childClose.displayStyle}>
                                            <a onClick={() => this.displayLoadingPage()} href={childClose.UrlLink}>{childClose.DisplayEntry}  ({childClose.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                        <IsSelected IsSelected={childClose.IsSelected} href={childClose.UrlLink} /></a>
                                        </li>
                                    </ul>
                                </li>
                                <li class="lv1">
                                    <a style={adult.displayStyle}><i class={classTypeAdult} aria-hidden="true"></i> {adult.DisplayEntry} </a>
                                    <ul class="sub-filter" style={adult.displayStyle}>
                                        <li class="lv-1" style={adultOpen.displayStyle}>
                                            <a onClick={() => this.displayLoadingPage()} href={adultOpen.UrlLink}>{adultOpen.DisplayEntry}  ({adultOpen.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                        <IsSelected IsSelected={adultOpen.IsSelected} href={adultOpen.UrlLink} /></a>
                                        </li>
                                        <li class="lv-1" style={adultClose.displayStyle}>
                                            <a onClick={() => this.displayLoadingPage()} href={adultClose.UrlLink}>{adultClose.DisplayEntry}  ({adultClose.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                        <IsSelected IsSelected={adultClose.IsSelected} href={adultClose.UrlLink} /></a>
                                        </li>
                                    </ul>
                                </li>
                                <li class="lv1">
                                    <a style={vehicle.displayStyle} onClick={() => this.displayLoadingPage()} href={vehicle.UrlLink}><i class={classTypeVehicle} aria-hidden="true"></i> {vehicle.DisplayEntry}  ({vehicle.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                        <IsSelected IsSelected={vehicle.IsSelected} href={vehicle.UrlLink} /></a>
                                </li>
                            </ul>
                        </li>
                    );

                } catch (except) {
                    console.log(`Critical error: ${except}`)
                    return <div></div>
                }
            }
            
        }
    }
}

class CatYearDictionary extends CatDictionary {
    constructor(props) {
        super(props);
    }

    handleDisplayPopupClick(dictionaryType) {
        document.getElementById('DictionaryModal').style.display = "block";
        document.getElementById('ifrMoreDictionary').src = "/Dictionary/LoadMoreAdvancedListDictionary?DictionaryType=" + dictionaryType + "&SearchUrl=" + encodeURIComponent(window.location.href) + "&PageIndex=1&OrderBy=2";
        return false;
    }

    render() {
        const { error, isLoaded, listDictionary } = this.state;
        const listDictionarys = listDictionary.ListDictionarys;
        const pagingFilteringContext = listDictionary.PagingFilteringContext;
        let addMore;

        if (error) {
            return <div></div>;
        } else if (!isLoaded) {
            return <div></div>;
        } else {

            if (pagingFilteringContext.TotalPages >= 2) {
                addMore = <li class="xem_them"><a onClick={() => this.handleDisplayPopupClick(this.props.dictionaryType)}>Xem thêm &gt;&gt;&gt;</a></li>;
            } else {
                addMore = <li></li>;
            }
            if (listDictionarys.length == 0) {
                return <div></div>;
            }
            else {
                return (
                    <li class="root ">
                        <a data-toggle="collapse" data-target={"#tag" + this.props.dictionaryType}> {this.props.title} </a>
                        <ul id={"tag" + this.props.dictionaryType} class="sub-filter">
                            {listDictionarys.map(item => (
                                <li class="lv1">
                                    <a href="javascript:void(0)" data-toggle="collapse" data-target={"#child-tag" + item.Id}>{item.DisplayEntry} ({item.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})</a>
                                    <ul id={"child-tag" + item.Id} class="collapse">
                                        {
                                            item.ChildModels.map(
                                                childItem => (
                                                    <li class="lv1">
                                                        <a href={childItem.UrlLink}>{childItem.DisplayEntry} ({childItem.NumberNo.toLocaleString(undefined, { maximumFractionDigits: 2 })})
                                                        <IsSelected IsSelected={childItem.IsSelected} href={childItem.UrlLink} /></a>
                                                    </li>
                                                )
                                            )
                                        }
                                    </ul>
                                    <IsSelected IsSelected={item.IsSelected} href="javascript:void(0)" />
                                </li>
                            ))}
                            {addMore}
                        </ul>
                    </li>
                );
            }

        }
    }
}

class DictionaryTree extends React.Component {
    constructor(props) {
        super(props);
        this.state = { totalDictionary: 0 };
        this.countCallAjaxDictionary = this.countCallAjaxDictionary.bind(this);
    }
    countCallAjaxDictionary() {
        this.setState({ totalDictionary: this.state.totalDictionary + 1 });
    }

    toggle() {
        this.setState({ addClass: !this.state.addClass });
    }

    render() {
        let boxClass = ["filter"];
        if (this.state.addClass) {
            boxClass.push('open');
        }
        return (
            <div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>
                <a href="javascript:void(0)" class="menu-fitter"><i class="fas fa-filter"></i></a>
                <ul class="list-filter" id="menu_fitter">
                    <CatObjectLocationDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="14" title="Đối tượng - Vị trí" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="10" title="Dạng tài liệu" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="11" title="Định dạng tài liệu" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="1" title="Tác giả" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="3" title="Từ khóa" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="5" title="Tiêu đề đề mục" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="2" title="Nhà xuất bản" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="9" title="Năm xuất bản" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="8" title="Phân loại DDC" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="4" title="Series" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="6" title="Ngôn ngữ" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="12" title="Thư viện" />
                    <CatDictionary updateTotalDictionary={this.countCallAjaxDictionary} stateDictionary={this.state.totalDictionary} dictionaryType="13" title="Loại tài liệu" />
                </ul>
                <IsDone stateDictionary={this.state.totalDictionary} />
            </div>
        )
    }
}

ReactDOM.render(<DictionaryTree />, document.getElementById("column-right"));