import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from "@ant-design/icons";
import { Alert, message, Tabs, Row, Col } from "antd";
import React, { useState } 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 } 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,
  shopSelectByFactory,
  productionLineSelectByShops,
  sectionSelectByShops,
  allUserSelect,
  departmentTree,
  roleSelectRegister,
} from "@/services/system";



const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

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 { initialState, setInitialState } = useModel("@@initialState");
  const [tabkey, settabkey] = useState("1");
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo(),
      menuData = await initialState?.getmenuData();

    if (userInfo) {
      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 handleSubmit = async (values) => {
    if (tabkey == "1") {
      await handleLogin()
    } else {


    }
  }



  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}>
        <div className="logincontent" style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column" }}>
          <div className={styles.content}>
            <LoginForm
              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 }}//样式适配
            >
              <Tabs
                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>
                <TabPane tab="注册" key="2">
                  {tabkey == "2" && (
                    <Row className="reg" gutter={12}>
                      <Col span={8}>
                        <ProFormText
                          name="accountName"
                          label={<b>用户名</b>}
                          placeholder="请输入用户名"
                          rules={[
                            {
                              required: true,
                              message: "请输入用户名!",
                            },
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormText
                          name="userName"
                          label={<b>姓名</b>}
                          placeholder="请输入姓名"
                          rules={[
                            {
                              required: true,
                              message: "请输入姓名!",
                            },
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormText
                          name="telephone"
                          label={<b>联系电话</b>}
                          placeholder="请输入联系电话"
                          rules={[
                            {
                              required: false,
                              message: "请输入联系电话!",
                            },
                            {
                              pattern: /^1\d{10}$/,
                              message: "手机号格式错误！",
                            },
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormTreeSelect
                          name="departmentId"
                          label={<b>组织</b>}
                          placeholder="请选择组织"
                          fieldProps={{
                            fieldNames: {
                              label: "title",
                              value: "key",
                              children: "children"
                            }
                          }}
                          request={async () => {
                            let res = await departmentTree({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: true,
                              message: "请选择组织!",
                            }
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormSelect
                          name="factoryId"
                          label={<b>工厂</b>}
                          placeholder="请选择工厂"
                          request={async () => {
                            let res = await factorySelectRegister({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: true,
                              message: "请选择工厂!",
                            }
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormDependency name={["factoryId"]}>
                          {
                            ({ factoryId }) => {

                              return <ProFormSelect
                                name="shopIdList"
                                label={<b>负责仓库</b>}
                                placeholder={"请选择负责仓库"}
                                params={{ factoryId }}
                                request={async (params) => {
                                  let res = await shopSelectByFactory({ factoryId: params.factoryId });
                                  return res?.data?.dataList ?? []
                                }}
                                rules={[
                                  {
                                    required: false,
                                    message: "请选择负责仓库!",
                                  }
                                ]}
                              />
                            }
                          }


                        </ProFormDependency>

                      </Col>

                      <Col span={8}>
                        <ProFormSelect
                          name="roleIdList"
                          label={<b>角色配置</b>}
                          placeholder="请选择角色配置"
                          request={async () => {
                            let res = await roleSelectRegister({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: false,
                              message: "请选择角色配置!",
                            }
                          ]}
                        />
                      </Col>

                      <Col span={8}>
                        <ProFormSelect
                          name="parentId"
                          label={<b>直属领导</b>}
                          placeholder="请选择直属领导"
                          request={async () => {
                            let res = await allUserSelect({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: false,
                              message: "请选择直属领导!",
                            }
                          ]}
                        />
                      </Col>
                      <Col span={8}>
                        <ProFormText
                          name="mailNo"
                          label={<b>邮箱</b>}
                          placeholder="请输入邮箱"
                          request={async () => {
                            let res = await allUserSelect({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: false,
                              message: "请输入邮箱!",
                            }
                          ]}
                        />
                      </Col>

                      <Col span={24}>
                        <ProFormTextArea
                          name="remark"
                          label={<b>备注</b>}
                          placeholder="请输入备注"
                          request={async () => {
                            let res = await allUserSelect({});
                            return res?.data?.dataList ?? []
                          }}
                          rules={[
                            {
                              required: false,
                              message: "请输入备注!",
                            }
                          ]}
                        />
                      </Col>
                    </Row>
                  )}
                </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;
