import React from 'react';
import ReactDom from 'react-dom';
import { Row, Col, Pagination, Button, CheckboxGroup, Checkbox, confirm, DropdownMenu, Upload } from 'neatui';
import { Table, Tooltip, Tag } from 'antd';
import xhr from 'SERVICE/xhr';
import './index.scss';
import { withRouter } from 'react-router-dom';
import { error, success } from 'UTIL/notification';
import { 
    isArray,
    getSearchParams,
    getPaginationConfig,
    downloadExcle,
    switchDataWithShowInfo,
    getBLen,
    parseData2Url,
    switchArrToStrByComma,
    switchArrToStrBySemicolon,
    isImage,
    parseFixedParameter
} from 'UTIL/util';
import BaseComponent from 'COMPONENT/common/BaseComponent';
import SearchBar from 'COMPONENT/container/SearchBar';
import projectConfig from 'CONFIG/projectConfig.json';
import FormModal from '../searchtableactionmodal/Searchtableactionmodal';

const encode = require('nodejs-base64-encode');

const localHost = projectConfig.localhost || [];
localHost.push('localhost');

class Searchtable 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.path = this.props.path || '';
        this.notInit = (this.config.basic && this.config.basic.notInit) || false;
        this.selectedCol = [];
        const columnsInfo = this.completionColumns();
        this.columns = columnsInfo.allColums;
        this.exportColumns = columnsInfo.exportColumns;
        this.state = {
            selectedRowKeys: [],
            defaultCol: columnsInfo.defaultCol || [],
            columns: columnsInfo.defColums || [],
            dataSource: [],
            random: Math.random(),
            tableLoading: !this.notInit,
            pageInfo: {
                pageNo: 1,
                pageSize: 10,
                totalSize: 10
            },
            sortFiled: '',
            order: '',
            searchForm: {},
            p2c: false
        };
    }

    componentDidMount() {
        let canSearch = true;
        const { searchForm, mustArr = [] } = this.props;
        mustArr.forEach(mustItem => {
            if (searchForm[mustItem.key] === '' || searchForm[mustItem.key] === undefined) {
                canSearch = false;
            }
        });
        if (!this.state.p2c && !this.notInit && canSearch) this.fetchDataHandler();
    }

    parentToChildren = (params) => {
        this.setState({
            p2c: true
        }, () => {
            this.fetchDataHandler(1, null, JSON.parse(JSON.stringify(params || {})));
        });
    }

    resetHandler = () => {
        this.setState({
            dataSource: [],
            pageInfo: {
                pageNo: 1,
                pageSize: 10,
                totalSize: 10
            },
            p2c: false
        });
    }

    updateColumns = (e, params) => {
        const re = [];
        for (let i = 0; i < this.columns.length; i+=1) {
            if (params.indexOf(this.columns[i].key) > -1) {
                re.push(this.columns[i]);
            }
        }
        this.setState({
            columns: re
        });
    }

    completionColumns = () => {
        const mine = this;
        const allColums = [...(this.config.basic.columns || [])];
        if (this.config.basic.hasSequence) {
            allColums.unshift({
                title: '序号',
                width: '8%',
                key: 'sequence',
                dataIndex: 'sequence',
                render: (text, data, index) => {
                    const { pageInfo } = mine.state;
                    const increment = (((pageInfo.pageNo - 1) * pageInfo.pageSize) || 0) + index + 1;
                    return <span title={ increment }>{ increment }</span>;
                }
            });
        }
        const defaultCol = [];
        const defColums = [];
        const exportColumns = [];
        let flag = true;
        let nullLabel = '';
        if (mine.config.basic.nullLabel || projectConfig.nullLabel) nullLabel = mine.config.basic.nullLabel || projectConfig.nullLabel || '';
        for (let i = 0; i < allColums.length; i+=1) {
            const item = allColums[i] || {};
            item.dataIndex = item.key;
            item.sorter = item.sort;
            item.align = item.align || 'center';
            item.className = item.className;
            if (!item.hidden) {
                defaultCol.push(item.key);
                defColums.push(item);
            }
            if (!item.notExport) {
                exportColumns.push(item);
            }
            if (mine.config.basic.nullLabel || projectConfig.nullLabel) {
                item.render = (text) => {
                    if (text === undefined || text === null) return nullLabel; 
                    return text;
                }
            }
            if (item.showinfo || item.switch) {
                if (item.showinfo && item.showinfo.type === 'route' && item.showinfo.goto) {
                    item.render = (text, data) => {
                        return <Button
                                    variant="text" color={item.primary || 'info'}
                                    size="small"
                                    style={{'height': 'auto'}}
                                    onClick={() => {
                                        mine.onShowAction('detail', data, item)
                                    }}>{text}</Button>;
                    }
                } else if (item.switch || (item.showinfo && item.showinfo.type === 'switch')) {
                    item.render = (text) => {
                        if (item.switch) {
                            switch(item.switch) {
                                case 'alias':
                                case 'tagalias': {
                                    const { aliasMap } = mine.props;
                                    item.showinfo = {
                                        "type": "switch",
                                        "switchtype": item.switch,
                                        "aliasInfo": aliasMap[item.alias] || {}
                                    };
                                    break;
                                }
                                case 'timestamp':
                                case 'second':
                                    item.showinfo = {
                                        "type": "switch",
                                        "switchtype": item.switch,
                                        "format": item.format || "YYYY-MM-DD HH:mm:ss"
                                    };
                                    break;
                                case 'image':
                                case 'array':
                                case 'percent':
                                    item.showinfo = {
                                        "type": "switch",
                                        "switchtype": item.switch
                                    };
                                    break;
                                case 'str2array':
                                    item.showinfo = {
                                        "type": "switch",
                                        "switchtype": item.switch,
                                        "separator": item.separator
                                    };
                                    break;
                                default:
                                    break;
                            }
                        }
                        if (item.showinfo && item.showinfo.switchtype === 'str2array') {
                            return ((text || '') ? (text || '').split(item.showinfo.separator || '\n') : []).map((aItem) => <div>{aItem}</div>);
                        }
                        if (item.showinfo && item.showinfo.switchtype === 'array') {
                            return (text || []).map((aItem) => <div>{aItem}</div>);
                        }
                        if (item.showinfo && item.showinfo.switchtype === 'image') {
                            if (isImage(text)) return <img style={{height: "60px"}} alt={text} src={text}></img>;
                            return text || nullLabel;
                        }
                        if (item.showinfo && item.showinfo.switchtype === 'tagalias') {
                            return <Tag color={
                                        (item.showinfo.aliasInfo[text] && item.showinfo.aliasInfo[text].color) ||
                                        (item.showinfo.aliasInfo.default && item.showinfo.aliasInfo.default.color) || "" }>
                                    {
                                        (item.showinfo.aliasInfo[text] && item.showinfo.aliasInfo[text].value) || text
                                    }
                                </Tag>;
                        }
                        return <span>
                            {
                                switchDataWithShowInfo(text, item.showinfo, nullLabel)
                            }
                        </span>;
                    };
                } else if (item.showinfo && item.showinfo.type === 'link1' && item.showinfo.goto) {
                    item.render = (text, data) => {
                        let gotoUrl = item.showinfo.goto;
                        for (let j = 0; j < (item.showinfo.gotoValue || []).length; j+=1) {
                            const gotoItem = item.showinfo.gotoValue[j];
                            gotoUrl = gotoUrl.replace('#{key}', data[gotoItem]);
                        }
                        return <a href={gotoUrl} target='_blank' rel='noopener noreferrer'>{text}</a>;
                    }
                } else if (item.showinfo && item.showinfo.type === 'link2' && item.showinfo.goto) {
                    item.render = (text, data) => {
                        return <a href={data[item.showinfo.goto]} target='_blank' rel='noopener noreferrer'>{text}</a>;
                    }
                } else if (item.showinfo && item.showinfo.type === 'tooltip') {
                    item.render = (text, data) => {
                        const len = item.showinfo.len || 30;
                        const { showkey } = item.showinfo;
                        const content = `${(showkey ? data[showkey] : text)}`.substr(0, len);
                        const id = `table-tooltip-${Math.random()}`;
                        return content.length === `${(showkey ? data[showkey] : text)}`.length ? <span>{`${content}`}</span> : <div id={id}><Tooltip
                                    style={{width: 200}}
                                    title={<span>{`${(showkey ? data[showkey] : text)}`}</span>}
                                    getPopupContainer={() => document.getElementById(id)}
                                    trigger={["click"]}>
                                    <p>{`${content}...`}</p>
                                </Tooltip></div>;
                    }
                }
            }
            if (item.key === 'opt') {
                flag = false;
            }
        }
        if (flag && this.config.basic.justOpt) {
            const vals = this.config.basic.justOpt.values || {};
            const optItem = {
                ...this.config.basic.justOpt,
                dataIndex: this.config.basic.justOpt.key,
                align: 'center',
                render: (index, data) => {
                    const userAuth = mine.props.userAuth || [];
                    const { noAuth } = projectConfig;
                    return <span>
                            {
                                vals.map(item => {
                                    const condition = [...(this.config[item.key].condition || [])];
                                    const auth = this.config[item.key].auth || '';
                                    let btnFlag = true;
                                    if(!noAuth && userAuth.indexOf(auth) === -1 && this.env !== 'local.') return '';
                                    for (let i = 0; i < condition.length; i+=1) {
                                        const conditionItem = condition[i];
                                        if (conditionItem.oper === 'notcontain') {
                                            btnFlag = true;
                                            if (conditionItem.values.indexOf(data[conditionItem.key]) > -1) {
                                                btnFlag = false;
                                                break;
                                            }
                                        } else if (conditionItem.oper === 'contain') {
                                            btnFlag = false;
                                            if (conditionItem.values.indexOf(data[conditionItem.key]) > -1) {
                                                btnFlag = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (btnFlag && this.config[item.key]) {
                                        if (this.config[item.key].showtype === 'span') {
                                            return <span>{this.config[item.key].label}</span>;
                                        }
                                        return <Button
                                            variant="contained" color={this.config[item.key].primary || item.primary || 'primary'}
                                            size="small"
                                            style={{margin: '2px'}}
                                            onClick={() => {
                                                if (this.config[item.key].type === 'link') {
                                                    mine.onShowAction('detail', data, this.config[item.key])
                                                } else if (this.config[item.key].type === 'modify') {
                                                    if (this.config[item.key].mode === 'link') {
                                                        mine.onShowAction(item.key, data, this.config[item.key])
                                                    } else {
                                                        mine.createDataHandler(item.key, data)
                                                    }
                                                } else if (this.config[item.key].type === 'delete') {
                                                    this.deleteHandler(data, this.config[item.key]);
                                                } else {
                                                    const { moduleids } = this.config[item.key];
                                                    const { modifyForm } = this.props
                                                    modifyForm(moduleids, data, item.key);
                                                }
                                            }}>{this.config[item.key].label}</Button>;
                                    }
                                    return '';
                                })
                            }
                            </span>;
                }
            }
            allColums.push(optItem);
            if (!this.config.basic.justOpt.hidden) {
                defaultCol.push(this.config.basic.justOpt.key);
                defColums.push(optItem);
            }
        }
        return {
            defaultCol,
            allColums,
            defColums,
            exportColumns
        };
    }

    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, mine.config.basic.accept, mine.config.basic.urlParams);
    }

    fetchDataHandler = (pageNo, pageSize, params) => {
        const mine = this;
        const { parseData } = mine.props;
        const { pageInfo, sortFiled, order } = mine.state;
        const { data, url } = mine.getSearchData(mine.config.basic[`${this.env}url`], params);
		if (url) {
            mine.setState({
                tableLoading: true
            });
			xhr({
				url,
				method: mine.config.basic.method || 'get',
				data: {
                    ...data,
                    ...(sortFiled ? { [mine.config.basic.sortFiled || 'sortFiled']: sortFiled } : {}),
                    ...(order ? { [mine.config.basic.order || 'order']: order } : {}),
                    ...(getPaginationConfig(mine.config.basic.pagination, {pageNo: pageNo || pageInfo.pageNo, pageSize: pageSize || pageInfo.pageSize}))
				},
				type: 'json',
			    contentType: mine.config.basic.contentType,
                notSwitchArrToStr: mine.config.basic.notSwitchArrToStr,
                notAcceptEmptyStr: mine.config.basic.notAcceptEmptyStr,
				complete: () => {
					mine.setState({
						tableLoading: false
					});
				}
			}).then((rs) => {
				if (rs[projectConfig.codeKey] === projectConfig.code) {
                    pageInfo.totalSize = rs.data[mine.config.basic.total || projectConfig.total || 'total'] || (rs.data[mine.config.basic.list || projectConfig.list || 'list'] || []).length || 0;
                    pageInfo.pageNo = pageNo || pageInfo.pageNo;
                    pageInfo.pageSize = pageSize || pageInfo.pageSize;
                    let dataSource = [...(rs.data[mine.config.basic.list || projectConfig.list || 'list'] || [])];
                    if (mine.config.basic.pagination === false) {
                        if (mine.config.basic.list) dataSource = rs.data[mine.config.basic.list] || [];
                        else dataSource = rs.data || [];
                    }
					this.setState({
						dataSource: parseData ? parseData(dataSource) : [...dataSource],
						pageInfo,
                        random: Math.random()
					});
				} else {
					error(rs[projectConfig.msg]);
				}
			});
		} else {
			mine.setState({
				tableLoading: false
			});
        }
    };
    
    beforeUpload = (file) => {
        if (file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
            error('文件格式错误，只支持2010版excel');
            return false;
        }
        const mine = this;
        const { method, logaction, contentType } = mine.config.upload;
        const formData = new FormData();
        formData.append('file', file);
        const headers = {};
        if (contentType) headers['Content-Type'] = contentType;
        fetch(mine.config.upload[`${mine.env}url`], {
            method: method || 'POST',
            headers,
            body: formData
        }).then(res => res.json()).then(rs => {
            if (rs[projectConfig.codeKey] === projectConfig.code) {
                mine.fetchDataHandler(1, mine.state.pageInfo.pageSize);
                success(logaction ? `${logaction}` : '上传成功');
            } else {
                error(rs[projectConfig.msg]);
            }
            return false;
        });
    }

    exportDataHandler = () => {
        const mine = this;
        const { type, method='get', contentType, notSwitchArrToStr } = mine.config.export;
        const searchData = mine.getSearchData(mine.config.export[`${this.env}url`], {});
        let { data } = searchData;
        const { url } = searchData;
        if (!notSwitchArrToStr && !projectConfig.notSwitchArrToStr) {
            if (!projectConfig.toKey || projectConfig.toKey === ',') data = switchArrToStrByComma(data);
            else if (projectConfig.toKey === ';') data = switchArrToStrBySemicolon(data);
        }
        if (type === 'front') {
            xhr({
                url,
                method,
                data,
                type: 'json',
                contentType,
                notSwitchArrToStr
            }).then((rs) => {
                if (rs[projectConfig.codeKey] === projectConfig.code) {
                    downloadExcle(this.exportColumns, rs.data[mine.config.basic.list || projectConfig.list || 'list'] || [], mine.config.export.name || '导出数据');
                } else {
                    error(rs[projectConfig.msg]);
                }
            });
        } else if (type === 'attachment') {
            const searchFormArr = [];
            Object.keys(data).forEach((key) => {
                searchFormArr.push(`${key}=${data[key]}`);
            });
            if (method === 'get' || method === 'GET') {
                window.open(`${url}?${searchFormArr.join('&')}`)
            } else {
                $.ajax({
                    url,
                    method,
                    data,
                    type: 'json',
                    success: (response, status, request) => {
                        if (response.code === 400) {
                            error(response[projectConfig.msg]);
                        } else {
                            const disp = request.getResponseHeader('Content-Disposition');
                            if (disp && disp.search('attachment') !== -1) {
                                const formStr = searchFormArr.join('&');
                                const form = $(`<form method="POST" action="${url}?${formStr}">`);
                                form.append($('<input type="hidden" name="filename">'));
                                $('body').append(form);
                                form.submit();
                            }
                        }
                    }
                });
            }
        }
    }

    deleteHandler = (params, config) => {
        const mine = this;
        const name = params[config.submit.logKey || config.logKey || 'name'] || '未指定提醒';
        const content = <div>
            <span>确认{config.logaction} <span style={{ color: 'orange' }}>{ name }</span> 吗?</span>
        </div>;
        const method = config.submit.method || 'get';
        const result = config.result || {};
        let searchParams = mine.searchParams || {};
        if (config.submit.isNeedLocationSearch && isArray(config.submit.isNeedLocationSearch)) {
            searchParams = {};
            for (let i = 0; i < config.submit.isNeedLocationSearch.length; i+=1) {
                const key = config.submit.isNeedLocationSearch[i];
                searchParams[key] = mine.searchParams[key];
            }
        }
        const configForms = {};
        for (let i = 0; config.forms && i < (config.forms.length); i+=1) {
            const formItem = config.forms[i];
            configForms[formItem.key] = params[formItem.key] || '';
        }
        const { data, url } = parseData2Url({
                ...parseFixedParameter(mine.config.fixedParameter),
                ...parseFixedParameter(config.submit.fixedParameter),
                ...searchParams,
                ...configForms
            }, config.submit[`${this.env}url`] || '');
        if (url) {
            confirm.open({
                title: false,
                hideBackdrop: false,
                content,
                onSure: () => {
                    xhr({
                        url,
                        method,
                        data,
                        type: 'json',
			            contentType: config.submit.contentType,
                        notSwitchArrToStr: config.submit.notSwitchArrToStr
                    }).then((rs) => {
                        if (rs[projectConfig.codeKey] === projectConfig.code) {
                            this.fetchDataHandler(mine.state.pageInfo.pageNo, mine.state.pageInfo.pageSize);
                            success(`${config.logaction}成功!`);
                            if (result.type === 'link') {
                                let gotoUrl = result.address;
                                for (let j = 0; j < (result.gotoValue || []).length; j += 1) {
                                    const gotoItem = result.gotoValue[j];
                                    gotoUrl = gotoUrl.replace('#{key}', params[gotoItem]);
                                }
                                window.open(gotoUrl);
                            }
                        } else {
                            error(rs[projectConfig.msg]);
                        }
                    });
                }
            });
        }
    }

    handlePageChange = pageNo => {
        const mine = this;
        const { pageInfo } = this.state;
        pageInfo.pageNo = pageNo;
        this.setState({
            loading: true,
            pageInfo
        }, ()=>{
            this.fetchDataHandler(pageNo, mine.state.pageInfo.pageSize);
        });
    };

    onChangePageSize = pageSize => {
        const mine = this;
        const { pageInfo } = this.state;
        pageInfo.pageNo = 1;
        pageInfo.pageSize = pageSize;
        this.setState({
            loading: true,
            pageInfo
        }, ()=>{
            this.fetchDataHandler(mine.state.pageInfo.pageNo, pageSize);
        });
    };

    checkUrl = (val) => {
        const strRegex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\\/])+$/;
        const re = new RegExp(strRegex);
        return re.test(val);
    }

    createDataHandler = (type, dataParam) => {
        const mine = this;
        const data = {...dataParam || {}};
        const modalContainer = document.createElement('div');
        const rules = {};
        const newForms = [...(mine.config.forms || []), ...(mine.config[type || 'add'].forms || [])];
        for (let i = 0; i < newForms.length; i+=1) {
            const item = newForms[i];
            const defaultLen = 200000;
            const len = (item.rule && item.rule.len) || defaultLen;
            rules[item.key] = {
                validator(val) {
                    if (item.inputType === 'number') {
                        if (isArray(item.rule.between) && item.rule.between.length === 2) {
                            return val >= item.rule.between[0] && val <= item.rule.between[1];
                        }
                    }
                    const valTmp = `${val || ''}`.trim();
                    const valTmpLen = item.rule.type === 'cn' ? getBLen(valTmp) : valTmp.length;
                    const urlCheck = item.rule.type === 'url' ? mine.checkUrl(val) : true;
                    if (item.rule.isMust) return valTmp && valTmpLen <= len && urlCheck;
                    return valTmpLen <= len;
                },
                message: () => {
                    if (item.inputType === 'number') {
                        if (isArray(item.rule.between) && item.rule.between.length === 2) {
                            return item.rule.log || `${item.label}是介于${item.rule.between[0]}和${item.rule.between[1]}之间的数字！`;
                        }
                        return '配置项错误，查看文档';
                    }
                    if (item.rule.isMust) return item.rule.log || `${item.label}不能为空且长度不超过${len}个字符！`;
                    return item.rule.log || `${item.label}长度不超过${len}个字符！`;
                }
            }
        }
        const { aliasArrMap } = mine.props;
        ReactDom.render(
            <FormModal
                history={mine.props.history}
                schema={rules || {}}
                uuid={mine.uuid || ''}
                config={mine.config || {}}
                mode={type || 'add'}
                formData={data || {}}
                aliasArrMap={aliasArrMap}
                refreshTable={mine.fetchDataHandler} />,
            modalContainer
        );
    };

    onShowAction = (modeParam, data, config) => {
        const mode = modeParam || 'add';
        let search = `?uuid=${this.uuid}&fastmode=${mode}`;
        const values = config.showinfo ? config.showinfo.gotoValue : (config.gotoValue || []);
        for (let i = 0; i < values.length; i+=1) {
            const key = values[i];
            if (data[key] || this.searchParams[key]) {
                search += `&${key}=`;
                search += (data[key] || this.searchParams[key]);
            }
        }
        const gotoType = config.gotoType || "route";
        let router = config.showinfo ? config.showinfo.goto : (config.goto || '/404');
        if (gotoType === "route") {
            this.props.history.push(router + search);
        } else {
            router = router.replace('#{search}', window.location.search);
            window.open(router + search);
        }
    }

    renderCheckboxGroup = (defaultCol) => {
        const mine = this;
        return <CheckboxGroup
            style={{
                display: 'grid',
                backgroundColor: '#EEEEEE',
                padding: '10px',
                maxHeight: '300px',
                overflow: 'auto'
            }}
            onChange={ mine.updateColumns } defaultValue={defaultCol || []}>
            {
                mine.columns.map(item => <Checkbox disabled={item.rule && item.rule.isMust} label={item.title} value={item.key} key={item.key} />)
            }
        </CheckboxGroup>
    }

    actionBatchHandler = (type, config) => {
        const mine = this;
        if (mine.selectedCol.length === 0) {
            error('未选中数据!');
            return false;
        }
        const content = <div>
            <span>确认{config.logaction}吗?</span>
        </div>;
        const method = config.submit.method || 'get';
        let searchParams = mine.searchParams || {};
        if (config.submit.isNeedLocationSearch && isArray(config.submit.isNeedLocationSearch)) {
            searchParams = {};
            for (let i = 0; i < config.submit.isNeedLocationSearch.length; i+=1) {
                const key = config.submit.isNeedLocationSearch[i];
                searchParams[key] = mine.searchParams[key];
            }
        }
        const configForms = {};
        configForms[config.submit.ajaxKey || 'ids'] = [];
        for (let s = 0; mine.selectedCol && s < (mine.selectedCol.length); s += 1) {
            for (let i = 0; config.forms && i < (config.forms.length) && config.forms.length === 1; i += 1) {
                const formItem = config.forms[i];
                configForms[config.submit.ajaxKey || 'ids'].push(mine.selectedCol[s][formItem.key]);
            }
        }
        const { data, url } = parseData2Url({
                ...parseFixedParameter(mine.config.fixedParameter),
                ...parseFixedParameter(config.submit.fixedParameter),
                ...searchParams,
                ...configForms
            }, config.submit[`${this.env}url`] || '');
        if (url) {
            confirm.open({
                title: false,
                hideBackdrop: false,
                content,
                onSure: () => {
                    xhr({
                        url,
                        method,
                        data,
                        type: 'json',
			            contentType: config.submit.contentType,
			            notSwitchArrToStr: config.submit.notSwitchArrToStr
                    }).then((rs) => {
                        if (rs[projectConfig.codeKey] === projectConfig.code) {
                            mine.fetchDataHandler(mine.state.pageInfo.pageNo, mine.state.pageInfo.pageSize);
                            mine.selectedCol = [];
                            mine.setState({ selectedRowKeys: [] });
                            success(`${config.logaction}成功!`);
                        } else {
                            error(rs[projectConfig.msg]);
                        }
                    });
                }
            });
        }
    }

    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, pageInfo, tableLoading, selectedRowKeys } = this.state;
        const { aliasArrMap } = this.props;
        const  userAuth = this.props.userAuth || [];
        const defaultTrue = true;
        const TEN = 10;
        const TWENTY = 20;
        const THIRTY = 30;
        const pageSizeOptions = [TEN, TWENTY, THIRTY];
        const { rowSelection, option, noShow, pagination } = this.config.basic
        
        const normalTableData = Object.assign(
            {
                columns: this.state.columns,
                dataSource: dataSource.map(item => {
                    const reItem = item;
                    reItem.key = rowSelection ? item[rowSelection.key || 'id'] : Math.random();
                    return reItem;
                }),
                bordered: true,
                loading: tableLoading,
                pagination: false,
                locale: {
                    emptyText: '暂无数据'
                },
                onChange: (p, filters, sorter) => {
                    const { field } = sorter;
                    let { order } = sorter;
                    if (order === 'descend') order = 'desc';
                    else if (order === 'ascend') order = 'asc';
                    this.setState(order ? { sortFiled: field, order } : {sortFiled: '', order},
                        () => {
                            this.fetchDataHandler();
                    });
                }
            },
            (option || {}), 
        );
        
        if (rowSelection) normalTableData.rowSelection = {
            type: rowSelection.type || 'checkbox',
            selectedRowKeys,
            onChange: (selectedKeys, selectedRows) => {
                this.setState({ selectedRowKeys: selectedKeys });
                this.selectedCol = selectedRows;
            }
        };
        const actionBtns = [];
        const mine = this;
        (this.config.actionBtn || []).forEach(item => {
            if (this.config[item.key] && (projectConfig.noAuth || userAuth.indexOf(this.config[item.key].auth) > -1 || this.env === 'local.')) {
                if (item.type === 'create' && ((this.config.forms && this.config.forms.length > 0) || (this.config[item.key].forms && this.config[item.key].forms.length > 0) || this.config[item.key].mode === 'link')) actionBtns.push(<Button
                    variant="contained" color={this.config[item.key].primary || 'primary'}
                    onClick={this.config[item.key].mode === 'link' ? () => {this.onShowAction(item.key, {}, this.config[item.key])} : () => {this.createDataHandler(item.key, this.config[item.key].setsearch ? { ...mine.props.searchForm, ...mine.state.searchForm } : '')}}
                    style={Object.assign({ float: 'right', marginLeft: '10px', marginRight: '10px' }, item.style, this.config[item.key].style)}
                >{this.config[item.key].label || item.label}</Button>);
                if (item.type === 'check') actionBtns.push(<Button
                    variant="contained" color={this.config[item.key].primary || 'primary'}
                    onClick={() => {this.actionBatchHandler(item.key, this.config[item.key])}}
                    style={Object.assign({ float: 'right', marginLeft: '10px', marginRight: '10px' }, item.style, this.config[item.key].style)}
                >{this.config[item.key].label || item.label}</Button>);
            }
        });
        const { pathname, search } = this.props.location;
        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", "marginLeft": 5}}
                                onClick={() => {
                                    this.switchJsOrJson({
                                        path: this.props.path,
                                        uuid: this.config.uuid
                                    })
                                }}>toJS</Button> : ''
                        }
                        {
                            !this.props.notModify && this.env === 'local.' ? <Button
                                    variant="contained" color="success"
                                    size="small"
                                    style={{"height": "auto", "float": "right"}}
                                    onClick={() => {
                                        this.props.history.push(`/module?url=${encode.encode(pathname + search, 'base64')}&fastmode=modify&path=${this.path}&uuid=${this.uuid}&tableId=${this.config.tableId}`);
                                    }}>编辑</Button> : ''
                        }
                        <div className="tool-bar">
                            {
                                this.config.filter && this.config.filter.length > 0 ? <SearchBar
                                    filter={this.config.filter || []}
                                    search={() => { this.fetchDataHandler(1) }}
                                    searchFormData={this.state.searchForm}
                                    nbg={this.config.nbg || true}
                                    filterLabel={this.config.filterLabel || '搜索'}
                                    aliasArrMap={aliasArrMap}
                                ></SearchBar> : ''
                            }
                        </div>
                        {
                            (this.config.name || this.config.export || this.config.upload || this.config.control || actionBtns.length > 0) ? <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 && (projectConfig.noAuth || userAuth.indexOf(this.config.export.auth) > -1 || this.env === 'local.') && dataSource.length > 0 ? <Button
                                        variant="contained" color={this.config.export.primary || 'primary'}
                                        onClick={this.exportDataHandler}
                                        style={{ float: 'right', marginLeft: '10px', marginRight: '10px' }}
                                    >{this.config.export.label || '导出数据'}</Button> : ''
                                }
                                {
                                    this.config.control ? <DropdownMenu
                                        onSelect={(e, value) => console.log(value)}
                                        anchorEl={<Button type="primary"
                                            style={{ float: 'right', marginLeft: '10px', marginRight: '10px' }}
                                            >显示设置</Button>
                                        }>
                                        { this.renderCheckboxGroup(this.state.defaultCol) }
                                    </DropdownMenu> : ''
                                }
                                {
                                    actionBtns
                                }
                                {
                                    this.config.upload && (projectConfig.noAuth || userAuth.indexOf(this.config.upload.auth) > -1 || this.env === 'local.') ?
                                        <div style={{ float: 'right', marginLeft: '10px', marginRight: '10px', minWidth: 60, position: 'relative' }}>
                                            <div style={Object.assign({ position: 'absolute', right: 0 }, this.config.upload.style || {})}>
                                                <Upload
                                                    multiple
                                                    beforeUpload={this.beforeUpload}>
                                                    <Button
                                                        variant="contained" color={this.config.upload.primary || 'primary'}
                                                    >{this.config.upload.label || '上传'}</Button>
                                                </Upload>
                                            </div>
                                            {
                                                this.config.upload.helperMust || this.config.upload.helperText ? <div style={this.config.upload.helperStyle || {}}>
                                                    {this.config.upload.helperMust ? <span style={{ color: 'red' }}>*</span> : ''}
                                                    {this.config.upload.helperText ? <span style={this.config.upload.helperTextStyle || {}}>{this.config.upload.helperText}</span> : ''}
                                                </div> : ''
                                            }
                                        </div> : ''
                                }
                            </div> : ''
                        }
                        {
                            !noShow ? <Table {...normalTableData} /> : ''
                        }
                        {
                            pagination !== false ? 
                                <Row justify="right">
                                    <Col align="stretch">
                                        <Pagination
                                            showTotal
                                            showSelectPageSize
                                            showWhenOnlyOne
                                            scrollToTop={defaultTrue}
                                            className="page"
                                            total={pageInfo.totalSize}
                                            pageSize={pageInfo.pageSize}
                                            current={pageInfo.pageNo}
                                            showQuickJump={defaultTrue}
                                            onChange={this.handlePageChange}
                                            onChangePageSize={this.onChangePageSize}
                                            pageSizeOptions={pageSizeOptions}
                                            />
                                    </Col>
                                </Row> : ''
                        }
                    </div>
                </Col>
            </Row>
        );
    }
}

export default withRouter(Searchtable);
