import React, { useState, useEffect } from 'react';
import { Modal, Button, Input,Popover} from 'antd';
import _ from 'underscore';
import './IdentificationModal.less';
import BaseService from "@/domains/basic-domain/baseService";
import CheckBeforeSendCode from '@/components/CheckBeforeSendCode';
interface IdentificationModalProps {
    onClose:() => void,
    phone:String,
    onConfirm:() => void
}
interface checkObjectType {
    reset:() => void
}

function IdentificationModal(props: IdentificationModalProps) {
    const {onClose, phone ,onConfirm} = props;
    const [phoneVerify, setPhoneverify] = useState(''); // 验证身份的验证码
    const [codeText, setCodeText] = useState('发送验证码');
    const [waitStatus, setWaitStatus] = 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 handleConfirm(){
        if(!phoneVerify){
            setPhoneVerifyError(true);
            setErrorMessageText('请输入验证码');
           return;
        }
        const param ={
            code:phoneVerify,
            phone,
            serverType:'CLOUD_CLASS_MODIFY_PHONE'
        }
        BaseService.checkBizAuthCode(param).then((res) => {
            if(res.success){
                onConfirm();
            }else{
               setErrorMessageText(res.message);
            }
        }); 
    }
    function handleSendSMSCode(checkData:any){
       if (waitStatus) return;
        let timer:any;
        const param ={
            phone,
            serverType:'CLOUD_CLASS_MODIFY_PHONE',
            sig: checkData.sig,
            sessionId: checkData.csessionid,
            token: checkData.token,
            scene: 'nc_login'
        }
        BaseService.sendBizAuthCode(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 checkSend() {
        if (waitStatus) return;
        !_.isEmpty(checkObject) && checkObject && checkObject.reset();
        setOpenCheck(true);
    }
    return (
        <Modal
            visible={true}
            title="身份验证"
            width={448}
            onCancel={onClose}
            maskClosable={false}
            closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
            className="identification-modal"
            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="phone">{phone}</div>
        <div className="verify-content">
            <Input
                type="number"
                name="phoneverify"
                placeholder="验证码"
                className={ phoneVerifyError ? 'error-input' : ''}
                maxLength={4}
                value={phoneVerify}
                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={() => {
                    checkSend()
                }}
                >{codeText}</div>
            </Popover>
        </div>
        <div className="error-message">{errorMessageText}</div>
      
        </Modal>
    )
}

export default IdentificationModal;