
import React from 'react';
import Icon from '@ant-design/icons';
import { decorator } from "grey-react-box";
import { Form } from "kts-components-antd-x3";
import { AutoComplete, Button, Checkbox, Col, Input, InputProps, Row, Tooltip } from 'kts-xui'
import { CheckboxChangeEvent } from 'kts-components-antd-x4/lib/checkbox';
import { FormComponentProps } from "kts-components-antd-x3/lib/form";
import { WrappedFormUtils } from 'kts-components-antd-x3/lib/form/Form';
import { ReactComponent as ArrowUpSvg } from './svg/arrowUp.svg';
import { ReactComponent as ArrowDownSvg } from './svg/arrowDown.svg';
import { ReactComponent as PlusSvg } from './svg/plus.svg'
import InvoiceController from "../../../InvoiceController";
import Invoice from "../../../../Invoice";
import './index.less';
import classNames from 'classnames';

const RULES = {
    companyName: (label: string) => [
        { required: true, message: `${label}必填` },
        { max: 100, message: `${label}内容超长` }
    ],
    taxId: (label: string) => [
        { max: 20, message: `${label}内容超长` },
        { pattern: /^([a-zA-Z0-9])*$/g, message: `${label}仅能数字、英文` }
    ],
    buyerTelPhone: (label: string) => [
        { max: 100, message: `${label}内容超长` },
        { pattern: /^[0-9\s\-\+]+$/g, message: `${label}仅能数字、空格、-、+` }
    ],
    sellerTelPhone: (label: string) => [
        // { required: true, message: `${label}必填` },
        { max: 100, message: `${label}内容超长` },
        { pattern: /^[0-9\s\-\+]+$/g, message: `${label}仅能数字、空格、-、+` }
    ],
    bankName: (label: string) => [
        { max: 100, message: `${label}内容超长` }
    ],
    bankAccount: (label: string) => [
        { max: 100, message: `${label}内容超长` },
        { pattern: /^([0-9a-zA-Z-\s])*$/g, message: `${label}仅能数字、字母、-、空格` }
    ]
}

const formatCompanyName = (e: any) => {
    const value = e?.target?.value;
    if (value) {
        return value.replace('(', '（').replace(')', '）').replace(' ', '');
    }
}

export interface IStakeholder {

    /** 是否显示导入按钮 */
    isShowImportButton?: boolean;

    /** 点击了 */
    onClickImportButton?: (e: InvoiceController) => void

    /** 查看当前可用授信额度 */
    lineCredit?: React.ReactNode;

    /** 票种类型 */
    isVatNormal?: boolean;

    /** 是否可以选择自然人 */
    isNaturalPerson?: boolean;

    /** 是否展开 */
    isExpand?: boolean;
}

