import {Button, Card, Form, Input, message} from 'antd';
import React, { useEffect, useState} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import service from './service';
import {connect} from "umi";
import {ConnectState} from "@/models/connect";
import { Dispatch, AnyAction } from 'redux';

interface PasswordChange {
  newPassword: string;
  oldPassword: string;
}

interface PushChange {
  userId: number;
  noteUrl: string;
}

enum InputState {
  default = '',
  success = 'success',
  error = 'error'
}

const layout = {
  labelCol: {span: 4},
  wrapperCol: {span: 18},
};
const tailLayout = {
  wrapperCol: {offset: 4, span: 18},
};

interface Props {
  dispatch: Dispatch<AnyAction>;
}

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: PasswordChange) => {
  const hide = message.loading('正在发送');
  try {
    const data = await service.updatePassword(fields);
    if (data.success) {
      hide();
      message.success('修改成功');
    } else {
      message.error('修改失败！');
    }
  } catch (e) {
    console.log(e);
  }
};



const TableList: React.FC<Props> = (props) => {
  const [success, setSuccess] = useState<InputState>(InputState.default);

  const [form2] = Form.useForm();
  const [noteForm] = Form.useForm();

  const logOutHandle=()=>{
    const { dispatch } = props;

    if (dispatch) {
      dispatch({
        type: 'login/logout',
      });
    }
    return;
  }

  const nameExist = async () => {
    const userName = form2.getFieldValue("userName");
    if (userName == null || userName.length <= 6) {
      message.error("密码长度不够6位");
      return false;
    }
    const res = await service.nameExist({userName: form2.getFieldValue("userName")});
    if (res.success) {
      setSuccess(InputState.success);
      return true;
    }
    setSuccess(InputState.error);

    return false;
  }


  /**
   * 密码更新
   * @param values
   */
  const onFinish = (values: any) => {
    handleUpdate(values);
  };

  const updatePushUrl = (values: PushChange) => {
    values["noteUrl"] = values["noteUrl"];
    service.updatePushUrl(values).then(res => {
      if (res.success) {
        message.success("更新成功");
      } else {
        message.error('获取url失败！');
      }
    });
  };
  /**
   * 用户名更新
   * @param value
   */
  const onFinishUserName = async (value: any) => {
    const res = await service.updateAccountName(value);
    if (res.success) {
      message.success('修改成功');
      window.history.go(0);
    } else {
      message.error('修改失败！');
    }
  }

  useEffect(() => {
    service.queryPushUrl({}).then(res => {
      if (res.success) {
        noteForm.setFieldsValue({"noteUrl": res.data});
      } else {
        message.error('获取url失败！');
      }
    })
  }, [])

  // const onFinishFailed = errorInfo => {
  //   console.log('Failed:', errorInfo);
  // };

  return (
    <PageHeaderWrapper title={false}>

      <Card title="修改用户名" style={{width: '100%'}}>
        <Form
          {...layout}
          name="basic"
          form={form2}
          initialValues={{remember: true}}
          onFinish={onFinishUserName}
          // onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="新用户名"
            name="userName"
            hasFeedback
            validateStatus={success}
            rules={[{required: true, message: '请输入用户名!'}]}
          >
            <Input/>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="button" onClick={nameExist}>
              校验
            </Button>
            <span> </span>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title="重置密码" style={{width: '100%'}}>
        <Form
          {...layout}
          name="basic"
          initialValues={{remember: true}}
          onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="旧密码"
            name="oldPassword"
            rules={[{required: true, message: '请输入旧密码!'}]}
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{required: true, message: '请输入旧密码'}]}
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title="消息提醒地址" style={{width: '100%'}}>
        <Form
          {...layout}
          name="basic"
          initialValues={{}}
          onFinish={updatePushUrl}
          form={noteForm}
          // onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="提醒地址"
            name="noteUrl"
          >
            <Input/>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title="刷新页面" style={{width: '100%'}}>
        <Form
          {...layout}
          name="basic"
        >
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="button" onClick={() => {
              window.location.reload();
            }}>
              刷新页面
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title="退出登录" style={{width: '100%'}}>
        <Form
          {...layout}
          name="basic"
        >
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="button" onClick={() => {
              logOutHandle();
            }}>
              退出登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(({  }: ConnectState) => ({
}))(TableList);
