import { Button, message, Radio, Spin } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { useModel, useRequest } from 'umi';
import { getCode, getDingKey, ddlogin, phoneLogin, getNoteCode, getEmailNoteCodeApi, emailLoginApi } 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';

/**  退出登录，并且将当前的 url 保存 */
const loginOut = async () => {
	localStorage.removeItem('Admin-Token')
};

const Login: React.FC<{}> = () => {
	const { 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 getEmailNoteCode = useRequest((phone) => getEmailNoteCodeApi(phone), { manual: true, formatResult: (res: any) => res })//短信验证码
	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 emailLogin = useRequest((params: any) => emailLoginApi(params), { manual: true, formatResult: (res: any) => res })//用邮箱登录
	let phone = decode('phone')
	let code = decode('code')
	const [values, setValues] = useState<{ phone: string, code: string }>({ phone: phone || '', code: code || '' })
	const [emailData, setEmailData] = useState<{ email: string, code: string }>({ email: '', 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>(1)
	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短信验证码

	// 获取TOKEN
	useEffect(() => {
		let hash = window.location.hash
		if (hash?.includes('token')) {
			let token = hash?.split('token=')[1]
			localStorage.setItem('Admin-Token', token)
			setTimeout(() => { window.location.href = '/'; }, 50)
		}
	}, [])

	// 获取运行环境
	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])

	//显示隐藏登录
	let handleShow = useCallback((props?: boolean) => {
		if (props && !show) {
			console.log('显示')
			setShow(true)
		}
		if (!props && show) {
			console.log('关闭')
			setShow(false)
		}
	}, [show])
	// 钉钉登录
	useEffect(() => {
		if (!localStorage.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) {
						localStorage.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) {
							localStorage.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)
					}
				})
			}
		}

	}, [localStorage.getItem('Admin-Token')])
	// 选择公司
	const setCompanyHandle = (companyId: number) => {
		setLoading(() => true)
		fetch(api + `/erp/user/chooseCompany/${companyId}`, {
			method: 'PUT',
			headers: { ['Authorization']: 'Bearer ' + localStorage.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, () => {
							localStorage.removeItem('Admin-Token')
							window.location.href = '/';
						})
					} else {
						localStorage.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)
				}
			}).catch(() => 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)
				}
			}).catch(() => timeOut(0))
		} else {
			message.error('请输入正确的手机号！！！')
		}
	}

	// 获取游戏验证码
	const getEmailCode = () => {
		const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
		if (emailData?.email && !regex.test(emailData.email)) {
			message.error('请输入正确的邮箱！！！')
			return 
		}
		if (emailData) {
			setM(30)
			getEmailNoteCode.run(emailData?.email).then(res => {
				if (res.code === 200) {
					message.success('获取成功，请查看你的邮箱！验证码将以邮件的形式发送到您的邮箱！')
					timeOut(30)
				} else {
					timeOut(0)
				}
			}).catch(() => timeOut(0))
		} else {
			message.error('请输入邮箱地址！！！')
		}
	}

	// 邮箱登录
	const emailSubmit = () => {
		if (emailData?.code) {
			emailLogin.run(emailData).then(res => {
				try {
					if (res.code === 200) {
						setIsLogin(false)
						localStorage.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) {
							localStorage.removeItem('Admin-Token')
							message.error('登录失败，请用趣程运营平台账号登录')
							return
						} else if (companyInfo?.length === 1) {
							setCompanyHandle(res?.data?.companyRelationInfo[0].companyId)
						} else {
							setCompanyList(companyInfo)
						}
						return;
					} else {
						setIsLogin(false)
					}
				} catch (error) {
					setIsLogin(false)
					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)
						localStorage.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) {
							localStorage.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}>

							{localStorage.getItem('Admin-Token') && companyList?.length > 0 ? <div className={`${styles.company}  ${isMobile ? '' : show ? '' : styles.login_hide}`}>
								<h1>趣程集团IAA业务应用数据系统</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}`} id='login_main'>
								<h1>趣程集团IAA业务应用数据系统</h1>
								{/*  (isMobile || location.origin === 'http://localhost:8000' || location.origin.includes('test')) */}
								<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>
												<input
													placeholder='Email'
													value={emailData?.email}
													onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
														let value = e.target.value
														if (value === '背景') {
															setVideoMenu({ visible: true })
														}
														setEmailData({ ...values, email: value })
													}}
												/>
											</div>
											<div>
												<input
													placeholder='Code'
													style={{ width: '60%' }}
													onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
														let value = e.target.value
														setEmailData({ ...emailData, 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={getEmailCode}
													disabled={!!m}
												>
													{!m ? '获取验证码' : m + '秒再次获取'}
												</button>
											</div>
											<button
												onClick={emailSubmit}
												disabled={isLogin}
												style={{ background: localStorage.getItem('color') || '#24DB95' }}
											>登录</button>
										</>
								}
							</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;