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 } 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 { erpApi } 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 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 })//用手机登录
	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>(1)
	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短信验证码

	// 获取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)
					}
				})
			} 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, localStorage.getItem('Admin-Token')])
	// 选择公司
	const setCompanyHandle = (companyId: number) => {
		setLoading(() => true)
		fetch(erpApi + `/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(erpApi + '/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)
				}
			})
		} 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)
						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(companyInfo[0].companyId)
						} else {
							setCompanyList(companyInfo)
						}
						return;
					} else {
						setIsLogin(false)
					}
				} 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>趣程游戏数据系统</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>趣程游戏数据系统</h1>
								{/*  (isMobile || location.origin === 'http://localhost:8000' || location.origin.includes('test')) */}
								{true && <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;