import React, { useState, useEffect } from 'react';
import { Modal, Button, Input,Popover} from 'antd';
import _ from 'underscore';
import './ChangePhoneModal.less';
import BaseService from "@/domains/basic-domain/baseService";
import CheckBeforeSendCode from '@/components/CheckBeforeSendCode';

interface changePhoneModalProps {
    onClose:() => void,
    onConfirm:any,
}

interface checkObjectType {
    reset:() => void

}

function ChangePhoneModal(props: changePhoneModalProps) {
    const { onClose,onConfirm} = props;
    const [newPhone,setNewPhone]  = useState('');
    const [phoneVerify,setPhoneVerify] = useState('');
    const [codeText, setCodeText] = useState('发送验证码'); 
    const [waitStatus, setWaitStatus] = useState(false); // 验证码是否在倒计时
    const [newPhoneError,setNewPhoneError] =  useState(false);
    const [phoneVerifyError,setPhoneVerifyError] =  useState(false);
    const [errorMessageText,setErrorMessageText] =  useState('');
    const [openCheck, setOpenCheck] = useState(false); //滑块验证是否是打开状态
    const [checkObject, setCheckObject] = useState<checkObjectType|undefined>();
    useEffect(() => {
     
    })
    async function checkAccount(code:any, callback = () => { }) {
        callback();
    }
    function checkSendPhone(){
        if (waitStatus) return;
        if(!newPhone){
            setErrorMessageText('请输入手机号'); 
            setNewPhoneError(true);
            return;
        }
        if(newPhone.length < 11){
            setErrorMessageText('请输入11位手机号'); 
            setNewPhoneError(true);  
            return; 
        }
        !_.isEmpty(checkObject) && checkObject && checkObject.reset();
        setOpenCheck(true);
    }
    function handleSendSMSCode(checkData:any){
        if (waitStatus) return;
        let timer:any;
        const param ={
            phone:newPhone,
            serverType:'CLOUD_CLASS_NEW_PHONE',
            sig: checkData.sig,
            sessionId: checkData.csessionid,
            token: checkData.token,
            scene: 'nc_login',
            appTermEnum:'XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN'
        }
        BaseService.sendNewPhoneAuthCode(param).then((res) => {
            timeSub(60,0);
        });
         function timeSub(waitTime:number, unit:number):any{
             clearTimeout(timer);
             timer = setTimeout(function () {
                 if (waitTime === 0) {
                 setCodeText('发送验证码')
                 setWaitStatus(false);
                 clearTimeout(timer);
                 } else {
                     setCodeText(`${waitTime}秒后重发`)
                     setWaitStatus(true)
                     timeSub(--waitTime, 1000);
                 }
             }, unit || 0);
         }
    }

    function handleConfirm():any{
        if(!newPhone){
            setErrorMessageText('请输入手机号'); 
            setNewPhoneError(true);
            return;
        }
        if(newPhone.length < 11){
            setErrorMessageText('请输入11位手机号'); 
            setNewPhoneError(true);  
            return; 
        }
        if(!phoneVerify){
            setErrorMessageText('请输入验证码'); 
            setPhoneVerifyError(true); 
            return;  
        }
        const param ={
            authCode: phoneVerify,
            phone: newPhone,
        }
        BaseService.editUserPhone(param).then((res) => {
            if(res.success){
                onConfirm(newPhone)
                onClose();
            }else{
              setPhoneVerifyError(true);
              setErrorMessageText(res.message); 
            }
        });
    }
    return (
        <Modal
            visible={true}
            title="更换手机号"
            width={448}
            onCancel={onClose}
            className="change-phone-modal"
            maskClosable={false}
            footer={[
                <Button
                    id='cancel_allot_btn'
                    key="back" onClick={onClose}>取消</Button>,
                <Button
                    id='confirm_allot_btn'
                    key="submit"
                    type="primary"
                    onClick={() => {
                        handleConfirm()
                    }}>
                    确认
                </Button>
            ]}
        >
            <div className="desc">请输入新的手机号</div>
            <div className="new-phone-content"> 
                <Input
                    maxLength={11}
                    name="newPhone"
                    placeholder="请输入新手机号"
                    value={newPhone}
                    className={ newPhoneError ? 'error-input' : ''}
                    onChange={(e) => { 
                        if((e.target.value).match(/^\d+$/) ||(!e.target.value) ){
                            setNewPhone(e.target.value);
                            setNewPhoneError(false);
                            setErrorMessageText('')
                        }  else {
                            setErrorMessageText('仅支持输入数字'); 
                            setNewPhoneError(true);  
                        }
                    }}
                    style={{ width:200,height:32}}
                />
                {newPhoneError && <div className="error-message">{errorMessageText}</div>}
            </div>
            <div className="verify-content"> 
                <Input
                    type="number"
                    name="phoneVerify"
                    maxLength={4}
                    placeholder="请输入验证码"
                    value={phoneVerify}
                    className={ phoneVerifyError ? 'error-input' : ''}
                    onChange={(e) => { 
                        setPhoneVerify(e.target.value);
                        setPhoneVerifyError(false);
                        setErrorMessageText('')
                    }}
                    style={{ width:200,height:32}}
                />
                <Popover
                visible={openCheck}
                trigger="click"
                title=""
                content={<div>
                <span style={{ fontSize: '12px', color: '#999', marginBottom: 8, display: 'block' }}>请完成安全验证</span>
                <CheckBeforeSendCode
                    callback={(data:any, nc:any) => {
                    setCheckObject(nc);
                    checkAccount(1, () => {
                        handleSendSMSCode(data);
                        setTimeout(() => {
                        setOpenCheck(false);
                        }, 500)
                    })
                    }}
                />
                </div>}
                onVisibleChange={(value) => {
                    if (!value) {
                        setOpenCheck(false);
                    }
                }}
                placement="bottomRight"
                >
                <div
                className="send-code"
                id="sendVerifyCode"
                onClick={() => {
                    checkSendPhone()
                }}
                >{codeText}</div>
            </Popover>
            </div>
            { phoneVerifyError && <div className="error-message">{errorMessageText}</div> }
            
        </Modal>
    )
}

export default ChangePhoneModal;