import styles from "./styles.module.scss";
import Spring from "@components/Spring";
import React, {useEffect, useState} from "react";
import {Controller, useForm} from "react-hook-form";
import classNames from "classnames";
import MultiNumPassInput from "@components/UInput/MultiNumPassInput";
import {ReactComponent as SuccessIcon} from "@assets/singlesvg/succss.svg";
import {useNavigate} from "react-router-dom";
import {ROUTE_PATH} from "@constants/routes";
import {useDispatch, useSelector} from "react-redux";
import {getSendCodeStatus, getSendCodeTS, getUserInfo} from "@features/mainSlice";
import {toast} from "react-toastify";
import {reqChangePayPass, reqForgetPayPass, reqSendCode} from "@features/api";
import {getChangePayPassStatus, getChangePayPassType, getForgetPayPassStatus} from "@features/paySlice";
import {REQ_STATUS} from "@api/config";
import SmallLoading from "@components/SmallLoading";
import {CircularProgress} from "@mui/material";
const i18n=global.i18n;
const objInfo={
    cdTimer:null
}
const WDPassEdit=({close})=>{
    const navigate=useNavigate();
    const dispatch=useDispatch();
    const user=useSelector(getUserInfo);
    const status=useSelector(getChangePayPassStatus);
    //0 新设置 1 修改 2 忘记
    const editType=useSelector(getChangePayPassType);
    const [showType,setShowType]=useState(0)
    const passLen=6;
    const {register, handleSubmit, formState: {errors}, control} = useForm({
        defaultValues: {
            oldpassword:"",
            password: "",
            repassword:"",
            code:""
        }
    });
    const [focusIndex,setFocusIndex]=useState(editType===0?0:-1);
    const otpTimeStamp=useSelector(getSendCodeTS);
    const [otpCD,setOtpCD]=useState(-1);
    const otpStatus=useSelector(getSendCodeStatus);
    const callback=(data)=>{
        if (data&&data.code===200){
            setShowType(1);
        }
    }
    const onSubmitPass=(data)=>{
        if (status===REQ_STATUS.LOADING)return;
        if (data.password!==data.repassword){
            toast.error(i18n.t("withdraw.pass.tips.err_not_same"),{toastId:"err_not_same"});
            return;
        }
        let pdata={
            newpassword:data.password,
            renewpassword:data.repassword
        }
        if (editType===1){
            pdata.oldpassword=data.oldpassword;
        }
        else if (editType===2){
            let phone=getUserPhone();
            if (phone==null||phone==="")return;
            pdata.country=user.RegisterLocation;
            pdata.phone=phone;
            pdata.code=data.code;
        }
        pdata.callback=callback;
        if (editType===2)dispatch(reqForgetPayPass(pdata));
        else dispatch(reqChangePayPass(pdata));
    }
    const clearTimer=()=>{
        if (objInfo.cdTimer!=null){
            clearInterval(objInfo.cdTimer);
            objInfo.cdTimer=null;
        }
    }
    const getUserPhone=()=>{
        let phone=user.Phone;
        if (phone==null||phone==="")return "";
        let RegisterLocation=user.RegisterLocation;
        if (RegisterLocation!=null)phone=phone.substring(RegisterLocation.length);
        return phone;
    }
    const onSendCode=(e)=>{
        if (otpCD>0)return;
        if (otpStatus===REQ_STATUS.LOADING)return;
        let phone=getUserPhone();
        if (phone==null||phone==="")return;
        let params={phone:phone,country:user.RegisterLocation};
        dispatch(reqSendCode(params));
    }
    const getLeftCD=()=>{
        let now=Date.now();
        let delta=now-otpTimeStamp;
        delta=Math.floor(delta/1000);
        delta=60-delta;
        if (delta<0)return -1;
        else return delta;
    }
    useEffect(()=>{
        return ()=>{
            clearTimer();
        }
    },[])
    useEffect(()=>{
        let left=getLeftCD();
        setOtpCD(left);
        clearTimer();
        if (left>0){
            objInfo.cdTimer=setInterval(()=>{
                left=getLeftCD();
                setOtpCD(left);
                if (left<0){
                    clearTimer();
                }
            },1000)
        }
    },[otpTimeStamp])
    const renderTitle=()=>{
        return (
            <div className={styles.title}>
                {i18n.t("withdraw.pass.edit_title")}
            </div>
        )
    }
    const renderPass=()=>{
        return (
            <Controller control={control}
                        name="password"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.password}>
                                <div>{i18n.t("withdraw.pass.new_pass")}</div>
                                <MultiNumPassInput
                                    focus={focusIndex===0}
                                    length={passLen}
                                    className={classNames({'input-control--error': error})}
                                    value={value}
                                    onChange={(num,index)=>{
                                    }}
                                    onFinish={(numArr)=>{
                                        let value=numArr.join("");
                                        onChange(value);
                                        setFocusIndex(focusIndex+1);
                                    }}
                                    innerRef={ref}
                                />
                            </div>
                        )}
            />
        )
    }
    const renderRePass=()=>{
        return (
            <Controller control={control}
                        name="repassword"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.password}>
                                <div>{i18n.t("withdraw.pass.re_pass")}</div>
                                <MultiNumPassInput
                                    focus={focusIndex===1}
                                    length={passLen}
                                    className={classNames({'input-control--error': error})}
                                    value={value}
                                    onChange={(num,index)=>{
                                    }}
                                    onFinish={(numArr)=>{
                                        let value=numArr.join("");
                                        onChange(value);
                                        setFocusIndex(focusIndex+1);
                                    }}
                                    innerRef={ref}
                                />
                            </div>
                        )}
            />
        )
    }
    const renderOldPass=()=>{
        return (
            <Controller control={control}
                        name="oldpassword"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.password}>
                                <div>{i18n.t("withdraw.pass.old_pass")}</div>
                                <MultiNumPassInput
                                    focus={focusIndex===-1}
                                    length={passLen}
                                    className={classNames({'input-control--error': error})}
                                    value={value}
                                    onChange={(num,index)=>{
                                    }}
                                    onFinish={(numArr)=>{
                                        let value=numArr.join("");
                                        onChange(value);
                                        setFocusIndex(focusIndex+1);
                                    }}
                                    innerRef={ref}
                                />
                            </div>
                        )}
            />
        )
    }
    const renderOTPInput=()=>{
        return (
            <Controller control={control}
                        name="code"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => {
                            return (
                                <div className={styles.password}>
                                    <div>{i18n.t("withdraw.pass.otp_title")}</div>
                                    <div
                                        className={`input-control ${classNames({'input-control--error': error})}`}>
                                        <input
                                            type={'text'}
                                            autoComplete="off"
                                            ref={ref}
                                            onChange={e => onChange(e.target.value)}
                                            placeholder={i18n.t('login.otp_ph')}
                                        />
                                        <button type={"button"}
                                                className={`${styles.otp_btn} ${otpCD > 0 ? styles.cd_timer : ''}`}
                                                onClick={onSendCode}>
                                            {
                                                otpStatus === REQ_STATUS.LOADING ? (
                                                    <CircularProgress color="success" size={22} thickness={5}/>) : (
                                                    <>
                                                        {
                                                            otpCD <= 0 ? i18n.t('login.btn_otp') : otpCD + "S"
                                                        }
                                                    </>
                                                )
                                            }
                                        </button>
                                    </div>
                                </div>
                            )
                        }}
            />
        )
    }
    const renderSubmitText=()=>{
        if (status===REQ_STATUS.LOADING)return (<SmallLoading fill={"#fff"}/>);
        if (editType===2){
            return (i18n.t("withdraw.pass.btn_confirm"));
        }
        else
        {
            return (i18n.t("withdraw.pass.btn_submit"));
        }
    }
    const renderSubmit=()=>{
        return (
            <div className={styles.btn_con}>
                <button className={"button-green"}>
                    {/*{status===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}/>):(i18n.t("withdraw.pass.btn_submit"))}*/}
                    {renderSubmitText()}
                </button>
            </div>
        )
    }
    const renderForm=()=>{
        return (
            <form className={styles.form} autoComplete="off" onSubmit={handleSubmit((data) => {
                onSubmitPass(data);
            })}>
                {renderTitle()}
                {editType===1?renderOldPass():(<></>)}
                {editType===2?renderOTPInput():(<></>)}
                {renderPass()}
                {renderRePass()}
                {renderSubmit()}
            </form>
        )
    }
    const renderSuccess=()=>{
        return (
            <div className={styles.success}>
                <SuccessIcon className={styles.logo}/>
                <div className={styles.title}>{i18n.t("withdraw.pass.tips.success")}</div>
                <div>{i18n.t("withdraw.pass.tips.des")}</div>
                <div className={styles.btns_con}>
                    <button className={"button-gray"} onClick={()=>{
                        // if (close)close()
                        navigate("",{replace:true})
                    }}>
                        {i18n.t("withdraw.pass.tips.btn_back")}
                    </button>
                    <button className={"button-green"} onClick={()=>{
                        navigate(ROUTE_PATH.SAQUE,{replace:true})
                    }}>
                        {i18n.t("withdraw.pass.tips.btn_withdraw")}
                    </button>
                </div>
            </div>
        )
    }
    const renderContent=()=>{
        // let InsurePass=Number(user.InsurePass);
        // if (InsurePass===1)return renderSuccess();
        // else return renderForm();

        if (showType===0)return renderForm();
        else return renderSuccess();
    }
    return (
        <>
            <div className={styles.container}>
                <Spring type="slideUp" className={styles.content}>
                    {renderContent()}
                </Spring>
            </div>
        </>
    )
}
export default WDPassEdit;
