import React from 'react';
import { Input, message, AutoComplete } from 'kts-xui';
import { Form, Row, Col } from 'kts-components-antd-x4';
import { PlusOutlined } from '@ant-design/icons';
import agent from '../../../Server';
import { alxd } from './VerifyInvoice';
import { FormInstance } from 'kts-components-antd-x4/lib/form';
const FormItem = Form.Item;
const Option = AutoComplete.Option;

interface IProps {
    url: any;
    fnForceUpdate: () => void;
}

class Component extends React.Component<IProps, any> {
    formRef = React.createRef<FormInstance>();
    public queryTimeout: any;
    public textInput; any;
    constructor(props: IProps) {
        super(props);
        this.state = {
            value: '',
            loading: false,
            showCheck: false,
            tip: '开具金额(不含税)',
            url: this.props.url && this.props.url.scankey4,
            type: this.props.url && this.props.url.scankey4type,
            inputType: this.props.url.scaninputType,
        };
        this.focusTextInput = this.focusTextInput.bind(this);
    }
    onFinish = async values => {
        let data = {
            ...values,
        };
        if (typeof this.state.url === 'string') {
            const res: any = await agent.post(this.state.url, data, this);
           
            this.handResponse(res);
        } else {
            this.state.url(values).then(res => {
                this.handResponse(res);
            })
        }
    }
    handResponse = res => {
        this.setState({
            value: null
        });
        if (!res.err) {
            this.success();
        } else {
            const err2 = res.err;
            message.error(err2.status.description);
            return null;
        }
    }
    resetForm = () => {

    }
    success = () => {
        message.success('上传成功');
        this.props.fnForceUpdate();
    }
    error = () => {
        message.error('上传失败，请稍后重新上传');
    }
    componentDidMount() {
        this.focusTextInput();
    }
    onScannerChange = (e) => {
        clearTimeout(this.queryTimeout);
        this.setState({
            value: e.target.value
        }, () => { this.queryTimeout = setTimeout(this.onGetqrcode, 200); });
    }
    onGetqrcode = () => {
        let code = this.state.value;
        let array = code.replace(/，/g, ',').split(',');
        if (array.length < 7) {
            message.error('数据未识别');
            this.setState({
                value: null
            });
        } else {
            if (array[2].length < 10) {
                return null;
            }
            if (array[3].length < 8) {
                return null;
            }
            let fplx = alxd(array[2]);//fplx 发票类型 

            if ((fplx === '01' || fplx === '02' || fplx === '03' || fplx === '15')) {
                let tip = '';
                if (fplx === '02') {
                    tip = '合计金额';
                } else if (fplx === '03') {
                    tip = '不含税价';
                } else if (fplx === '15') {
                    tip = '车价合计';
                } else {
                    tip = '开具金额(不含税)';
                }
                this.setState({
                    showCheck: false,
                    tip: tip
                });
            } else if (fplx === '04' || fplx === '10' || fplx === '11' || fplx === '14') {
                this.setState({
                    showCheck: true
                });
            }

            let r = new RegExp(/^[0-9]*$/);
            if (r.test(array[2]) && r.test(array[3]) && r.test(array[5]) && new RegExp(/^[0-9].*$/).test(array[4])) {
                this.formRef.current!.setFieldsValue({
                    invoiceCode: array[2],
                    invoiceNo: array[3],
                    invoiceDate: array[5].substring(0, 4) + '-' + array[5].substring(4, 6) + '-' + array[5].substring(6, 8),
                    invoiceAmount: array[4],
                    checkCode: array[6].substr(-6, 6)
                });
                this.formRef.current!.submit();
            } else {
                message.error('数据未识别');
                this.setState({
                    value: null
                });
            }

        }
    }

    onScannerBlur = () => {
        this.textInput.focus();
    }
    focusTextInput() {
        window.setTimeout(() => {
            this.textInput.focus();
        }, 500)
    }
    onChange = (e) => {
        if (e.target.checked) {
            this.setState({
                draftFlag: 1
            });
        } else {
            this.setState({
                draftFlag: 0
            });
        }
    }
    render() {
        let formItemLayout = {
            labelCol: { span: 24 },
            wrapperCol: { span: 24 },
        };
        return (
            <div>
                <Form ref={this.formRef} onFinish={this.onFinish}>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="扫码输入" style={{ height: 0, opacity: 0 }}>
                                <Input ref={(input) => { this.textInput = input; }} onChange={this.onScannerChange} value={this.state.value} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row justify="space-between">
                        <Col span={11}>
                            <FormItem required={true} {...formItemLayout} label="发票代码" name="invoiceCode">
                                <Input readOnly={true} onClick={this.onScannerBlur} />
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem required={true} {...formItemLayout} label="发票号码" name="invoiceNo">
                                <Input readOnly={true} onClick={this.onScannerBlur} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem
                                {...formItemLayout}
                                label="开票日期"
                                name="invoiceDate"
                                required={true}
                            >
                                <Input readOnly={true} onClick={this.onScannerBlur} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem required={true} {...formItemLayout} name="invoiceAmount" label={this.state.tip} className={this.state.showCheck ? 'hide' : ''}>
                                <Input readOnly={true} onClick={this.onScannerBlur} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem {...formItemLayout} name="checkCode" label="校验码" className={this.state.showCheck ? '' : 'hide'}>
                                <Input readOnly={true} />
                            </FormItem>
                        </Col>
                    </Row>

                </Form>
                <div style={{ padding: '10px 0px 0', color: '#4D4D4D', fontSize: '12px', fontWeight: '500' }}>请将扫码枪靠近发票二维码，并保证二维码清晰，系统会自动进行发票录入。(扫码多次失败可以尝试把输入法设置成小写)</div>
            </div>
        );
    }

}
export default Component;
