import React from "react";
import { calculateWidth } from "../../utils/utils";
import { withRouter } from "react-router-dom";
import { inject, observer } from "mobx-react/index";
import { Form, Input, message, Row, Col, Tabs } from "antd";
import PromptBox from "../../components/PromptBox";
import request from "../../utils/request";
import AccountLogin from "./AccountLogin";
import MobileLogin from "./MobileLogin";
import qs from "qs";
const { TabPane } = Tabs;

@withRouter
@inject("appStore")
@observer
@Form.create()
class LoginForm extends React.Component {
  state = {
    focusItem: -1, //保存当前聚焦的input
    code: "4568", //验证码
  };

  componentDidMount() {
    // this.createCode()
  }

  /**
   * 生成验证码
   */
  // createCode = () => {
  //   const ctx = this.canvas.getContext('2d')
  //   const chars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  //   let code = ''
  //   ctx.clearRect(0, 0, 80, 39)
  //   for (let i = 0; i < 4; i++) {
  //     const char = chars[randomNum(0, 57)]
  //     code += char
  //     ctx.font = randomNum(20, 25) + 'px SimHei'  //设置字体随机大小
  //     ctx.fillStyle = '#D3D7F7'
  //     ctx.textBaseline = 'middle'
  //     ctx.shadowOffsetX = randomNum(-3, 3)
  //     ctx.shadowOffsetY = randomNum(-3, 3)
  //     ctx.shadowBlur = randomNum(-3, 3)
  //     ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
  //     let x = 80 / 5 * (i + 1)
  //     let y = 39 / 2
  //     let deg = randomNum(-25, 25)
  //     /**设置旋转角度和坐标原点**/
  //     ctx.translate(x, y)
  //     ctx.rotate(deg * Math.PI / 180)
  //     ctx.fillText(char, 0, 0)
  //     /**恢复旋转角度和坐标原点**/
  //     ctx.rotate(-deg * Math.PI / 180)
  //     ctx.translate(-x, -y)
  //   }
  //   this.setState({
  //     code
  //   })
  // }
  loginSubmit = (e) => {
    e.preventDefault();
    this.setState({
      focusItem: -1,
    });
    this.props.form.validateFields((err, values) => {
      // this.props.appStore.toggleLogin(true, {username: values.username})
      // const {from} = this.props.location.state || {from: {pathname: '/'}}
      // this.props.history.push(from)

      if (!err) {
        // 表单登录时，若验证码长度小于4则不会验证，所以我们这里要手动验证一次，线上的未修复
        // if (this.state.code.toUpperCase() !== values.verification.toUpperCase()) {
        //   this.props.form.setFields({
        //     verification: {
        //       value: values.verification,
        //       errors: [new Error('验证码错误')]
        //     }
        //   })
        //   return
        // }
        // console.log();

        // const users = this.props.appStore.users
        // // 检测用户名是否存在
        // const result = users.find(item => item.username === values.username)
        // if (!result) {
        //   this.props.form.setFields({
        //     username: {
        //       value: values.username,
        //       errors: [new Error('用户名不存在')]
        //     }
        //   })
        //   return
        // } else {
        //   //检测密码是否错误
        //   if (result.passwd !== values.passwd) {
        //     this.props.form.setFields({
        //       passwd: {
        //         value: values.passwd,
        //         errors: [new Error('密码错误')]
        //       }
        //     })
        //     return
        //   }
        // }
        // this.props.appStore.toggleLogin(true, {username: values.username})
        // const {from} = this.props.location.state || {from: {pathname: '/'}}
        // this.props.history.push(from)
        request
          .post("/pub/login", values)
          .then((res) => {
            console.log(res);
            if (res.data.code === 200) {
              window.localStorage.setItem("token", res.data.result.token);
              this.props.appStore.toggleLogin(true, {
                userAccount: values.userAccount,
              });
              const { from } = this.props.location.state || {
                from: { pathname: "/" },
              };
              this.props.history.push(from);
            } else {
              message.error(res.data.message);
            }
          })
          .catch((err) => {
            console.error(err);
          });
      }
    });
  };
  register = () => {
    this.props.switchShowBox("register");
    setTimeout(() => this.props.form.resetFields(), 500);
  };
  register2 = () => {
    this.props.switchShowBox("Registered");
    setTimeout(() => this.props.form.resetFields(), 500);
  };

  render() {
    const { getFieldDecorator, getFieldError } = this.props.form;
    const { focusItem } = this.state;
    return (
      <div className={this.props.className}>
        <div>
        <Tabs defaultActiveKey="1">
          <TabPane tab="帐号登录" key="1">
            <AccountLogin />
          </TabPane>
          <TabPane tab="短信登录" key="2">
          <MobileLogin></MobileLogin>
          </TabPane>
        </Tabs>

        </div>
       
        <div className="switch-div">
          <div className="registerBtn" onClick={this.register2}>
            注册新号
          </div>
          <div className="registerBtn" onClick={this.register}>
            忘记密码
          </div>
        </div>
      </div>
    );
  }
}

const styles = {
  focus: {
    width: "20px",
    opacity: 1,
  },
};

export default LoginForm;
