import React from 'react';
import { Row, Col, Button, Select, Input, Field, createEasyForm, TagSelect, RadioGroup, Radio } from 'neatui';
import { withRouter } from 'react-router-dom';
import xhr from 'SERVICE/xhr';
import BaseComponent from 'COMPONENT/common/BaseComponent';
import { error, success } from 'UTIL/notification';
import Loading from 'COMPONENT/container/Loading/Loading';
import { getSearchParams } from 'UTIL/util';
import './index.scss';

const { modulePath, uuid, fastmode } = getSearchParams() || {};
console.log(modulePath);
let config = {};
if (modulePath) {
    try {
        config = require(`CONFIG/${modulePath}/${uuid}config.json`);
    } catch (err) {
        error('CONFIG配置路径错误');
        throw new Error('error');
    }
} else {
    error('CONFIG配置路径错误');
}
if (!fastmode) {
    error('缺少xhr配置');
}

const formList = [ ...(fastmode ? (config[fastmode].forms || {}) : {}), ...(config.forms || {})];
const rules = {};
const defaultVals = {};
for (let i = 0; i < formList.length; i+=1) {
    const item = formList[i];
    if (item.isMust) {
        const defaultLen = 20;
        const len = item.rule.len || defaultLen;
        rules[item.key] = {
            validator(val) {
                const valTmp = `${val || ''}`;
                return valTmp && valTmp.length < len;
            },
            message: () => item.rule.log || `${item.key}不能为空且长度不超过${len}个字符！`
        }
    }
    defaultVals[item.key] = item.defaultValue || '';
}
class Fastform extends BaseComponent {
    constructor(props) {
        super(props);
        /*
            config, key, submit, goback
        */
        const submitForm = {};
        const submitFormData = {};
        for ( let i = 0; i < formList.length; i+=1 ) {
            submitForm[formList[i].key] = formList[i].defaultValue || '';
            submitFormData[formList[i].key] = [];
        }
        this.state = {
            loading: false,
            submitForm: {
                ...submitForm
            },
            submitFormData: {
                ...submitFormData
            }
        };
    }

    componentDidMount() {
        if (fastmode !== 'create') {
            this.setState({
                loading: true
            });
            this.fetchDataHandler(this.state.modifyID);
        }
    }

    fetchDataHandler = (id) => {
        const mine = this;
        const url = config[fastmode].data.url || '';
        const method = config[fastmode].data.type || 'get';
        xhr({
            url,
            method,
            type: 'json',
            data: {
                id
            },
            complete: () => {

            }
        }).then((rs) => {
            if (rs.status === '200') {
                const submitForm = {
                    ...mine.state.submitForm
                };
                for (let i = 0; i < formList.length; i+=1) {
                    const key = formList[i].key || '';
                    if (key) {
                        this.props.updateFieldValue(key, rs.data[key] || '');
                        submitForm[key] = rs.data[key] || '';
                    }
                }
                mine.setState({
                    loading: false,
                    submitForm
                });
            } else {
                error(rs.message);
            }
        });
    };

    submitHandler = (data) => {
        const url = config[fastmode].submit.url || '';
        const method = config[fastmode].submit.type || 'post';
        const msg = config[fastmode].submit.msg || '操作成功';
        xhr({
            url,
            method,
            data: {
                ...this.state.submitForm,
                ...data
            },
            type: 'json',
            complete: () => {

            }
        }).then((rs) => {
            if (rs.status === '200') {
                success(msg);
                this.props.history.push('/62fs6ivwv7ljs6hf');
            } else {
                error(rs.message);
            }
        });
    };

    cancelHandler = () => {
        this.props.history.push('/62fs6ivwv7ljs6hf');
    };

