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 * as barMan from 'UTIL/barMan';
import ReactECharts from 'COMPONENT/container/charts/ReactECharts';
import { isArray, getSearchParams, parseFixedParameter, parseData2Url } from 'UTIL/util';
import SearchBar from 'COMPONENT/container/SearchBar';
import projectConfig from 'CONFIG/projectConfig.json';

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

class Barman 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.uuid = this.props.uuid || '';
        this.state = {
            loading: true,
            data: {},
            searchForm: {
            }
        };
    }

    componentDidMount() {
        this.fetchDataHandler();
    }

    parentToChildren = (params) => {
        this.fetchDataHandler(JSON.parse(JSON.stringify(params || {})));
    }

    resetHandler = () => {
        this.setState({
            data: {}
        });
    }

    getSearchData = (url, params) => {
        const mine = this;
        const { searchForm } = mine.props;
        
        let searchParams = mine.searchParams || {};
        if (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];
            }
        }
        return parseData2Url({
                ...parseFixedParameter(mine.config.fixedParameter),
                ...parseFixedParameter(mine.config.basic.fixedParameter),
                ...searchParams,
                ...searchForm,
                ...mine.state.searchForm,
                ...(params || {})
            }, url);
    }

    fetchDataHandler = (params) => {
        const mine = this;
        const { data, url } = mine.getSearchData(mine.config.basic[`${this.env}url`], params);
        if (url) {
			xhr({
				url,
				method: mine.config.basic.method || 'get',
				data,
				type: 'json',
			    contentType: mine.config.basic.contentType,
                notSwitchArrToStr: mine.config.basic.notSwitchArrToStr,
				complete: () => {
					mine.setState({
						loading: false
					});
				}
			}).then((rs) => {
				if (rs[projectConfig.codeKey] === projectConfig.code) {
                    mine.setState({
                        data: rs.data || {}
                    });
				} else {
					error(rs[projectConfig.msg]);
				}
			});
		} else {
			mine.setState({
				loading: false
			});
        }
    }
	
    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);
            }
        });
    }


    getOption = () => {
        return barMan.getOption(this.config.type, this.config.chart, this.state.data);
    }

    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() {
        return (
            <Row className="mb-10 bar-man">
                <Col>
                    <div className="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}
                                    searchFormData={this.state.searchForm}
                                ></SearchBar> : ''
                            }
                        </div>
                        {
                            (this.config.name || this.config.export) ? <div className="charts-action" style={{
                                height: '54px',
                                lineHeight: '54px',
                                padding: '0 5px'
                            }}>
                                {
                                    this.config.name ? <span style={{fontSize: 16, fontWeight: 'bold'}}>{ this.config.name }</span> : ''
                                }
                                {
                                    this.config.export ? <Button
                                        variant="contained" color={this.config.export.primary || 'primary'}
                                        onClick={this.exportDataHandler}
                                        style={{ float: 'right', marginLeft: '10px', marginRight: '10px' }}
                                    >导出数据</Button> : ''
                                }
                            </div> : ''
                        }
                        {
                            this.state.data.columnMetas && this.state.data.results && this.state.data.columnMetas.length > 0 && this.state.data.results.length > 0 ? <ReactECharts
                                option={this.getOption()}
                                style={{minHeight: '300px', width: '100%'}}
                                className='react-echarts'
                            /> : <div className="no-data">暂无数据</div>
                        }
                    </div>
                </Col>
            </Row>
        );
    }
}

export default withRouter(Barman);
