/**
 * 表单提交：handleSubmit: Function,
 *
 * 表单取消：handleCancel:Function
 *
 * 数据回显：mapPropsToFields:Function
 *
 * 监听表单值发生变化是的回掉：onValuesChange:Function
 *
 * 样式：propClass：object
 *  */
import React, { Component } from 'react';
import { Form, Button } from 'antd';
import styles from './index.less';
import { config } from '../component/base/config';
import { transferAttr } from '../component/base/_utils/transferAttr';
import { getFormat, setFormat } from '../component/base';
import { Provider } from '../component/context';
import { defaultLocale } from '@/submodule/components/apolloTable/locale';
import _ from 'lodash';

const FormItem = Form.Item;

class FormWrap extends Component {
    handleSubmit = (e) => {
        e.preventDefault();
        e.stopPropagation();
        const { rowId, form, handleSubmit, data, rowData } = this.props;
        form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const newValues: any[] = [];
                _.keys(values).map((key) => {
                    const item = data.find((temp: any) => {
                        return temp.columnName === key;
                    });
                    const { columnType, renderEditForm, readOnlyFlag, dynamicCellConfigDTO } = item;
                    if (readOnlyFlag || (dynamicCellConfigDTO && dynamicCellConfigDTO.readonlyFlag)) {
                        return;
                    }
                    let detailConfig: any;
                    if (typeof renderEditForm === 'function') {
                        detailConfig = renderEditForm({ cellData: values[key], rowData, columnConfig: item });
                    } else {
                        detailConfig = config[String(columnType)] || config['1'];
                    }
                    const cellValueList = setFormat(detailConfig, item, values[key]);
                    newValues.push({
                        columnCode: key,
                        cellValueList,
                    });
                });
                if (typeof handleSubmit === 'function') {
                    handleSubmit({ data: { value: newValues } });
                }
            }
        });
    };

    handleCancel = () => {
        const { handleCancel } = this.props;
        if (typeof handleCancel === 'function') {
            handleCancel();
        }
    };

    handleDelete = () => {
        const { rowId, handleDelete } = this.props;
        if (typeof handleDelete === 'function') {
            handleDelete({ data: { id: rowId } });
        }
    };

    renderLabel = (item) => {
        // const { icon } = config[item.columnType];
        return (
            <span className={styles.titleContainer}>
                {/* icon && <div className={styles.colIcon}>{icon}</div> */}
                <span className={styles.itemTitle}>{item.columnChsName}</span>
            </span>
        );
    };

    validateRequired = (item, rule, value, callback) => {
        const { columnAttrObj = {} } = item;
        const { validator } = columnAttrObj;
        if (!item.requiredFlag) {
            callback();
            return;
        }
        if (!value || value.length === 0) {
            callback('必填项不能为空');
            return;
        }
        const [first] = value;
        if (!first.text && first.text !== 0 && !first.value && first.value !== 0) {
            callback('必填项不能为空');
            return;
        }
        if (validator && typeof validator === 'function') {
            const values = this.props.form.getFieldsValue();
            callback(validator({ value, values, item }));
        }
        callback();
    };

    renderEditForm = (item) => {
        const { getFieldDecorator } = this.props.form;
        const { rowData } = this.props;
        const {
            columnType,
            columnName,
            columnAttrObj,
            value,
            renderEditForm,
            readOnlyFlag,
            rules = [],
            validateFirst = true,
            validateTrigger = 'onChange',
            dynamicCellConfigDTO,
        } = item;
        let detailConfig: any;
        if (typeof renderEditForm === 'function') {
            detailConfig = renderEditForm({ cellData: value, rowData, columnConfig: item });
        } else {
            detailConfig = config[String(columnType)] || config['1'];
        }
        const EditComp: any = detailConfig.editComp;
        const newProps = {
            ...(detailConfig.componentAttr || {}),
            ...(columnAttrObj || {}),
        };
        const transferColumn = transferAttr(columnType, newProps);
        const disabled = readOnlyFlag || (dynamicCellConfigDTO && dynamicCellConfigDTO.readonlyFlag);
        return (
            <FormItem key={columnName} label={this.renderLabel(item)}>
                {getFieldDecorator(columnName, {
                    validateFirst,
                    validateTrigger,
                    rules: [{ required: !!item.requiredFlag, message: '必填项不能为空' }, ...rules],
                    initialValue: getFormat(detailConfig, item, value),
                })(<EditComp {...transferColumn} columnConfig={item} disabled={disabled} />)}
            </FormItem>
        );
    };

    getContext = () => {
        const { locale } = this.props;
        if (locale) {
            if (locale.context) {
                if (locale.lang && defaultLocale[locale.lang]) {
                    return { ...defaultLocale[locale.lang], ...locale.context };
                }
                return locale.context;
            }
        }
        return defaultLocale.cn;
    };

    render() {
        const { loading, isShowDelBtn, data, btnWrapStyle, name, colsNum } = this.props;

        return (
            <Provider value={{ locale: this.getContext() }}>
                <div className={styles.wrap}>
                    <p className={styles.titleCls}>{name || '客户跟进'}</p>
                    <div
                        id="gotop"
                        className={styles.formItemCls}
                        ref={(r) => {
                            this.wrapDom = r;
                        }}
                    >
                        <Form onSubmit={this.handleSubmit} layout="vertical">
                            {data.map((item: any, i: number) => {
                                return (
                                    <div
                                        key={i}
                                        className={styles.item}
                                        style={{
                                            width: `${100 / colsNum}%`,
                                            marginLeft: colsNum > 1 && i % colsNum === 0 ? '-50px' : 0,
                                            paddingLeft: colsNum > 1 ? '50px' : 0,
                                        }}
                                    >
                                        {this.renderEditForm(item)}
                                    </div>
                                );
                            })}
                        </Form>
                    </div>
                    <div className={styles.buttonWrap} style={btnWrapStyle}>
                        <div style={{ display: 'flex', justifyContent: 'center' }}>
                            {isShowDelBtn ? (
                                <Button onClick={this.handleDelete} type="link" className={styles.delBtnCls}>
                                    删除
                                </Button>
                            ) : null}
                            <Button onClick={this.handleCancel} className={styles.btnCls}>
                                取消
                            </Button>
                            <Button
                                onClick={this.handleSubmit}
                                type="primary"
                                className={styles.btnCls}
                                loading={loading}
                                id="submitBtn" // 用于业务监听此dom节点
                            >
                                确定
                            </Button>
                        </div>
                    </div>
                </div>
            </Provider>
        );
    }
}

function mapPropsToFields(props) {
    const returnObj = {};
    const { data, renderEditForm, rowData } = props;
    data.forEach((el) => {
        // let detailConfig: any;
        // if (typeof renderEditForm === 'function') {
        //     detailConfig = renderEditForm({ cellData: el.value, rowData, columnConfig: el });
        // } else {
        //     detailConfig = config[String(el.columnType)] || config['1'];
        // }
        // const formatValue = getFormat(detailConfig, el, el.value);
        // console.log('formatValue',formatValue)
        returnObj[el.columnType] = Form.createFormField({
            value: el.value,
        });
    });
    return returnObj;
}

function onValuesChange(props, changedValues, allValues) {
    if (props.changeValue) {
        props.changeValue(changedValues, allValues);
    }
}

export default Form.create({ name: 'form_view' })(FormWrap);