    createField = () => {
        const result = [];
        for (let i = 0; i < formList.length; i+=1) {
            const item = formList[i];
            if (item.type === 'input') {
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onBlur'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                    <Input disabled={item.notModify} autoComplete="off" placeholder={`请输入${item.label}`}/>
                </Field>);
            } else if (item.type === 'multinput') {
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onBlur'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                    <Input disabled={item.notModify} autoComplete="off" multiline rows={5} placeholder={`请输入${item.label}`}/>
                </Field>);
            } else if (item.type === 'select') {
                const data = [].concat(item.data || []).concat(defaultVals[item.key] || []);
                const selectItems = data.map(selectItem => {return { 'label': selectItem[item.dataLabel || 'name'], 'value': selectItem[item.dataKey || 'id'] }});
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onChange'
                    valuePropName='defaultValue'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                    <Select
                        placeholder=""
                        options={item.notAll ? [...selectItems] : [{ label: '全部', value: '' }, ...selectItems]}
                    >
                    </Select>
                </Field>);
            } else if (item.type === 'multselect') {
                const data = [].concat(item.data || []).concat(defaultVals[item.key] || []);
                const selectItems = data.map(selectItem => {return { 'label': selectItem[item.dataLabel || 'name'], 'value': selectItem[item.dataKey || 'id'] }});
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onChange'
                    valuePropName='defaultValue'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                    <Select
                        searchable
                        multiple
                        placeholder={`请选择${item.label}`}
                        options={item.notAll ? [...selectItems] : [{ label: '全部', value: '' }, ...selectItems]}
                    >
                    </Select>
                </Field>);
            } else if (item.type === 'tags') {
                const data = [].concat(item.data || []).concat(defaultVals[item.key] || []);
                const selectItems = data.map(selectItem => {return { 'label': selectItem[item.dataLabel || 'name'], 'value': selectItem[item.dataKey || 'id'] }});
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onChange'
                    valuePropName='defaultValue'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                        <TagSelect
                            placeholder={`请选择/输入${item.label}`}
                            options={item.notAll ? [...selectItems] : [{ label: '全部', value: '' }, ...selectItems]}
                        >
                        </TagSelect>
                </Field>);
            } else if (item.type === 'radio') {
                const data = [].concat(item.data || []).concat(defaultVals[item.key] || []);
                const selectItems = data.map(selectItem => {return { 'label': selectItem[item.dataLabel || 'name'], 'value': selectItem[item.dataKey || 'id'] }});
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='ignore'
                    valuePropName='value'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                    <RadioGroup>
                        {
                            selectItems.map((radioItem) => <Radio label={radioItem.label} value={radioItem.value} key={radioItem.value} /> )
                        }
                    </RadioGroup>
                </Field>);
            } else if (item.type === 'todo') {
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    label={<span>{item.rule && item.rule.isMust ? <span className="required">*</span> : ''}{item.label}</span>}
                    name={item.key}
                    helperText={item.helperText || ''}
                    validateTrigger='onChange'
                    valuePropName='defaultValue'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                        <div>TODO这里还没有配置</div>
                </Field>);
            } else {
                result.push(<Field
                    className="fastform-field"
                    style={item.style || {}}
                    validateTrigger='onChange'
                    valuePropName='defaultValue'
                    nativeStatusIcon
                    labelLayout={{ size: 5 }}
                    contentLayout={{ size: 15 }}>
                        <div>这里是错误类型</div>
                </Field>);
            }
        }
        return result;
    };

    render() {
        const { submit } = this.props;
        return (<div>
                <Row className="mb-10">
                <Col>
                    <div className="section">
                        <Row justify="center">
                            <Col align="stretch">
                                <h3 style={{ float: 'left', position: 'relative' }}>基础信息</h3>
                            </Col>
                        </Row>
                        <Row justify="center">
                            <Col align="stretch">
                                {this.state.loading ? <Loading /> : ''}
                                {this.createField()}
                            </Col>
                        </Row>
                        <Row justify="center">
                            <Col align="stretch" style={{ textAlign: 'center', marginTop: 15 }}>
                                <Button
                                    onClick={submit(data => this.submitHandler(data), err => console.log(err))}
                                    type="primary">确定</Button>
                                <Button style={{ marginLeft: 10 }} onClick={this.cancelHandler} type="hollow">取消</Button>
                            </Col>
                        </Row>
                    </div>
                </Col>
                </Row>
                </div>
        );
    }
}

export default withRouter(createEasyForm(defaultVals, rules)(Fastform));
