import React, { Component } from 'react';
import { Input, Form, Space } from '@easyv/antd';
import { connect } from 'react-redux';
import styles from './PasswordResetModal.less';
import { editPassword } from 'models/user';
import { FormInstance } from '@easyv/antd/lib/form';
import EasyvModal, { ActionModalRef } from './EasyvModal';
import EasyvButton from './EasyvButton';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 14
  }
};

interface IProps {
  userInfo: any;
  children: React.ReactElement | React.ReactElement[];
  editPassword: (param, callback) => void;
}

interface IState {
  confirmDirty: boolean;
}

class PasswordModal extends Component<IProps, IState> {
  formRef = React.createRef<FormInstance>();
  modalRef = React.createRef<ActionModalRef>();
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false
    };
  }

  onSubmit = () => {
    const { userInfo = {} } = this.props;
    const { oldPassword, newPassword } = this.formRef.current?.getFieldsValue();
    this.formRef.current
      ?.validateFields()
      .then(() => {
        this.props.editPassword(
          {
            id: userInfo.userId,
            oldPassword,
            newPassword
          },
          this.onHide
        );
      })
      .catch((err) => {
        if (err.errorFields.length === 0) {
          this.props.editPassword(
            {
              id: userInfo.userId,
              oldPassword,
              newPassword
            },
            this.onHide
          );
        }
      });
  };

  onShow = () => {
    this.modalRef.current?.show();
  };

  onHide = () => {
    this.modalRef.current?.close();
  };

  compareToFirstPassword = (_rule, value) => {
    if (value && value !== this.formRef?.current?.getFieldValue('newPassword')) {
      return Promise.reject('两次密码不一致');
    } else {
      return Promise.resolve();
    }
  };

  validateToNextPassword = (_rule, value) => {
    if (value && this.state.confirmDirty) {
      this.formRef?.current?.validateFields(['confirm']);
    }
    return Promise.resolve();
  };

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  render() {
    const { children } = this.props;

    return (
      <>
        <span onClick={this.onShow} style={{ display: 'inline-block', width: '100%' }}>
          {children}
        </span>
        <EasyvModal.ActionModal
          title="修改密码"
          ref={this.modalRef}
          footer={null}
          content={
            <div className={styles.container}>
              <Form {...formItemLayout} ref={this.formRef}>
                <FormItem name="oldPassword" label="旧密码" rules={[{ required: true, message: '请输入旧密码' }]}>
                  <Input type="password" placeholder="请输入旧密码进行确认" />
                </FormItem>
                <FormItem
                  name="newPassword"
                  label="新密码"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码长度过短' },
                    { validator: this.validateToNextPassword }
                  ]}>
                  {<Input type="password" placeholder="请输入密码，6位以上任意字符" />}
                </FormItem>
                <FormItem
                  name="confirm"
                  label="确认密码"
                  rules={[{ required: true, message: '再次输入密码' }, { validator: this.compareToFirstPassword }]}>
                  <Input type="password" placeholder="再次输入新密码以确认" onBlur={this.handleConfirmBlur} />
                </FormItem>
              </Form>

              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Space>
                  <EasyvButton theme="default" onClick={() => this.modalRef.current?.close()}>
                    取消
                  </EasyvButton>
                  <EasyvButton theme="primary" onClick={this.onSubmit}>
                    确认
                  </EasyvButton>
                </Space>
              </div>
            </div>
          }
        />
      </>
    );
  }
}

function mapStateToProps(state) {
  return { userInfo: state.user.userInfo };
}

const mapDispatchToProps = {
  editPassword: editPassword
};

export default connect(mapStateToProps, mapDispatchToProps)(PasswordModal);
