import React from 'react';
import { Row, Col, Button } from 'neatui';
import xhr from 'SERVICE/xhr';
import './index.scss';
import { success, error } from 'UTIL/notification';
import BaseComponent from 'COMPONENT/common/BaseComponent';
import { withRouter } from 'react-router-dom';
import moment from 'moment';
import 'moment/locale/zh-cn';
import projectConfig from 'CONFIG/projectConfig.json';
import { getSearchParams, isArray, parseData2Url, parseFixedParameter } from '../../../utils/util';

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

class Boardlist 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.state = {
            loading: false,
            dataSrc: {},
            dataSource: []
        };
    }

    componentDidMount() {
        this.fetchDataHandler();
    }

    parentToChildren = (params, formData) => {
        this.fetchDataHandler({
            ...(params || {}),
            ...(formData || {})
        });
    }

    fetchDataHandler = (params) => {
        const mine = this;
        const { url, data } = parseData2Url({
            ...parseFixedParameter(mine.config.fixedParameter),
            ...parseFixedParameter(mine.config.basic.fixedParameter),
            ...(mine.props.searchForm || {}),
            ...(params || {})
        }, mine.config.basic[`${this.env}url`], mine.config.basic.accept, mine.config.basic.urlParams);
        xhr({
            url,
            method: mine.config.basic.method || 'get',
            data,
            contentType: mine.config.basic.contentType,
            notSwitchArrToStr: mine.config.basic.notSwitchArrToStr,
            type: 'json',
            complete: () => {
                mine.setState({
                    loading: false
                });
            }
        }).then((rs) => {
            if (rs[projectConfig.codeKey] === projectConfig.code) {
                mine.setState({
                    dataSrc: rs.data,
                    dataSource: [...(rs.data[mine.config.basic.list || projectConfig.list || 'list'] || [])]
                });
            } else {
                error(rs[projectConfig.msg]);
            }
        });
    }

    goback = (gotoConfig) => {
        let search = `?${Math.random().toFixed(3)}`;
        const values = [...(gotoConfig.gotoValue || [])];
        for (let i = 0; i < values.length; i += 1) {
            const key = values[i];
            if (this.searchParams[key]) {
                search += `&${key}=`;
                search += (this.searchParams[key]);
            }
        }
        const router = gotoConfig.address || '/404';
        this.props.history.push(router + search);
    }

    parseData = (source, config) => {
        const { template, rules, ruleundefind } = (config || {});
        let temStr = template || '';
        for (let i = 0; i < (rules || []).length; i += 1) {
            let srcStr = '';
            if (typeof(rules[i]) === 'string') {
                srcStr = source[rules[i]] || ruleundefind;
            } else {
                srcStr = source[rules[i].key];
                if (rules[i].switchtype === 'timestamp') {
                    srcStr = srcStr ? moment(srcStr).format(rules[i].format) : ruleundefind;
                }
            }
            temStr = temStr.replace('#{key}', srcStr);
        }
        return temStr;
    };

    getDataSource = (dataSource, config) => {
        const { len } = (config || {});
        const result = [];
        for (let i = 0; i < len && i < dataSource.length; i += 1) {
            result.push(dataSource[i]);
        }
        return result;
    };

    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 { dataSource, dataSrc } = this.state;
        return (<Row className="mb-10 boardlist">
            <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> : ''
                    }
                    {
                        this.config.title ? <Row style={Object.assign({ textAlign: "center", display: "block" }, this.config.title.style)}>{this.config.title.name || ''}</Row> : ''
                    }
                    {
                        this.config.basic && this.config.basic.template && isArray(dataSource) && dataSource.length > 0 ?
                            <Row style={Object.assign({ textAlign: "left", display: "block" }, this.config.basic.rowStyle)}>
                                {this.getDataSource((dataSource || []), this.config.basic).map(dataItem => <Col style={Object.assign({ minHeight: "30px", lineHeight: "30px" }, this.config.basic.style)}>{this.parseData(dataItem, this.config.basic)}</Col>)}
                            </Row>
                            : <Row style={Object.assign({ textAlign: "center", display: "block", margin: "15px 0" }, this.config.basic.style)}>{this.config.basic.nodata || '暂无数据'}</Row>
                    }
                    {
                        this.config.link ? <Row style={Object.assign({ "display": "block" }, this.config.link.rowStyle)}>
                            {
                                this.config.link.goto && this.config.link.goto.type === 'route' ? <Button color="info" variant="text"
                                    style={Object.assign({ float: 'right', cursor: 'pointer', paddingTop: 2 }, this.config.link.goto.style)}
                                    onClick={() => { this.goback(this.config.link.goto) }}>{this.config.link.goto.label}</Button> : ''
                            }
                            {
                                this.config.link.goto && this.config.link.goto.type === 'link' ? <div style={Object.assign({ float: 'right' }, this.config.link.goto.style)}>{}</div> : ''
                            }
                            {
                                this.config.link.template ? <div style={Object.assign({ float: 'right' }, this.config.link.style)}>{this.parseData(dataSrc, this.config.link)}</div> : ''
                            }
                        </Row> : ''
                    }
                </div>
            </Col>
        </Row>
        );
    }
}

export default withRouter(Boardlist);
