import React from 'react';
import { Row, Col, Button } from 'neatui';
import xhr from 'SERVICE/xhr';
import './index.scss';
import BaseComponent from 'COMPONENT/common/BaseComponent';
import { withRouter } from 'react-router-dom';
import { success, error } from 'UTIL/notification';
import { isArray, getSearchParams, switchDataWithShowInfo, parseData2Url, parseFixedParameter } from 'UTIL/util';
import SearchBar from 'COMPONENT/container/SearchBar';
import projectConfig from 'CONFIG/projectConfig.json';

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

class Detail extends BaseComponent {
    constructor(props, context) {
        super(props, context);
        this.env = localHost.indexOf(window.location.hostname) > -1 ? 'local.' : '';
        const { getInstance } = props;
        if (typeof getInstance === 'function') {
            getInstance(this);
        }
        this.searchParams = getSearchParams();
        this.config = this.props.config;
        this.notInit = (this.config.basic && this.config.basic.notInit) || false;
        this.state = {
            searchForm: {},
            detailData: {},
            p2c: false
        };
    }

    componentDidMount() {
        if (!this.state.p2c && !this.notInit) this.fetchDataHandler();
    }

    parentToChildren = (params) => {
        this.setState({
            p2c: true
        }, () => {
            this.fetchDataHandler(JSON.parse(JSON.stringify(params || {})));
        });
    }

    resetHandler = () => {
        this.setState({
            detailData: {},
            p2c: false
        });
    }

    fetchDataHandler = (params) => {
        const mine = this;
        const json = JSON.parse(JSON.stringify(params || {}));
        const { searchForm } = mine.state;
        Object.keys(searchForm).forEach((key) => {
            if (searchForm[key]) {
                json[key] = searchForm[key];
            }
        });
        let searchParams = mine.searchParams || {};
        if (mine.config.basic && mine.config.basic.isNeedLocationSearch && isArray(mine.config.basic.isNeedLocationSearch)) {
            searchParams = {};
            for (let i = 0; i < mine.config.basic.isNeedLocationSearch.length; i += 1) {
                const key = mine.config.basic.isNeedLocationSearch[i];
                searchParams[key] = mine.searchParams[key];
            }
        }
        const { url, data } = parseData2Url({
                    ...parseFixedParameter(mine.config.fixedParameter),
                    ...parseFixedParameter(mine.config.basic.fixedParameter),
                    ...searchParams,
                    ...searchForm,
                    ...json
                }, mine.config.basic[`${this.env}url`], mine.config.basic.accept, mine.config.basic.urlParams);
        if (url) {
            xhr({
                url,
                method: mine.config.basic.method || 'get',
                data,
                type: 'json',
                contentType: mine.config.basic.contentType,
                notSwitchArrToStr: mine.config.basic.notSwitchArrToStr,
                notAcceptEmptyStr: mine.config.basic.notAcceptEmptyStr
            }).then((rs) => {
                if (rs[projectConfig.codeKey] === projectConfig.code) {
                    mine.setState({
                        detailData: mine.props.parseData ? mine.props.parseData(rs.data || {}) : (rs.data || {})
                    });
                } else {
                    error(rs[projectConfig.msg]);
                }
            });
        }
    };

    exportDataHandler = () => {
        const downloadURL = '';
        const { allSearchForms } = this.state;
        const searchFormArr = [];
        Object.keys(allSearchForms).forEach((key) => {
            searchFormArr.push(`${key}=${allSearchForms[key]}`);
        });
        $.ajax({
            url: downloadURL,
            type: "post",
            data: allSearchForms,
            success: (response, status, request) => {
                const disp = request.getResponseHeader('Content-Disposition');
                if (disp && disp.search('attachment') !== -1) {
                    const formStr = searchFormArr.join('&');
                    const form = $(`<form method="POST" action="${downloadURL}?${formStr}">`);
                    form.append($('<input type="hidden" name="filename">'));
                    $('body').append(form);
                    form.submit();
                }
            },
            error: (e) => {
                console.error("请求出错(请检查相关网络状况.)", e);
            }
        });
    }

