import { useState, useEffect, useRef } from 'react';
import { history, useModel } from '@umijs/max';
import type { CaptFieldRef } from '@ant-design/pro-components';
import { LockOutlined, UserOutlined, FileImageOutlined, } from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProForm, ProFormText, ProFormDependency, } from '@ant-design/pro-components';
import { message, Row, Col, Image, ConfigProvider } from 'antd';
import type { CSSProperties } from 'react';
import { Login, PostSmsSend, GetCaptcha, GetUserMenulist } from '@/apis/api';
const contentStyle: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  paddingTop: '200px'
};

function flattenPermissions(permissions: { id: number; action: string; childs?: { id: number; action: string }[] }[]): string[] {
  const flattenedPermissions: string[] = [];

  permissions.forEach(permission => {
    flattenedPermissions.push(permission.action);
    if (permission.childs) {
      flattenedPermissions.push(...flattenPermissions(permission.childs));
    }
  });

  return flattenedPermissions;
}

export default () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const formRef = useRef();
  const captRef = useRef();
  const captchaRef = useRef<CaptFieldRef | null | undefined>();

  const [codeImage, setCodeImage] = useState<string>('');
  const [capt_id, setCaptId] = useState<string>('');



  useEffect(() => {
    GetCaptcha().then(res => {
      setCodeImage(res.data.img);
      setCaptId(res.data.capt_id);
    })
  }, []);

  return (
    <ConfigProvider theme={{
      token: {
        colorPrimary: '#4FBE70',
      }
    }}>
      <div style={contentStyle} >
        <LoginForm<{
          mobile: String,
          password: String,
          sms_code: Number
        }
        >
          formRef={formRef}
          title="菊城人才后台管理系统"
          subTitle="欢迎登录"
          onFinish={async (values) => {
            // 重新获取权限信息
            try {
              values.sms_code = Number(values.sms_code)
              let res = await Login(values)
              message.success('登录成功！');
              sessionStorage.setItem('token', res.data.jwttoken.accesstoken)
              let permissions = [];
              const res1 = await GetUserMenulist();
              permissions = flattenPermissions(res1.data.menulist);
              // 重新获取权限信息
              setInitialState((s) => ({
                ...s,
                permissions: permissions,
              }));
              history.push('/');
            } catch (error) {
              captRef.current.resetFields();
              formRef.current.resetFields();
              let res = await GetCaptcha()
              setCodeImage(res.data.img);
              setCaptId(res.data.capt_id);
            }
          }}
        >
          <>
            <ProFormText
              name="mobile"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />,
              }}
              placeholder={'账号'}
              rules={[
                {
                  required: true,
                  message: '请输入账号!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
            />
            <ProForm<{
              captcha: string;
            }>
              formRef={captRef}
              submitter={{ render: () => null }}
            >
              <Row gutter={10}>
                <Col span={14}>
                  <ProFormText
                    name='captcha'
                    fieldProps={{
                      size: 'large',
                      prefix: <FileImageOutlined className={'prefixIcon'} />,

                    }}
                    placeholder={'请输入图形验证码'}
                    rules={[
                      {
                        required: true,
                        message: '请输入图形验证码',
                      },
                    ]}
                  />
                </Col>
                <Col span={10}>
                  <Image src={codeImage} width='100%' height={40} preview={false} style={{ borderRadius: '8px' }} onClick={async () => {

                    let res = await GetCaptcha()
                    setCodeImage(res.data.img);
                    setCaptId(res.data.capt_id);
                  }} />
                </Col>
              </Row>
            </ProForm>
            <ProFormDependency name={['mobile']}>
              {({ mobile }) => {
                return (
                  <ProFormCaptcha
                    fieldRef={captchaRef}
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={'prefixIcon'} />
                    }}
                    captchaProps={{
                      size: 'large',

                    }}
                    placeholder={'短信验证码'}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count} ${'获取验证码'}`;
                      }
                      return '获取验证码';
                    }}
                    name="sms_code"
                    rules={[
                      {
                        required: true,
                        message: '请输入验证码！',
                      }
                    ]}
                    onGetCaptcha={async (value) => {
                      try {
                        let captcha = captRef.current?.getFieldsValue().captcha;
                        let res = await PostSmsSend({ mobile: mobile, captcha: captcha, capt_id: capt_id })
                        message.success('发送验证码成功，验证码有效期为一分钟');
                      } catch (error) {
                        let res = await GetCaptcha()
                        setCodeImage(res.data.img);
                        setCaptId(res.data.capt_id);
                        throw new Error()
                      }

                    }}
                  />
                );
              }}
            </ProFormDependency>
          </>
          <div
            style={{
              marginBlockEnd: 24,
            }}
          >

          </div>
        </LoginForm>
      </div>
    </ConfigProvider>
  );
};