import React from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { Form, FormItem, Field, Button } from "@antmjs/vantui";
import { useModel } from "@/store";
import user from "@/assets/image/user.png";
import password from "@/assets/image/password.png";
import { warn } from "@/utils/message";
import "./form.less";

export default (props) => {
  const { onSuccess } = props;

  const { signin } = useModel("user");
  const form = Form.useForm();
  const [accErr, setAccErr] = React.useState();
  const [pwdErr, setPwdErr] = React.useState();
  const [loading, setLoading] = React.useState(false);

  const onFinish = (errs, res) => {
    console.log(11111111);
    if (!res.account) {
      setAccErr("账户不能为空");
      return;
    } else {
      setAccErr();
    }
    if (!res.password) {
      setPwdErr("密码不能为空");
      return;
    } else {
      setPwdErr();
    }

    setLoading(true);
    signin(res)
      .then(() => {
        onSuccess();
        setLoading(false);
      })
      .catch((err) => {
        setLoading(false);
      });
  };

  const onForgetPwd = () => {
    // Taro.navigateTo({
    //   url: '/pages/reset-password/index'
    // });
    warn(true, "请联系管理人员");
  };

  const handleClick = () => {
    form.validateFields((err, res) => {
      if (!res.account) {
        setAccErr("账户不能为空");
        return;
      } else {
        setAccErr();
      }
      if (!res.password) {
        setPwdErr("密码不能为空");
        return;
      } else {
        setPwdErr();
      }
  
      setLoading(true);
      signin(res)
        .then(() => {
          onSuccess();
          setLoading(false);
        })
        .catch((err) => {
          setLoading(false);
        });
    });
    console.log(11111);
  };
  return (
    <View className="login-form">
      {/* onFinish={onFinish} */}
      <Form form={form} >
        <FormItem name="account" valueFormat={(e) => e.detail}>
          <Field
            border
            label="账号"
            leftIcon={user}
            errorMessage={accErr}
            placeholder="请输入您的登录账号"
          ></Field>
        </FormItem>
        <FormItem name="password" valueFormat={(e) => e.detail}>
          <Field
            password
            label="密码"
            leftIcon={password}
            errorMessage={pwdErr}
            placeholder="请输入您的登录密码"
          ></Field>
        </FormItem>
        <View className="forget-password" onClick={onForgetPwd}>
          忘记密码?
        </View>
        <View>
          <Button
            block
            type="primary"
            // formType="submit"
            loading={loading}
            disabled={loading}
            onClick={handleClick}
          >
            登录
          </Button>
        </View>
      </Form>
    </View>
  );
};
