123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- import { Button, message, Radio, Spin } from 'antd';
- import React, { useCallback, useEffect, useState } from 'react';
- import { useModel, useRequest } from 'umi';
- import { fakeAccountLogin, getCode, getDingKey, ddlogin, phoneLogin, getNoteCode, isPreserve } from '@/services/login';
- import styles from './style.less';
- import { CopyrightOutlined, SwapRightOutlined } from '@ant-design/icons';
- import { useBase64 } from '@/Hook/useBase64'
- import Bg from './components/bg';
- import { history } from 'umi'
- import { api } from '@/services/api'
- import { useAjax } from '@/Hook/useAjax';
- /**
- * 退出登录,并且将当前的 url 保存
- */
- const loginOut = async () => {
- sessionStorage.removeItem('Admin-Token')
- // window.location.href = '/';
- };
- const Login: React.FC<{}> = () => {
- const { encrypt, decode } = useBase64()
- const { setInitialState, initialState } = useModel('@@initialState');
- const codeRes = useRequest((phone) => getCode(phone), { manual: true, formatResult: (res: any) => res })//钉钉验证码
- const noteCode = useRequest((phone) => getNoteCode(phone), { manual: true, formatResult: (res: any) => res })//短信验证码
- const getKey = useRequest(() => getDingKey(), { manual: true, formatResult: (res: any) => res })//获取服务器KEY
- const Ddlogin = useRequest((params: any) => ddlogin(params), { manual: true, formatResult: (res: any) => res })//用钉钉登录
- const phone_login = useRequest((params: any) => phoneLogin(params), { manual: true, formatResult: (res: any) => res })//用手机登录
- const ispreserve = useAjax(() => isPreserve())
- let phone = decode('phone')
- let code = decode('code')
- const [values, setValues] = useState<{ phone: string, code: string }>({ phone: phone || '', code: code || '' })
- const [isLogin, setIsLogin] = useState<boolean>(false)
- const [videoMenu, setVideoMenu] = useState<{ visible: boolean, left?: number, top?: number }>({ visible: false, left: 0, top: 0 })
- const [show, setShow] = useState<boolean>(false)
- const [tab, setTab] = useState<1 | 2>(2)
- const [APPID,] = useState<string>('dingwfmhucedfluenpuj')//测试 dingdsfuoevmawlyyrjx 线上dingwfmhucedfluenpuj
- const [REDIRECT_URI,] = useState<string>(encodeURIComponent(location.href?.split('?')[0]))
- const [companyList, setCompanyList] = useState<any[]>([])
- const [loading, setLoading] = useState<boolean>(false)
- const [isMobile, setIsMobile] = useState<boolean>(false)
- const [m, setM] = useState<any>(0)//倒计时,0可以点击
- const [codeType,setCodeType]=useState(1)//1钉钉验证码 2短信验证码
- // 获取运行环境
- useEffect(() => {
- let u = navigator.userAgent
- let isPhone = !!u.match(/AppleWebKit.*Mobile.*/) || u.indexOf('iPad') > -1
- if (isPhone) {
- setTab(1)
- setIsMobile(isPhone) // 判断是否在移动端
- }
- }, [])
- // 获取公司列表
- useEffect(() => {
- let data = initialState?.currentUser?.companyList
- if (data && Object.keys(data).length > 0) {
- setCompanyList(() => data as any)
- }
- }, [initialState?.currentUser?.companyList])
- //登录事件
- // const handleSubmit = async () => {
- // setIsLogin(true)
- // values.account = values.account ? values.account : account || '';
- // values.password = values.password ? values.password : password || '';
- // if (!Object.keys(values).every((key) => !!values[key])) {
- // message.error('请填写完整!')
- // setIsLogin(false)
- // return
- // } else {
- // let { code, ...value } = values
- // Object.keys(value).forEach((key) => {
- // encrypt({ key, value: value[key] })
- // })
- // }
- // console.log(values)
- // };
- //显示隐藏登录
- let handleShow = useCallback((props?: boolean) => {
- if (props && !show) {
- console.log('显示')
- setShow(true)
- }
- if (!props && show) {
- console.log('关闭')
- setShow(false)
- }
- }, [show])
- // 钉钉登录
- useEffect(() => {
- if (!sessionStorage.getItem('Admin-Token')) {
- let query = history?.location?.query
- if (query?.code) {
- Ddlogin.run({ code: query?.code, state: query?.state, stateKey: sessionStorage.getItem('DDK') }).then((msg: any) => {
- if (msg.code === 200) {
- sessionStorage.setItem('Admin-Token', msg?.data?.token)
- let companyInfo = msg?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
- setIsLogin(false)
- if (companyInfo?.length === 0) {
- sessionStorage.removeItem('Admin-Token')
- message.error('登录失败,请用趣程运营平台账号登录')
- return
- } else if (companyInfo?.length === 1) {
- setCompanyHandle(msg?.data?.companyRelationInfo[0].companyId)
- } else {
- setCompanyList(companyInfo)
- }
- // message.success('登录成功!');
- return;
- } else {
- setIsLogin(false)
- message.success('2秒后刷新页面,请重新扫码登录')
- setTimeout(() => {
- window.open(location?.origin, '_parent')
- }, 2000)
- }
- })
- } else {
- if (tab === 2) {
- let state = ''
- getKey.run().then((res) => {
- if (res?.code === 200) {
- let strArr = res?.data?.split('_')
- sessionStorage.setItem('DDK', strArr[0])
- state = strArr[1]
- }
- });
- (window as any).DDLogin({
- id: "login_container",
- goto: encodeURIComponent(`https://oapi.dingtalk.com/connect/qrconnect?appid=${APPID}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${REDIRECT_URI}`),
- style: "border:none;padding:0 0 20px 0;background-color:rgba(255,255,255,0.7);",
- width: "100%",
- height: "400"
- });
- const handleMessage = (event: { data: any; origin: any; }) => {
- // 获取loginTempCode
- const loginTempCode = event.data;
- // 获取消息来源
- const origin = event.origin;
- // 拼接 url
- const url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${APPID}&response_type=code&scope=snsapi_login&state=${encodeURIComponent(state)}&redirect_uri=${REDIRECT_URI}&loginTmpCode=${loginTempCode}`
- // 如果来源为https://login.dingtalk.com,则在当前窗口打开回调链接
- if (origin === 'https://login.dingtalk.com') {
- window.open(encodeURI(url), '_parent')
- }
- }
- // 监听iframe的消息
- if (typeof window.addEventListener != 'undefined') {
- window.addEventListener('message', handleMessage, false);
- } else if (typeof (window as any).attachEvent != 'undefined') {
- (window as any).attachEvent('onmessage', handleMessage);
- }
- }
- }
- }
- }, [tab, sessionStorage.getItem('Admin-Token')])
- // 选择公司
- const setCompanyHandle = (companyId: number) => {
- setLoading(() => true)
- fetch(api + `/erp/user/chooseCompany/${companyId}`, {
- method: 'PUT',
- headers: { ['Authorization']: 'Bearer ' + sessionStorage.getItem('Admin-Token') }
- }).then(res => res.json()).then((res: any) => {
- setLoading(() => false)
- if (res?.code === 200) {
- // 验证服务器是否升级
- fetch(api + '/erp/config/sysVersion/preserve', {
- headers: {
- 'Authorization': 'Bearer ' + res?.data?.token
- }
- }).then(res => res.json()).then(js => {
- if (js?.data?.configValue === 'true') {
- message.error('版本更新中....请关注大群公告!!!!',5,()=>{
- sessionStorage.removeItem('Admin-Token')
- window.location.href = '/';
- })
- } else {
- sessionStorage.setItem('Admin-Token', res?.data?.token)
- window.location.href = '/';
- // setTimeout(() => {
- // refresh();
- // }, 0);
- }
- })
- }
- }).catch(() => setLoading(() => false))
- }
- // 更换账户
- const logOut = () => {
- setInitialState({ ...initialState, currentUser: undefined });
- loginOut();
- }
- // 获取手机钉钉验证码
- const getPhoneCode = () => {
- let reg = new RegExp(/^(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}$/g)
- if (values) {
- setM(30)
- codeRes.run(values?.phone).then(res => {
- if (res.code === 200) {
- message.success('获取成功,请查看你的钉钉消息!验证码将发送到钉钉')
- timeOut(30)
- } else {
- timeOut(0)
- }
- })
- } else {
- message.error('请输入正确的手机号!!!')
- }
- }
- // 获取手机短信验证码
- const getPhoneNoteCode = () => {
- let reg = new RegExp(/^(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}$/g)
- if (values) {
- setM(30)
- noteCode.run(values?.phone).then(res => {
- if (res.code === 200) {
- message.success('获取成功,请查看你的短信消息!验证码将以短信的形式发送到您的手机!')
- timeOut(30)
- } else {
- timeOut(0)
- }
- })
- } else {
- message.error('请输入正确的手机号!!!')
- }
- }
- // 倒计时
- const timeOut = useCallback((num) => {
- let timer: any = null
- if (num > 0) {
- timer = setTimeout(() => {
- setM(num - 1)
- timeOut(num - 1)
- clearTimeout(timer)
- timer = null
- }, 1000)
- } else {
- setM(0)
- }
- }, [])
- // 手机登录
- const phoneSubmit = () => {
- if (values?.code) {
- phone_login.run(values).then(res => {
- try {
- if (res.code === 200) {
- setIsLogin(false)
- sessionStorage.setItem('Admin-Token', res?.data?.token)
- let companyInfo = res?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
- if (companyInfo?.length === 0) {
- sessionStorage.removeItem('Admin-Token')
- message.error('登录失败,请用趣程运营平台账号登录')
- return
- } else if (companyInfo?.length === 1) {
- setCompanyHandle(res?.data?.companyRelationInfo[0].companyId)
- } else {
- setCompanyList(companyInfo)
- }
- // message.success('登录成功!');
- return;
- } else {
- setIsLogin(false)
- // codeRes.run()
- }
- // 如果失败去设置用户错误信息
- } catch (error) {
- setIsLogin(false)
- message.error('登录失败,请重试!');
- }
- })
- }
- }
- return (
- <>
- {
- <>
- {/* {isOk?} */}
- <div className={`${styles.container}`} id='login'>
- <div className={styles.content}>
- {sessionStorage.getItem('Admin-Token') && companyList?.length > 0 ? <div className={`${styles.company} ${isMobile ? '' : show ? '' : styles.login_hide}`}>
- <h1>趣程运营管理后台</h1>
- <div className={styles.companyAccount}>
- <h3 className={styles.title}>请选择公司账户登录</h3>
- <div className={styles.chooseTableBlock}>
- <Spin spinning={loading}>
- {
- companyList?.map((item: any) => <div className={styles.acTableLine} key={item?.companyId} onClick={() => { setCompanyHandle(item.companyId) }}>
- <div className={styles.actname}>{item?.companyInfo?.companyName}</div>
- <div className={styles.right}> <div className={styles.actcha}>{item?.powerLevel === 999 ? '超级管理员' : item?.powerLevel === 100 ? '系统管理员' : item?.powerLevel === 99 ? '管理员' : '普通用户'}</div> <SwapRightOutlined className={styles.iconRight} /></div>
- </div>)
- }
- </Spin>
- </div>
- <div className={styles.button}>
- <Button type="link" onClick={logOut}>更换账号</Button>
- </div>
- </div>
- </div> : <div className={`${styles.main} ${isMobile ? '' : show ? '' : styles.login_hide}`}>
- <h1>趣程运营管理后台</h1>
- {<div className={styles.tabs}>
- <span onClick={() => { setTab(1) }} style={tab === 1 ? { color: localStorage.getItem('color') || '#24DB95' } : {}}>手机</span>
- <span onClick={() => { setTab(2) }} style={tab === 2 ? { color: localStorage.getItem('color') || '#24DB95' } : {}}>钉钉</span>
- </div>}
- {
- tab === 1 ? <>
- <div>
- <input
- placeholder='Phone'
- value={values?.phone}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
- let value = e.target.value
- if (value === '背景') {
- setVideoMenu({ visible: true })
- }
- setValues({ ...values, phone: value })
- }}
- />
- </div>
- <div>
- <input
- placeholder='Code'
- style={{ width: '60%' }}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
- let value = e.target.value
- setValues({ ...values, code: value })
- }}
- onKeyUp={(event: React.KeyboardEvent<HTMLInputElement>) => {
- if (event.key === 'Enter') {
- phoneSubmit()
- }
- }}
- />
- <button
- className={styles.btn}
- style={!m ? { background: localStorage.getItem('color') || '#24DB95' } : { background: '#999' }}
- onClick={codeType===1 ?getPhoneCode : getPhoneNoteCode}
- disabled={!!m}
- >
- {!m ? '获取验证码' : m + '秒再次获取'}
- </button>
- </div>
- <Radio.Group value={codeType} onChange={(e)=>{
- let v = e.target.value
- setCodeType(v)
- }}>
- <Radio value={1} style={{ color: '#fff' }}>钉钉验证码</Radio>
- <Radio value={2} style={{ color: '#fff' }}>手机验证码</Radio>
- </Radio.Group>
- <button
- onClick={phoneSubmit}
- disabled={isLogin}
- style={{ background: localStorage.getItem('color') || '#24DB95' }}
- >登录</button>
- </> :
- <div id='login_container' />
- }
- </div>}
- </div>
- {/**背景 */}
- {!isMobile && <Bg data={videoMenu} open={setVideoMenu} show={handleShow} isShow={show} />}
- <footer className={`${styles.footer} ${show ? '' : styles.footer_hide}`} onClick={() => { setVideoMenu({ visible: !videoMenu.visible }) }}>
- <a >
- 趣程
- </a>
- <span>Copyright<span><CopyrightOutlined /></span>趣程 </span>
- </footer>
- </div>
- </>
- }
- </>
- );
- };
- export default Login;
|