import {
  LockOutlined,
  UserOutlined,
  LoginOutlined,
  ArrowRightOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import { Alert, message, Tabs, Row, Col, Button, Input } from "antd";
import React, { useState, useRef, useEffect, useLayoutEffect } from "react";
import {
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormDependency,
  ProFormText,
  LoginForm,
  ProFormTreeSelect,
  ProFormSelect,
  ProFormTextArea,
} from "@ant-design/pro-form";
import { Link, history, FormattedMessage, useModel } from "umi";
import { fakeAccountLogin, saveForRegister } from "@/services/login";
import styles from "./index.less";
import AES from "crypto-js/aes";
import ECB from "crypto-js/mode-ecb";
import Pkcs7 from "crypto-js/pad-pkcs7";
import Utf8 from "crypto-js/enc-utf8";
import moment from "moment";
import Footer from "@/components/Footer";
import {
  factorySelectRegister,
  storeselectionBoxAll,
  productionLineSelectByShops,
  sectionSelectByShops,
  allUserSelect,
  departmentTree,
  roleSelectRegister,
} from "@/services/system";
import { doFetch } from "@/utils/doFetch";
import { ProDescriptions } from "@ant-design/pro-components";

const { Search } = Input;

const { TabPane } = Tabs;

let col = { xs: 0, sm: 0, md: 7, lg: 6, xl: 6, xxl: 6 },
  cols = { xs: 24, sm: 24, md: 17, lg: 18, xl: 18, xxl: 18 };

const Login = () => {
  const formRef = useRef();
  const { initialState, setInitialState } = useModel("@@initialState");
  const [tabkey, settabkey] = useState("1");
  const [visible, setvisible] = useState(false);
  const [data, setdata] = useState();
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo(),
      menuData = await initialState?.getmenuData();

    if (userInfo) {
      localStorage.setItem("WMS_ID", userInfo?.data?.id);
      await setInitialState((s) => {
        return { ...s, currentUser: userInfo?.data, newMenu: menuData };
      });
    }
  };

  //登录
  const handleLogin = async (values) => {
    let timestamp = moment().valueOf().toString() + "acb";
    let newtimestamp = AES.encrypt(timestamp, Utf8.parse("NANGAODEAESKEY--"), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    let password = AES.encrypt(values.password, Utf8.parse(timestamp), {
      mode: ECB,
      padding: Pkcs7,
    }).toString();
    const postdata = {
      accountName: values.userName,
      password: password,
      encryptKey: newtimestamp,
    };
    try {
      // 登录
      const res = await fakeAccountLogin({ ...postdata });
      if (res.code === "0000") {
        let token = res?.data?.token;
        localStorage.setItem("TOKEN_MES", token);
        await fetchUserInfo();

        message.success("🎉 🎉 🎉  登录成功！");
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query;
        history.push(redirect || "/");
        return;
      }
    } catch (error) {
      message.error(res.msg);
    }
  };

  const handleReg = async (values) => {
    // 登录
    const res = await saveForRegister({ ...values });
    if (res.code === "0000") {
      message.success("注册成功,根据用户名可查询注册进度");
      formRef.current.resetFields();
      return;
    }
  };

  const handleSubmit = async (values) => {
    if (tabkey == "1") {
      await handleLogin(values);
    } else {
      await handleReg(values);
    }
  };

  return (
    <Row className={styles.container}>
      <Col {...col}>
        <div
          className="img"
          style={{
            backgroundImage: `url(${require("@/assets/loginbg.jpg")})`,
            position: "relative",
          }}
        >
          <div className="cover">
            <img alt="logo" src={require("@/assets/logo_white.png")} />
          </div>
        </div>
      </Col>
      <Col
        {...cols}
        onClick={() => {
          setvisible(false);
        }}
      >
        <div
          className="logincontent"
          style={{
            width: "100%",
            height: "100%",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <div className={styles.content}>
            <LoginForm
              submitter={{
                render: (props) => {
                  return (
                    <Button
                      {...props}
                      style={{ width: "100%" }}
                      type="primary"
                      size="large"
                      icon={
                        tabkey === "1" ? (
                          <LoginOutlined />
                        ) : (
                          <ArrowRightOutlined />
                        )
                      }
                      onClick={async () => {
                        let values = await formRef.current.validateFields();
                        await handleSubmit(values);
                      }}
                    >
                      {tabkey === "1" ? "登录" : "注册"}
                    </Button>
                  );
                },
              }}
              onValuesChange={async (values) => {
                if (Object.keys(values)[0] == "factoryIdList") {
                  formRef.current.setFieldsValue({ storeIdList: [] });
                }
              }}
              title={<span style={{ color: "#fff" }}>WMS</span>}
              subTitle={
                <span style={{ color: "rgba(255,255,255,0.6)" }}>
                  智慧仓储管理系统
                </span>
              }
              initialValues={{
                autoLogin: true,
              }}
              onFinish={async (values) => {
                await handleSubmit(values);
              }}
              style={{
                width: tabkey == "2" ? 560 : 328,
                marginLeft: tabkey == "2" ? -116 : 0,
              }} //样式适配
              formRef={formRef}
            >
              <Tabs
                style={{ justifyContent: "flex-start" }}
                activeKey={tabkey}
                onChange={settabkey}
                tabBarStyle={{ color: "#fff" }}
              >
                <TabPane tab="登录" key="1">
                  {tabkey == "1" && (
                    <>
                      <ProFormText
                        name="userName"
                        fieldProps={{
                          size: "large",
                          prefix: (
                            <UserOutlined className={styles.prefixIcon} />
                          ),
                        }}
                        placeholder="用户名"
                        rules={[
                          {
                            required: true,
                            message: "请输入用户名!",
                          },
                        ]}
                      />
                      <ProFormText.Password
                        name="password"
                        fieldProps={{
                          size: "large",
                          prefix: (
                            <LockOutlined className={styles.prefixIcon} />
                          ),
                        }}
                        placeholder="密码"
                        rules={[
                          {
                            required: true,
                            message: "请输入密码！",
                          },
                        ]}
                      />
                    </>
                  )}
                </TabPane>
              </Tabs>

              <div
                style={{
                  marginBottom: 12,
                  height: 0,
                }}
              >
                {/* <Link to="/user/logon"
                style={{
                  float: 'right',
                  textShadow: "0 0 4px #999"
                }}
              >
                <FormattedMessage id="pages.login.registerAccount" defaultMessage="" />
              </Link> */}
              </div>
            </LoginForm>
          </div>
          <Footer></Footer>
        </div>
      </Col>
    </Row>
  );
};

export default Login;
