import * as React from "react";
import { useCallback, useEffect, useState } from "react";
import { Button, Checkbox, Form, Input, Row } from "antd";
import defaultLogo from "@/assets/logo.svg";
import styles from "./sign-in.less";
import { observer } from "mobx-react";
import { history, useIntl, useModel } from "umi";
import JSEncrypt from "jsencrypt";
// @ts-ignore
import jwt from "jsonwebtoken";
import _ from "lodash";
import API from "@/api";
import { Session } from "@/utils";

const FormItem = Form.Item;

interface IComponentProps {
}

export const refreshUserInfo = (callback: Function) => {
  let _user = Session.get();
  let status = "error";
  API.AccountService.getAccountInfo().then(({ success, data }) => {
    if (!success || _.isEmpty(data)) {
      status = "error";
    } else {
      const dbUser = data.user;
      const roles = _.concat(
        _user.roles,
        _.map(data.roles, (d: any) => d.no)
      );
      _user = Object.assign(
        {},
        _user,
        dbUser,
        { roles, authorities: roles },
        { organizations: data.organizations },
        { tenants: data.tenants },
        { menus: data.menus }
      );
      Session.init(_user, true);
      status = "ok";
    }

    if (status === "ok") {
      callback && callback();
    } else {
      return;
    }
  });
};

const SignIn: React.FC<IComponentProps> = observer(({}) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [publicKey, setPublicKey] = useState<string>("");
  const { refresh } = useModel("@@initialState");
  const intl = useIntl();

  useEffect(() => {
    // API.AccountService.pk().then(({ data }) => setPublicKey(data));
  }, []);

  const handleOk = useCallback(
    (values: any) => {
      Session.destroy();
      setLoading(true);
      let user = {};
      let status = "";
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);
      values.password = encrypt.encrypt(values.password);
      API.AccountService.fakeAccountLogin(values).then(({ success, data }) => {
        if (!success || data.access_token === "ERROR") {
          status = "error";
        } else {
          status = "ok";
          const { access_token, refresh_token, ...rest } = data;
          const decoded = jwt.decode(access_token);
          if (decoded) {
            const { authorities = [] } = decoded;
            user = {
              ...decoded,
              roles: authorities,
              access_token,
              refresh_token,
              ...rest
            };
            Session.init(user);
          } else {
            status = "error";
          }
        }

        if (status === "ok") {
          refreshUserInfo(() => {
            refresh && refresh();
            setTimeout(() => {
              history.push("/");
            }, 100);
          });
        }
        setLoading(false);
      });
    },
    [publicKey]
  );

  // const logo = API.SettingService.getSystemParam("logo") || defaultLogo;
  // const appName = API.SettingService.getSystemParam("appName") || "管理系统";
  const logo = defaultLogo;
  const appName = "管理系统";

  return (
    <>
      <div className={styles.form}>
        <div className={styles.logo} onClick={() => history.push("/home")}>
          <img alt="logo" src={logo}/>
          <span>{appName}</span>
        </div>
        <Form onFinish={handleOk}>
          <FormItem name="username" rules={[{ required: true }]}>
            <Input placeholder={intl.formatMessage({ id: "Username" })}/>
          </FormItem>
          <FormItem name="password" rules={[{ required: true }]}>
            <Input
              type="password"
              placeholder={intl.formatMessage({ id: "Password" })}
            />
          </FormItem>
          <FormItem
            name="rememberMe"
            initialValue={true}
            valuePropName="checked"
            className={styles.additional}
          >
            <Checkbox className={styles.autoLogin}>
              {intl.formatMessage({ id: "RememberMe" })}
            </Checkbox>
          </FormItem>
          <Row>
            <Button
              className={styles.submit}
              type="primary"
              htmlType="submit"
              loading={loading}
            >
              {intl.formatMessage({ id: "Sign in" })}
            </Button>
          </Row>
        </Form>
      </div>
      <div className={styles.footer}></div>
    </>
  );
});

export default SignIn;