    switchData = (item) => {
        const mine = this;
        const { detailData } = mine.state;
        const { searchChild, history } = mine.props;
        let text = '';
        if (isArray(item.key)) {
            item.key.forEach(ik => {
                text += `${detailData[ik] || '-'}${item.separator || '/'}`;
            });
            text = text.substr(0, text.length - 1);
        } else {
            text = detailData[item.key];
        }
        const nullLabel = mine.config.basic.nullLabel || projectConfig.nullLabel || '';
        if (item.switch) {
            if (item.switch === 'alias') {
                const { aliasMap } = mine.props;
                Object.assign(item, {
                    "showinfo": {
                        "type": "switch",
                        "switchtype": "alias",
                        "aliasInfo": aliasMap[item.alias] || {}
                    }
                });
            } else if (item.switch === 'timestamp') {
                Object.assign(item, {
                    "showinfo": {
                        "type": "switch",
                        "switchtype": "timestamp",
                        "format": "YYYY-MM-DD HH:mm:ss"
                    }
                });
            }
        }
        if (item.showinfo && item.showinfo.type === 'route' && item.showinfo.goto) {
            return <Button
                        variant="text" color={item.primary || 'info'}
                        size="small"
                        style={{'height': 'auto'}}
                        onClick={() => {
                            history.push(`${item.showinfo.goto}`);
                            if (searchChild) searchChild();
                        }}>{text}</Button>;
        }
        if (item.showinfo && item.showinfo.type === 'switch') {
            if (item.showinfo && item.showinfo.switchtype === 'array') {
                return text ? (text || []).map((aItem) => <div>{aItem}</div>) : '-';
            }
            return switchDataWithShowInfo(text, item.showinfo, nullLabel);
        }
        return text;
    }

    getDetailContent = () => {
        const mine = this;
        return mine.config.basic.columns.map((item, i) => {
            const containerStyle = {
                borderBottom: '0',
                borderRight: 'solid 1px #AAAAAA'
            };
            if (mine.config.basic.columns.length - 1 === i) {
                containerStyle.borderBottom = 'solid 1px #AAAAAA';
            }
            return (<Row justify="center" align="stretch" style={containerStyle}>{
                item.map(sitem => {
                    return (<Col size={sitem.width} className="item-container">{
                        sitem.type !== 'img' ? sitem.keys.map((tt, index) => {
                            const style = {
                                borderBottom: 'solid 1px #AAAAAA'
                            };
                            if (sitem.keys.length - 1 === index) {
                                style.borderBottom = '0';
                            }
                            Object.assign(style, (tt.style || {}));
                            return (<Row justify="center" align="stretch" style={style}>
                                <Col size={8} className="item-key">{tt.label}</Col>
                                <Col size={16} className="item-val">{mine.switchData(tt) || '-'}</Col>
                            </Row>);
                        }) : <div style={{
                            height: '100%',
                            textAlign: 'center'
                        }}>
                                <img style={{ width: '122px', height: '122px' }} alt='' src={mine.state.detailData.avatar || ''} />
                            </div>
                    }</Col>);
                })
            }</Row>)
        });
    }

    switchJsOrJson = (data) => {
        xhr({
            url: '/local/api/switchJsOrJson',
            method: 'post',
            data,
            type: 'json'
        }).then((rs) => {
            if (rs[projectConfig.codeKey] === projectConfig.code) {
                success('格式转换成功!');
            } else {
                error(rs[projectConfig.msg]);
            }
        });
    }

    render() {
        const { detailData } = this.state;
        return (
            <Row className="mb-10">
                <Col>
                    <div className={!this.config.nbg ? "section" : ''}>
                        {
                            !this.props.notModify && this.env === 'local.' ? <Button
                                variant="contained" color="info"
                                size="small"
                                style={{"height": "auto", "float": "right"}}
                                onClick={() => {
                                    this.switchJsOrJson({
                                        path: this.props.path,
                                        uuid: this.config.uuid
                                    })
                                }}>toJS</Button> : ''
                        }
                        <div className="tool-bar">
                            {
                                this.config.filter && this.config.filter.length > 0 ? <SearchBar
                                    filter={this.config.filter || []}
                                    search={this.fetchDataHandler}
                                    filterLabel={this.config.filterLabel || '搜索'}
                                    searchFormData={this.state.searchForm}
                                ></SearchBar> : ''
                            }
                        </div>
                        {
                            (this.config.name || this.config.export) ? <div className="table-action" style={{
                                height: '54px',
                                lineHeight: '54px',
                                padding: '0 5px'
                            }}>
                                {
                                    this.config.name ? <span style={{ fontSize: 16, fontWeight: 'bold' }}>{this.config.name}</span> : ''
                                }
                                {
                                    this.config.name && this.config.description ? <span style={{ marginLeft: 12 }}>({ this.config.description })</span> : ''
                                }
                                {
                                    this.config.export && Object.keys(detailData).length > 0 ? <Button
                                        variant="contained" color={this.config.export.primary || 'primary'}
                                        onClick={this.exportDataHandler}
                                        style={{ float: 'right', marginLeft: '10px', marginRight: '10px' }}
                                    >导出数据</Button> : ''
                                }
                            </div> : ''
                        }
                        {this.getDetailContent()}
                    </div>
                </Col>
            </Row>
        );
    }
}

export default withRouter(Detail);
