import './App.less'
import { checkRoleApi, getPackApi, getServerListApi, pushLingkLogApi, sendPhoneCodeApi } from './api'
import { useAjax } from './hooks/useAjax'
import { App as AntdApp, Button, Form, Input, message, Select, Typography } from 'antd'
import headerImg from './assets/image/header.png'
import { isMobile } from './utils'
import { useEffect, useState } from 'react'
import iconSucc from './assets/image/icon-succ.png'


function App() {

	/**************************************/
	const [form] = Form.useForm()
	const serverId = Form.useWatch('serverId', form)
	const roleName = Form.useWatch('roleName', form)
	const userPhone = Form.useWatch('userPhone', form)
	const [linkLogId, setLinkLogId] = useState<number>()
	const [serverList, setServerList] = useState<{ label: string, value: any }[]>([])
	const [isCheckRoleSucc, setIsCheckRoleSucc] = useState<boolean>(false)
	const [phone, setPhone] = useState<number>()
	const [msg, setMsg] = useState<string | number>('发送验证码')
	const [succ, setSucc] = useState<boolean>(false)
	const [code, setCode] = useState<string>()

	const getServerList = useAjax((params) => getServerListApi(params))
	const pushLingkLog = useAjax((params) => pushLingkLogApi(params))
	const checkRole = useAjax((params) => checkRoleApi(params))
	const sendPhoneCode = useAjax((params) => sendPhoneCodeApi(params))
	const getPack = useAjax((params) => getPackApi(params))
	/**************************************/

	useEffect(() => {
		pushLingkLog.run({ url: window.location.href }).then(res => {
			if (res?.data) {
				setLinkLogId(res?.data)
			}
		})
	}, [])

	useEffect(() => {
		if (linkLogId) {
			getServerList.run({ linkLogId }).then(res => {
				if (res?.data) {
					setServerList(Object.keys(res.data).map(key => ({ label: res.data[key], value: key })))
				}
			})
		}
	}, [linkLogId])


	const handleCheckRole = () => {
		checkRole.run({ linkLogId, serverId, roleName }).then(res => {
			if (res?.data?.result) {
				setIsCheckRoleSucc(true)
				message.success(res?.data?.msg || '验证成功')
				if (res?.data?.userPhone) {
					setPhone(res?.data?.userPhone)
					form.setFieldsValue({ userPhone: res?.data?.userPhone })
				}
			} else {
				setIsCheckRoleSucc(false)
				message.error(res?.data?.msg || '验证失败')
				setPhone(undefined)
			}
		})
	}

	// 发送验证码
	const handleSendCode = () => {
		sendPhoneCode.run({ phoneNumber: userPhone, linkLogId }).then(res => {
			if (res?.data) {
				message.success('发送成功')
				setMsg(60)
				timeOut(60)
			}
		})
	}

	const onFinish = (values: any) => {
		const params = JSON.parse(JSON.stringify(values))
		delete params.serverId
		delete params.roleName
		getPack.run({ ...params, linkLogId }).then(res => {
			if (res?.data?.result) {
				setSucc(true)
				setCode(res?.data?.msg)
			} else {
				res?.data?.msg && message.error(res?.data?.msg || '暂无可领取的礼包')
			}
		})
	};

	// 倒计时
	const timeOut = (num: number) => {
		let timer: any = null
		if (num > 0) {
			timer = setTimeout(() => {
				setMsg(num - 1)
				timeOut(num - 1)
				clearTimeout(timer)
				timer = null
			}, 1000)
		} else {
			setMsg('发送验证码')
		}
	}

	return <AntdApp>
		<div className='send_code'>
			<img src={headerImg} alt="" />
			<div className='cK'>
				<Form
					name="basicLq"
					form={form}
					onFinish={onFinish}
					autoComplete='false'
				>
					<Form.Item name="serverId" style={{ marginBottom: 20 }} rules={[{ required: true, message: '请选择区服!' }]}>
						<Select
							style={{ width: '100%' }}
							className='selectQf'
							placeholder="选择区服"
							showSearch
							options={serverList}
							loading={getServerList.loading || pushLingkLog.loading}
							filterOption={(input, option) =>
								(option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
							}
							size="large"
							onChange={() => {
								setIsCheckRoleSucc(false)
							}}
						/>
					</Form.Item>

					<Form.Item style={{ marginBottom: 40 }}>
						<div style={{ display: 'flex', gap: 10 }}>
							<Form.Item name="roleName" rules={[{ required: true, message: '请输入角色名!' }]} noStyle>
								<Input placeholder="请输入角色名" className='inputReset' size="large" onChange={() => {
									setIsCheckRoleSucc(false)
								}} />
							</Form.Item>
							<Button style={{ backgroundColor: '#DFD4C5' }} onClick={handleCheckRole} size="large" loading={checkRole.loading} disabled={!(serverId && roleName)}><strong>角色名检测</strong></Button>
						</div>
					</Form.Item>

					<Form.Item
						name="userPhone"
						style={{ marginBottom: 20 }}
						help={phone ? <span style={{ color: '#FFFBE6', fontSize: 12 }}>手机号码如果不正确，请联系客服修改</span> : undefined}
						rules={[
							{
								required: phone ? false : true,
								validator(_rule, value) {
									if (phone) {
										return Promise.resolve()
									}
									if (!value) {
										return Promise.reject(new Error('请输入手机号!'))
									} else if (!isMobile(value)) {
										return Promise.reject(new Error('请输入正确的手机号!'))
									}
									return Promise.resolve()
								}
							}
						]}
					>
						<Input placeholder="请输入手机号" className='inputReset' size="large" disabled={!isCheckRoleSucc || !!phone} />
					</Form.Item>

					<Form.Item style={{ marginBottom: 50 }}>
						<div style={{ display: 'flex', gap: 10 }}>
							<Form.Item name="randomCode" rules={[{ required: true, message: '请输入验证码!' }]} noStyle>
								<Input placeholder="请输入验证码" className='inputReset' size="large" disabled={!isCheckRoleSucc} />
							</Form.Item>
							<Button style={{ backgroundColor: '#DFD4C5' }} size="large" disabled={!userPhone || msg !== '发送验证码'} onClick={handleSendCode}><strong>{msg === '发送验证码' ? msg : msg + 's'}</strong></Button>
						</div>
					</Form.Item>

					<Form.Item style={{ marginBottom: 10, textAlign: 'center' }}>
						<Button htmlType="submit" className="form_button" style={{ backgroundColor: '#1D1001', color: '#FFEBD5', width: 140 }} loading={getPack.loading} size="large"><strong>领取</strong></Button>
					</Form.Item>
				</Form>
			</div>

			{succ && <div className="pop">
				<div className="pop_body">
					<div className="payment_head">
						<img src={iconSucc} style={{ width: 25 }} />
						<span className="payment_amount" style={{ fontSize: 20 }}><b>领取成功</b></span>
					</div>
					<Typography.Title level={4} style={{ margin: '10px 6px' }} copyable={{ icon: <span>复制</span>, tooltips: ['复制', '复制成功'] }}>{code}</Typography.Title>
				</div>
			</div>}
		</div>
	</AntdApp>
}

export default App