/** 干系人 */
export default decorator<IStakeholder, IStakeholder & FormComponentProps>(Form.create())(props => {

    const { form, isShowImportButton, onClickImportButton, isVatNormal = false } = props;

    const [isExpand, setExpand] = React.useState(typeof props.isExpand === 'boolean' ? props.isExpand : true);

    const { getFieldDecorator } = form;

    const controller = Invoice.useInvoiceController();

    const model = controller.useMemo(s => s.model, []);

    const disableds = controller.useMemo(s => s.stakeholder.disableds || [], []);

    const rulesMap = controller.useMemo(s => s.stakeholder.rulesMap || {}, []);

    const readOnly = React.useMemo(() => {
        if (model === 'readOnly') return true;
        if (model === 'prefab') return true;
        return false;
    }, [model]);

    const onExpand = React.useCallback(() => { setExpand(e => !e) }, []);

    const isReadOnly = React.useCallback(field => readOnly || disableds.indexOf(field) >= 0, [disableds, readOnly]);

    const getRules = React.useCallback((field, defaultRules) => {
        if (isReadOnly(field)) return [];
        return rulesMap[field] || defaultRules;
    }, [rulesMap, isReadOnly, isReadOnly]);

    controller.useForm('stakeholder', form);

    // props.isExpand 变化的时候更新
    React.useEffect(() => {
        setExpand(typeof props.isExpand === 'boolean' ? props.isExpand : true);
    }, [props.isExpand])

    return (
        <div className={classNames("kts-invoice-operate-invoice-digtal-stakeholder", { readOnly: readOnly })} >
            <div>
                {'购买方信息'.split('').map(e => <span>{e}</span>)}
                {
                    !readOnly &&
                    <Icon
                        className="digtal-stakeholder-expand-button"
                        component={isExpand ? ArrowUpSvg : ArrowDownSvg}
                        onClick={onExpand}
                    />
                }
            </div>
            <div>
                <div style={{ marginTop: 20 }} className='natural-person-flag' >
                    {
                        props.isNaturalPerson === true &&
                        <Form.Item colon={false}>
                            {getFieldDecorator('naturalPersonFlag', {
                            })(
                                <NaturalPersonFlag readOnly={isReadOnly('naturalPersonFlag')} />
                            )}
                        </Form.Item>
                    }
                </div>
                <Form className="digtal-stakeholder-form" >
                    <Row gutter={[16, 0]}>
                        <Col span={24} >
                            <Form.Item label='名称' colon={false}>
                                {getFieldDecorator('buyerName', {
                                    rules: getRules('buyerName', RULES.companyName('购买方名称')),
                                })(
                                    <BuyerNameInput
                                        myform={form}
                                        fieldName='buyerName'
                                        readOnly={isReadOnly('buyerName')}
                                        placeholder="请输入名称"
                                        autoComplete="off"
                                        suffix={
                                            isShowImportButton === true &&
                                            <Button
                                                type='link'
                                                style={{ padding: 0, width: 20, height: '100%' }}
                                                icon={<Icon component={PlusSvg} />}
                                                onClick={() => { onClickImportButton && onClickImportButton(controller) }}
                                            />
                                        }
                                    />
                                )}
                            </Form.Item>
                        </Col>

                        <Col span={24} >
                            <Form.Item label='统一社会信用代码/纳税人识别号' colon={false}>
                                {getFieldDecorator('buyerTaxId', {
                                    rules: getRules('buyerTaxId', [{ required: !isVatNormal, message: '购买方纳税人识别号必填' }, ...RULES.taxId('购买方纳税人识别号')])
                                })(
                                    <BuyerNameInput
                                        myform={form}
                                        fieldName='buyerTaxId'
                                        readOnly={isReadOnly('buyerTaxId')}
                                        placeholder="请输入统一社会信用代码/纳税人识别号"
                                        autoComplete="off"
                                    />
                                )}
                            </Form.Item>
                        </Col>

                        <Col span={14} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='购买方地址' colon={false}>
                                {getFieldDecorator('buyerAddress', {
                                    rules: getRules('buyerAddress', [{ max: 100, message: '购买方地址内容超长' }])
                                })(<MyInput readOnly={isReadOnly('buyerAddress')} placeholder="请输入购买方地址" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={10} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='电话' colon={false} className='telephone'>
                                {getFieldDecorator('buyerPhone', {
                                    rules: getRules('buyerPhone', RULES.buyerTelPhone('购买方电话'))
                                })(<MyInput readOnly={isReadOnly('buyerPhone')} placeholder="请输入电话" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={14} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='购买方开户银行' colon={false}>
                                {getFieldDecorator('buyerBank', {
                                    rules: getRules('buyerBank', RULES.bankName('购买方开户银行'))
                                })(<MyInput readOnly={isReadOnly('buyerBank')} placeholder="请输入购买方开户银行" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={10} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='银行账号' colon={false}>
                                {getFieldDecorator('buyerAccount', {
                                    rules: getRules('buyerAccount', RULES.bankAccount('购买方银行账号'))
                                })(<MyInput readOnly={isReadOnly('buyerAccount')} placeholder="请输入银行账号" autoComplete="off" />)}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div>
                {'销售方信息'.split('').map(e => <span>{e}</span>)}
                {
                    !readOnly &&
                    <Icon
                        className="digtal-stakeholder-expand-button"
                        component={isExpand ? ArrowUpSvg : ArrowDownSvg}
                        onClick={onExpand}
                    />
                }
            </div>
            <div>
                {
                    !readOnly && props.lineCredit &&
                    <div style={{ marginTop: 20 }} >
                        <Tooltip trigger="click" title={props.lineCredit} >
                            <Button type="link" style={{ padding: `0px 8px` }} >查看当前可用授信额度</Button>
                        </Tooltip>
                    </div>
                }
                <Form className="digtal-stakeholder-form" >
                    <Row gutter={[16, 0]}>
                        <Col span={24} >
                            <Form.Item label='名称' colon={false}>
                                {getFieldDecorator('supplierName', {
                                    rules: getRules('supplierName', RULES.companyName('销售方名称')),
                                    getValueFromEvent: formatCompanyName
                                })(<MyInput readOnly={isReadOnly('supplierName')} placeholder="请输入名称" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={24} >
                            <Form.Item label='统一社会信用代码/纳税人识别号' colon={false}>
                                {getFieldDecorator('supplierTaxId', {
                                    rules: getRules('supplierTaxId', [{ required: true, message: '销售方纳税人识别号必填' }, ...RULES.taxId('销售方纳税人识别号')])
                                })(<MyInput readOnly={isReadOnly('supplierTaxId')} placeholder="请输入统一社会信用代码/纳税人识别号" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={12} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='销售方地址' colon={false}>
                                {getFieldDecorator('sellerAddress', {
                                    rules: getRules('sellerAddress', [{ max: 300, message: '销售方地址内容超长' }])
                                })(<MyInput readOnly={isReadOnly('sellerAddress')} placeholder="请输入销售方地址" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={12} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='电话' colon={false} className='telephone' >
                                {getFieldDecorator('sellerPhone', {
                                    rules: getRules('sellerPhone', RULES.sellerTelPhone('销售方电话'))
                                })(<MyInput readOnly={isReadOnly('sellerPhone')} placeholder="请输入电话" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={12} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='销售方开户银行' colon={false}>
                                {getFieldDecorator('sellerBank', {
                                    rules: getRules('sellerBank', RULES.bankName('销售方开户银行'))
                                })(<MyInput readOnly={isReadOnly('sellerBank')} placeholder="请输入销售方开户银行" autoComplete="off" />)}
                            </Form.Item>
                        </Col>

                        <Col span={12} style={{ display: isExpand ? undefined : 'none' }} >
                            <Form.Item label='银行账号' colon={false}>
                                {getFieldDecorator('sellerAccount', {
                                    rules: getRules('sellerAccount', RULES.bankAccount('销售方银行账号'))
                                })(<MyInput readOnly={isReadOnly('sellerAccount')} placeholder="请输入银行账号" autoComplete="off" />)}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </div>
    )
})

function NaturalPersonFlag(props: {
    // NATURAL("自然人"),  COMPANY("非自然人");
    value?: 'COMPANY' | 'NATURAL',
    onChange?: (e: 'COMPANY' | 'NATURAL') => void
    readOnly?: boolean;
}) {

    const [value, setValue] = React.useState(props.value || 'COMPANY');

    const onChange = React.useCallback((e: CheckboxChangeEvent) => {
        if (props.readOnly) return;
        setValue(e.target.checked ? 'NATURAL' : 'COMPANY');
        props.onChange && props.onChange(e.target.checked ? 'NATURAL' : 'COMPANY');
    }, [props.onChange, props.readOnly])

    React.useEffect(() => {
        setValue(props.value || 'COMPANY')
    }, [props.value])

    return (
        <Checkbox
            disabled={props.readOnly}
            checked={value === 'NATURAL'}
            onChange={onChange}
        >
            是否开票给自然人
        </Checkbox>
    )
}

function BuyerNameInput(props: InputProps & { fieldName: string; myform: WrappedFormUtils<any> }) {

    const { fieldName, myform: form } = props;

    const controller = Invoice.useInvoiceController();

    const rootElement = controller.useMemo(s => s.rootElement, []);

    const autoComplete = controller.useMemo(s => s.autoComplete, [])

    const [options, setOptions] = React.useState<any[]>([])

    const onChangeAutoComplete = React.useCallback(value => {
        const record = options.filter(e => e[fieldName] === value)[0] as any;
        if (!record || !form) return;

        form.setFieldsValue(record);
        setOptions([])
    }, [options, fieldName, form])

    const onSearch = React.useCallback(async (searchText: string) => {
        await Discontinue.start();
        try {
            if (fieldName === 'buyerName') {
                if (autoComplete.onBuyerNameSearch) {
                    setOptions(await autoComplete.onBuyerNameSearch(searchText));
                }
            } else if (fieldName === 'buyerTaxId') {
                if (autoComplete.onBuyerTaxIdSearch) {
                    setOptions(await autoComplete.onBuyerTaxIdSearch(searchText));
                }
            }

        } catch (error) {
            setOptions([]);
            throw error;
        }
    }, [autoComplete.onBuyerNameSearch, fieldName])

    if (props.readOnly) return <span className='digtal-stakeholder-form-text'>{props.value}</span>;

    return (
        <AutoComplete
            onSearch={onSearch}
            options={options.map(e => ({ value: e[fieldName] }))}
            onChange={onChangeAutoComplete}
            value={props.value}
            getPopupContainer={() => rootElement || document.body}
            style={{ width: '100%' }}
        >
            <Input {...props} style={{ width: '100%', ...props.style }} />
        </AutoComplete>
    )
}

class MyInput extends React.Component<InputProps>{
    render() {
        const props = this.props;
        if (props.readOnly) {
            return <span className='digtal-stakeholder-form-text'>{props.value}</span>
        } else {
            return <Input {...props} />
        }
    }
}

class Discontinue {

    private static timer: any;

    static start = (interval = 200) => new Promise<void>(resolve => {
        clearTimeout(Discontinue.timer);
        Discontinue.timer = setTimeout(resolve, interval);
    })
}

