import {
  LockOutlined,
  UserOutlined,
  LoginOutlined,
  ArrowRightOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import { Alert, message, Tabs, Row, Col, Button, Input } from "antd";
import React, { useState, useRef } 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) {
      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>
          {visible && (
            <div className={styles.search}>
              <h2
                style={{
                  fontSize: 16,
                  borderBottom: "6px solid #eee",
                  marginBottom: 12,
                  paddingBottom: 12,
                }}
                className="spread"
              >
                <a>查询注册进度</a>
                <CloseOutlined
                  style={{ color: "red" }}
                  onClick={() => {
                    setvisible(false);
                  }}
                ></CloseOutlined>
              </h2>
              <Search
                placeholder="请输入用户名"
                allowClear
                onSearch={(value) => {
                  if (value) {
                    doFetch({
                      url: "/ngic-auth/sysAccountApply/queryByAccount",
                      params: { accountName: value.replace(/^\s+|\s+$/g, "") },
                    }).then((res) => {
                      if (res.code == "0000") {
                        let data = res?.data?.data;
                        setdata(data);
                      }
                    });
                  }
                }}
                style={{ width: "100%", marginBottom: 15 }}
              />

              <ProDescriptions
                columns={[
                  {
                    title: "用户名",
                    dataIndex: "accountName",
                    key: "accountName",
                  },
                  {
                    title: "姓名",
                    dataIndex: "userName",
                    key: "userName",
                  },
                  {
                    title: "联系电话",
                    dataIndex: "telephone",
                    key: "telephone",
                  },
                  {
                    title: "工厂",
                    dataIndex: "factoryName",
                    key: "factoryName",
                  },
                  {
                    title: "组织",
                    dataIndex: "departmentName",
                    key: "departmentName",
                  },
                  {
                    title: "负责仓库",
                    dataIndex: "chargeStoreName",
                    key: "chargeStoreName",
                  },
                  {
                    title: "角色",
                    dataIndex: "roleName",
                    key: "roleName",
                  },
                  {
                    title: "直属领导",
                    dataIndex: "parentName",
                    key: "parentName",
                  },
                  {
                    title: "邮箱",
                    dataIndex: "mailNo",
                    key: "mailNo",
                  },
                  {
                    title: "审批结果",
                    dataIndex: "auditResultName",
                    key: "auditResultName",
                  },
                  {
                    title: "审批意见",
                    dataIndex: "auditOpinion",
                    key: "auditOpinion",
                  },
                  {
                    title: "审批状态",
                    dataIndex: "statusName",
                    key: "statusName",
                  },
                  {
                    title: "备注",
                    dataIndex: "remark",
                    key: "remark",
                  },
                  {
                    title: "申请时间",
                    dataIndex: "applyTime",
                    key: "applyTime",
                  },
                  {
                    title: "审批时间",
                    dataIndex: "auditTime",
                    key: "auditTime",
                  },
                  {
                    title: "审批人",
                    dataIndex: "auditUserName",
                    key: "auditUserName",
                  },
                ]}
                column={1}
                dataSource={data}
              ></ProDescriptions>
            </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" }}
                tabBarExtraContent={
                  <a
                    style={{ color: "rgba(255,255,255,0.6)" }}
                    onClick={(e) => {
                      e.stopPropagation();
                      setvisible(true);
                    }}
                  >
                    查询注册进度
                  </a>
                }
              >
                <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
                          fieldProps={{
                            style: {
                              height: 32,
                            },
                          }}
                          name="accountName"
                          label={<b>用户名</b>}
                          placeholder="请输入用户名"
                          rules={[
                            {
                              required: true,
                              message: "请输入用户名!",
                            },
                          ]}
                        />
                      </Col>

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

                      <Col span={8}>
                        <ProFormText
                          fieldProps={{
                            style: {
                              height: 32,
                            },
                          }}
                          name="telephone"
                          label={<b>联系电话</b>}
                          placeholder="请输入联系电话"
                          rules={[
                            {
                              required: false,
                              message: "请输入联系电话!",
                            },
                            {
                              pattern:
                                /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/,
                              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
                          fieldProps={{
                            mode: "multiple",
                            maxTagCount: 1,
                          }}
                          name="factoryIdList"
                          label={<b>工厂</b>}
                          placeholder="请选择工厂"
                          request={async () => {
                            let res = await factorySelectRegister({});
                            return res?.data?.dataList ?? [];
                          }}
                          rules={[
                            {
                              required: true,
                              message: "请选择工厂!",
                            },
                          ]}
                        />
                      </Col>
                      <Col span={8}>
                        <ProFormDependency name={["factoryIdList"]}>
                          {({ factoryIdList }) => {
                            return (
                              <ProFormSelect
                                fieldProps={{
                                  mode: "multiple",
                                  maxTagCount: 1,
                                }}
                                name="storeIdList"
                                label={<b>负责仓库</b>}
                                placeholder={"请选择负责仓库"}
                                params={{ factoryIdList }}
                                request={async (params) => {
                                  let res = await storeselectionBoxAll(params);
                                  return res?.data?.dataList ?? [];
                                }}
                                rules={[
                                  {
                                    required: false,
                                    message: "请选择负责仓库!",
                                  },
                                ]}
                              />
                            );
                          }}
                        </ProFormDependency>
                      </Col>

                      <Col span={8}>
                        <ProFormSelect
                          fieldProps={{
                            mode: "multiple",
                            maxTagCount: 1,
                          }}
                          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
                          fieldProps={{
                            style: {
                              height: 32,
                            },
                          }}
                          name="mailNo"
                          label={<b>邮箱</b>}
                          placeholder="请输入邮箱"
                          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;