import React, { Component } from 'react';
import hocImmutable, { imShallowEqual } from '../../utils/HOC/hocImmutable';
import { Popconfirm } from 'antd';
import Icon from '../icon';

export default hocImmutable(class extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        visible: false,
        cancelLoading: false,
        okLoading: false
    }
    store = {
        actionClicked: false
    }
    onVisibleChange = (visible) => {
        if (this.state.visible !== visible) {
            if (this.store.actionClicked && (this.state.okLoading || this.state.cancelLoading)) return;
            this.store.actionClicked = false;
            this.setState({ visible, cancelLoading: false, okLoading: false });
        }
    }
    onOk = () => {
        if (this.store.actionClicked) return;
        this.store.actionClicked = true;
        const onOk = this.props.onOk || this.props.onConfirm;
        const result = typeof onOk === 'function' && onOk();
        if (result && typeof result.then === 'function') {
            this.setState({ visible: true, okLoading: true });
            result.then(() => {
                this.setState({ visible: false, okLoading: false });
            })
        } else {
            this.setState({ visible: false });
        }
    }
    onCancel = () => {
        if (this.store.actionClicked) return;
        this.store.actionClicked = true;
        const { onCancel } = this.props;
        const result = typeof onCancel === 'function' && onCancel();
        if (result && typeof result.then === 'function') {
            this.setState({ visible: true, cancelLoading: true });
            result.then(() => {
                this.setState({ visible: false, cancelLoading: false });
            })
        } else {
            this.setState({ visible: false });
        }
    }
    render() {
        const { okText = '确定', cancelText = '取消', onOk, onConfirm, onCancel, ...props } = this.props;
        return <Popconfirm {...props}
            visible={this.state.visible}
            onVisibleChange={this.onVisibleChange}
            okText={<span><Icon type={this.state.okLoading ? 'loading' : 'check'} />&nbsp;&nbsp;{okText}</span>}
            cancelText={<span><Icon type={this.state.cancelLoading ? 'loading' : 'close'} />&nbsp;&nbsp;{cancelText}</span>}
            onConfirm={this.onOk}
            onCancel={this.onCancel}
        />
    }
})