import { useEffect, useState, useRef } from 'react';

import {
    Box,
    Button, Checkbox
    // MenuItem
    , FormControl, FormGroup, FormHelperText,
    Grid, IconButton,
    InputAdornment,
    InputLabel, OutlinedInput,
    Stack, TextField, Typography
} from '@mui/material';
import Autocomplete from "@mui/material/Autocomplete";
import { useForm } from 'react-hook-form';

// third party
import { FormikProvider, useFormik } from 'formik';
import * as yup from 'yup';
// import axios from "axios";

// project import
// import AnimateButton from 'components/@extended/AnimateButton';
import { strengthColorChi, strengthIndicator } from 'utils/password-strength';
// import {apiPath} from "auth/utils";
import axios from "axios";
import { POST_USERNAME, POST_USER_EMAIL, POST_CAPTCHA, POST_PUBLIC_USER_REGISTER, POST_IDNO, POST_CAPTCHA_AUDIO } from "utils/ApiPathConst";
// import * as HttpUtils from 'utils/HttpUtils';
import * as ComboData from "utils/ComboData";

import Loadable from 'components/Loadable';
import { lazy } from 'react';
const UploadFileTable = Loadable(lazy(() => import('./UploadFileTable')));
const PreviewUploadFileTable = Loadable(lazy(() => import('./PreviewUploadFileTable')));
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
// import UploadFileTable from './UploadFileTable';
// import LoadingComponent from "../../extra-pages/LoadingComponent";

// assets
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
// import { Paper } from '../../../../node_modules/@mui/material/index';
import { ThemeProvider } from "@emotion/react";
import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import LoopIcon from '@mui/icons-material/Loop';
import { useTheme } from '@mui/material/styles';
import { FormattedMessage, useIntl } from "react-intl";
import { Link } from 'react-router-dom';
import { PNSPS_LONG_BUTTON_THEME } from "../../../themes/buttonConst";
import * as HttpUtils from "../../../utils/HttpUtils";
import { notifyActionError } from 'utils/CommonFunction';
// ============================|| FIREBASE - REGISTER ||============================ //

const CustomFormWizard = (props) => {
    const intl = useIntl();
    const { locale } = intl;

    const theme = useTheme()
    const [level, setLevel] = useState();
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setshowConfirmPassword] = useState(false);
    const [showId, setshowId] = useState(false);
    const [fileList, setFileList] = useState([]);
    const [fileListData, setFileListData] = useState([]);
    const [checkUpload, setCheckUpload] = useState(false);
    const [isLoading, setLoding] = useState(true);
    const [updateRows, setUpdateRows] = useState([]);
    const [captchaImg, setCaptchaImage] = useState("");
    const [base64Url, setBase64Url] = useState("")
    const [checkCode, setCheckCode] = useState("")

    const handleClickShowPassword = () => {
        setShowPassword(!showPassword);
    };

    const handleClickShowConfirmPassword = () => {
        setshowConfirmPassword(!showConfirmPassword);
    };

    const handleMouseDownPassword = (event) => {
        event.preventDefault();
    };

    const handleClickShowId = () => {
        setshowId(!showId);
    };

    const handleMouseDownId = (event) => {
        event.preventDefault();
    };

    const changePassword = (value) => {
        const temp = strengthIndicator(value);
        setLevel(strengthColorChi(temp));
    };

    const [selectedIdDocType, setSelectedIdDocType] = useState({});
    const [selectedIdDocInputType, setSelectedIdDocInputType] = useState();
    const [selectedAddress4, setSelectedAddress4] = useState(null);
    const [selectedAddress5, setSelectedAddress5] = useState(ComboData.country[0]);
    const [termsAndConAccept, setTermsAndConAccept] = useState(false);
    const [termsAndConNotAccept, setTermsAndConNotAccept] = useState(false);
    const [isValid, setisValid] = useState(false);
    const [checkCountry, setCheckCountry] = useState(false);
    // eslint-disable-next-line no-unused-vars -- used as ref for hidden file input (ref={fileInputRef}) and in click handlers
    const fileInputRef = useRef(null);
    
    const username = document.getElementById("username-login")
    const [checkUsername, setCheckUsername] = useState(false);
    const [checkUsernameBlur, setCheckUsernameBlur] = useState(false)
    
    const idDocNumber = document.getElementById("idNo-login")
    const [checkIdDocNumber, setCheckIdDocNumber] = useState(false)
    const [checkIdDocNumberBlur, setCheckIdDocNumberBlur] = useState(false)
    
    const [idDocHKIDNumber, setIdDocHKIDNumber] = useState(document.getElementById("idNo-hkid-login"))
    const [checkIdDocHKIDNumberBlur, setCheckIdDocHKIDNumberBlur] = useState(false)
    
    const [checkDigit, setCheckDigit] = useState(document.getElementById("checkDigit-login"))
    const [checkCheckDigitBlur, setCheckCheckDigitBlur] = useState(false)
    const [checkHKIdDocWithCheckDigit, setCheckHKIdDocWithCheckDigit] = useState(false)
    
    const email = document.getElementById("email-login")
    const [checkEmail, setCheckEmail] = useState(false)
    const [checkEmailBlur, setCheckEmailBlur] = useState(false)
    
    const district = document.getElementById("address4-combo")
    const [checkDistrict, setCheckDistrict] = useState(false)
    const [checkDistrictBlur, setCheckDistrictBlur] = useState(false)
    const [districtErrStr, setDistrictErrStr] = useState("")

    const idDocTypeComboList = ComboData.idDocType;
    const refType = "identification";

    useEffect(() => {
        changePassword('');
        if (captchaImg == ""){
            onCaptchaChange();
        }
    }, []);

    const playCaptchaAudio = async () => {
        try {
            const resp = await axios.post(
            `${POST_CAPTCHA_AUDIO}`,
            { base64Url, lang: intl.locale },
            { responseType: "arraybuffer" }
            );

            const blob = new Blob([resp.data], { type: "audio/wav" });
            const url = URL.createObjectURL(blob);

            const audio = new Audio(url);

            await audio.play();

        } catch (error) {

            let message = intl.formatMessage({ id: "captchaAudioError" });

            if (error.response) {
                if (error.response.status === 404) {
                    message = intl.formatMessage({ id: "captchaExpired" });
                } else if (error.response.status === 500) {
                    message = intl.formatMessage({ id: "captchaAudioServerError" });
                }
            } else if (error.request) {
                message = intl.formatMessage({ id: "connectionError" });
            }

            notifyActionError(message);
        }
    };
    
    useEffect(() => {
        if (selectedIdDocType.type === "HKID"){
            setIdDocHKIDNumber(document.getElementById("idNo-hkid-login"))
            setCheckDigit(document.getElementById("checkDigit-login"))
            // setTimeout(() => {
            // }, 1000);
        }
    }, [selectedIdDocType]);

    const handleCheckUsername = async () => {
        if (values?.username) {
            if (handleUsername(values.username)){
                const response = await axios.post(`${POST_USERNAME}`, {
                    u1: values.username,
                })
                setCheckUsername((Number(response.data[0]) > 0))
                return Number(response.data[0]) > 0
            }
        }
    }

    const handleCheckIdDocNumber = async () => {
        if (values?.idNo&&values?.checkDigit !="") {
            if (handleIdNo(values.idNo, selectedIdDocType.type, values.checkDigit)){
                const response = await axios.post(`${POST_IDNO}`, {
                    i1: values.idNo,
                })
                // console.log(response.data.Vaild)
                setCheckIdDocNumber(response.data.Vaild === false)
                return response.data.Vaild === false
            }
        }
    }
    
    const handleCheckIdDocNumberbyCheckDigit = async () => {
        if (values?.checkDigit) {
            if (handleIdNo(values.idNo, selectedIdDocType.type, values.checkDigit)){
                const response = await axios.post(`${POST_IDNO}`, {
                    i1: values.idNo,
                })
                // console.log(response.data.Vaild)
                setCheckIdDocNumber(response.data.Vaild === false)
                return response.data.Vaild === false
            }
        }
    }

    /** POST /user/checkE1 — returns true if email is already registered */
    const checkEmailRegistered = async (emailStr) => {
        const em = emailStr?.trim();
        if (!em) return false;
        const response = await axios.post(`${POST_USER_EMAIL}`, { e1: em });
        return Number(response.data[0]) > 0;
    };

    const handleCheckEmail = async () => {
        if (!values?.email) return false;
        if (!handleEmail(values.email)) return false;
        try {
            const taken = await checkEmailRegistered(values.email);
            setCheckEmail(taken);
            return taken;
        } catch (error) {
            notifyActionError(intl.formatMessage({ id: 'connectionError' }));
            return false;
        }
    };
    
    const isDistrictSelectionValid = () => {
        if (selectedAddress5?.type !== "hongKong") {
            return true;
        }
        return !(selectedAddress4 == null || selectedAddress4 === "");
    };

    const handleCheckDistrict = () => {
        setDistrictErrStr("");
        if (selectedAddress5?.type === "hongKong") {
            if (selectedAddress4 == null || selectedAddress4 == "" || selectedAddress4 == {}){
                setCheckDistrict(true) 
                setDistrictErrStr(getRequiredErrStr("district"))
            }else {
                setCheckDistrict(false)
            }
        } else {
            setCheckDistrict(false);
        }
    }

    useEffect(() => {
        handleCheckDistrict();
    }, [selectedAddress4, selectedAddress5]);

    useEffect(() => {
        if (username) {
            username.addEventListener("blur", function () {
                setCheckUsernameBlur(true)
            })
        }
    }, [username])

    useEffect(() => {
        if (checkUsernameBlur) {
            handleCheckUsername()
            setCheckUsernameBlur(false)
        }
    }, [checkUsernameBlur])

    useEffect(() => {
        if (idDocNumber) {
            idDocNumber.addEventListener("blur", function () {
                setCheckIdDocNumberBlur(true)
            })
        }
    }, [idDocNumber])

    useEffect(() => {
        if (checkIdDocNumberBlur) {
            handleCheckIdDocNumber()
            setCheckIdDocNumberBlur(false)
        }
    }, [checkIdDocNumberBlur])

    useEffect(() => {
        if (idDocHKIDNumber) {
            idDocHKIDNumber.addEventListener("blur", function () {
                setCheckIdDocHKIDNumberBlur(true)
            })
        }
    }, [idDocHKIDNumber])

    useEffect(() => {
        if (checkIdDocHKIDNumberBlur) {
            handleCheckIdDocNumber()
            setCheckIdDocHKIDNumberBlur(false)
        }
    }, [checkIdDocHKIDNumberBlur])

    useEffect(() => {
        if (checkDigit) {
            checkDigit.addEventListener("blur", function () {
                setCheckCheckDigitBlur(true)
            })
        }
    }, [checkDigit])

    useEffect(() => {
        if (checkCheckDigitBlur) {
            handleCheckIdDocNumberbyCheckDigit()
            setCheckCheckDigitBlur(false)
        }
    }, [checkCheckDigitBlur])

    useEffect(() => {
        if (email) {
            email.addEventListener("blur", function () {
                setCheckEmailBlur(true)
            })
        }
    }, [email])

    useEffect(() => {
        if (checkEmailBlur) {
            handleCheckEmail()
            setCheckEmailBlur(false)
        }
    }, [checkEmailBlur])
    
    useEffect(() => {
        if (district) {
            district.addEventListener("blur", function () {
                setCheckDistrictBlur(true)
            })
        }
    }, [district])

    useEffect(() => {
        if (checkDistrictBlur) {
            handleCheckDistrict()
            setCheckDistrictBlur(false)
        }
    }, [checkDistrictBlur])

    const onCaptchaChange = () => {
        HttpUtils.post({
            url: POST_CAPTCHA,
            params: { width: 130, height: 40, captcha: captchaImg },
            onSuccess: (responseData) => {
                props.setBase64Url(responseData.base64Url)
                setBase64Url(responseData.base64Url)
                localStorage.setItem("base64Url", responseData.base64Url);
                setCaptchaImage(localStorage.getItem('base64Url'));
            }
        });
    }

    /** Step-0 validity excluding duplicate-email result from /checkE1 (see checkEmail state). */
    const computeStep0ValidSync = (data) => (
        handleCaptcha(data.captchaField) &&
        data.username !== "" &&
        data.password !== "" &&
        data.confirmPassword !== "" &&
        data.password == data.confirmPassword &&
        selectedIdDocType.type !== "" &&
        data.idNo !== "" &&
        handleName(data.enName, data.chName) &&
        data.address1 !== "" &&
        data.email !== "" &&
        data.emailConfirm !== "" &&
        data.email == data.emailConfirm &&
        data.phone !== "" &&
        data.phoneCountryCode !== "" &&
        termsAndConAccept == true &&
        fileList.length !== 0 &&
        handlePassword(data.password) &&
        handleEmail(data.email) &&
        handleIdNo(data.idNo, selectedIdDocType.type, data.checkDigit) &&
        handlePhone(data.phone) &&
        handleUsername(data.username) &&
        isDistrictSelectionValid() &&
        !checkUsername &&
        !checkIdDocNumber
    );

    const computeStep0Valid = (data) => computeStep0ValidSync(data) && !checkEmail;

    const checkDataField = (data) => {
        const can = computeStep0Valid(data);
        setisValid(can);
        return can;
    };

    const handleCheckBoxChange = (event) => {
        if (event.target.name == 'termsAndConAccept') {
            setTermsAndConAccept(event.target.checked)
            setTermsAndConNotAccept(!event.target.checked)
        }
        if (event.target.name == 'termsAndConNotAccept') {
            setTermsAndConNotAccept(event.target.checked)
            setTermsAndConAccept(!event.target.checked)
        }
    };

    useEffect(() => {
        let updateRowList = new DataTransfer();
        var updateRowsIndex = updateRows.length;
        const saveFileList = [];

        if (updateRowsIndex != null) {
            for (let i = 0; i < updateRowsIndex; i++) {
                const file = updateRows[i]
                file.id = i;
                updateRowList.items.add(file);
                saveFileList.push(file);
            }
            let updatedFileList = updateRowList.files;
            setFileList(updatedFileList);
            setFileListData(saveFileList)

        }

    }, [updateRows]);

    const handleFileUpload = (event) => {
        let updateList = new DataTransfer();
        let currentFileList = fileListData;
        const uploadFileList = event.target.files;
        const saveFileList = [];
        var currentIndex = 0;

        if (currentFileList.length != null) {
            currentIndex = currentFileList.length;
            for (let i = 0; i < currentIndex; i++) {
                const file = currentFileList[i]
                // file.id = currentIndex;
                updateList.items.add(file);
                saveFileList.push(file);
            }
        }

        for (let i = 0; i < uploadFileList.length && currentIndex < 5; i++) {
            const file = event.target.files[i]
            let isDuplicate = false;

            // Check if the file name already exists in saveFileList
            for (let j = 0; j < saveFileList.length; j++) {
                if (saveFileList[j].name === file.name) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate && i + currentIndex < 5) {
                file.id = currentIndex + i
                saveFileList.push(file)
                updateList.items.add(file);
            }

        }
        let updatedFileList = updateList.files;

        setFileListData(saveFileList)
        setFileList(updatedFileList);
    };

    useEffect(() => {
        props.setUpdateValid(isValid)
    }, [isValid])

    useEffect(() => {
        checkDataField(values)
    }, [
        selectedIdDocType,
        selectedAddress4, selectedAddress5,
        termsAndConAccept, termsAndConNotAccept, fileList])

    // useEffect(() => {
    //     setDistrictErrStr("");
    //     if (selectedAddress5?.type === "hongKong") {
    //         if (selectedAddress4 == null || selectedAddress4 == "" || selectedAddress4 == {})
    //             setDistrictErrStr(getRequiredErrStr("district"))
    //     }
    // }, [selectedAddress4, selectedAddress5])

    useEffect(() => {
        props.step == 2 ? _onSubmit() : null;
        if (captchaImg == "")
            onCaptchaChange();
        checkDataField(values)
    }, [props.step])

    const { handleSubmit } = useForm({})
    const _onSubmit = () => {
        setLoding(true);
        values.idDocType = selectedIdDocType.type
        values.address4 = selectedAddress4 == null ? "" : selectedAddress4.type
        values.address5 = selectedAddress5.type
        // console.log(values)
        const userAddress = {
            "addressLine1": "",
            "addressLine2": "",
            "addressLine3": "",
            "district": "",
            "country": ""
        };
        userAddress.addressLine1 = values.address1
        userAddress.addressLine2 = values.address2
        userAddress.addressLine3 = values.address3
        userAddress.district = values.address4
        userAddress.country = values.address5

        const userFaxNo = {
            "countryCode": values.faxCountryCode,
            "faxNumber": values.fax,
        };
        const userMobileNumber = {
            "countryCode": values.phoneCountryCode,
            "phoneNumber": values.phone,
        };
        let tncFlag = false;
        if (termsAndConAccept) {
            tncFlag = true
        }
        if (termsAndConNotAccept) {
            tncFlag = false
        }

        const preferLocale = locale === 'en' ? 'en': locale === 'zh-HK' ? 'zh_HK': 'zh-CN'
        const user = {
            username: values.username,
            password: values.password,
            name: values.username,
            enName: values.enName,
            chName: values.chName,
            emailAddress: values.email,
            idDocType: values.idDocType,
            identification: values.idNo,
            checkDigit: values.checkDigit,
            tncFlag: tncFlag,
            type: "IND",
            captcha: base64Url,
            checkCode: checkCode,
            preferLocale: preferLocale
        };

        var formData = new FormData();
        for (let i = 0; i < fileListData.length; i++) {
            const file = fileListData[i]
            formData.append("multipartFileList", file);
        }
        formData.append("refType", refType);

        for (const [key, value] of Object.entries(user)) {
            formData.append(key, value);
        }

        formData.append("userFaxNo", JSON.stringify(userFaxNo));
        formData.append("userMobileNumber", JSON.stringify(userMobileNumber));
        formData.append("userAddress", JSON.stringify(userAddress));
        // formData.append("preferLocale", "en");

        // if(refCode){
        //     formData.append("refCode", refCode);
        // }

        if (isValid) {
            axios.post(POST_PUBLIC_USER_REGISTER, formData, {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            })
                .then((
                    // response
                ) => {
                    // console.log(response)
                    setCheckUpload(true)
                    setLoding(false);
                })
                .catch(error => {
                    console.error(error);
                    setLoding(false);
                });
        } else {
            setLoding(false);
        }
    }

    function handlePhone(phone) {
        if (phone.length < 8) {
            return false;
        } else {
            // console.log("Phone true")
            return true;
        }
    }

    function handleUsername(username) {
        var symbol = /^(?=.*\W)/;
        var space = /\s/;
        if (username.length < 6) {
            return false;
        } else if (username.match(symbol)) {
            return false;
        } else if (username.match(space)) {
            return false;
        } else {
            return true;
        }
    }

    function handleCaptcha(captchaField) {
        // console.log(captchaField.length)
        if (captchaField.length == 5 ){
            return true
        } else {
            return false
        }
    }

    function handleIdNo(idNo, selectedIdDocType, checkDigit) {
        // var pattern = /^[A-Z][0-9]*$/;
        var pattern_HKIDv1 = /^[A-Z]{1}[0-9]{6}$/;
        var pattern_HKIDv2 = /^[A-Z]{2}[0-9]{6}$/;
        var pattern_passport = /^[A-Z]{1}[0-9]{8}$/;
        var pattern_CHID = /^[0-9]{6}(20|19)[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9X]{1}/;
        var pattern_otherCert = /^[A-Z]{1}[0-9]{5,}/;
        // var space = /\s/;
        // if (!idNo.match(pattern)) {
        //     return false;
        // } else if (selectedIdDocType=="HKID"&&checkDigit==""){
        //     return false;
        // } else if (idNo.match(space)) {
        //     return false;
        // } else if (idNo.length < 6) {
        //     return false;
        // } else {
        //     // console.log("IdNo true")
        //     return true;
        // }
        switch (selectedIdDocType) {
            case "HKID":
                if (checkDigit === ""){
                    setCheckHKIdDocWithCheckDigit(true)
                    return false
                } else{
                    setCheckHKIdDocWithCheckDigit(false)
                }
                if (idNo.match(pattern_HKIDv1)) {
                    return true
                } else if (idNo.match(pattern_HKIDv2)) {
                    return true
                } else {
                    return false
                }
            case "passport":
                if (idNo.match(pattern_passport)) {
                    return true
                } else {
                    return false
                }
            case "CNID":
                if (idNo.match(pattern_CHID)) {
                    const subStr_year = idNo.substring(6, 10)
                    const subStr_month = idNo.substring(10, 12)
                    const subStr_date = idNo.substring(12, 14)

                    const today = new Date()
                    const inputDate = new Date(`${subStr_year}-${subStr_month}-${subStr_date}`)

                    if (inputDate > today || inputDate === "Invalid Date" || inputDate.getFullYear().toString() !== subStr_year || (inputDate.getMonth() + 1).toString().padStart(2, "0") !== subStr_month || inputDate.getDate().toString().padStart(2, "0") !== subStr_date) {
                        return false
                    } else {
                        return true
                    }
                } else {
                    return false
                }
            case "otherCert":
                if (idNo.match(pattern_otherCert)) {
                    return true
                } else {
                    return false
                }
            default:
                break;
        }
    }

    function handleName(enName, chName) {
        if (enName == "" && chName !== ""){
            return true
        } else if (enName !== "" && chName == ""){
            return true
        } else if (enName !== "" && chName !== "") {
            return true
        } else {
            return false
        }
    }

    function handlePassword(password) {
        let new_pass = password;
        // regular expressions to validate password
        var lowerCase = /[a-z]/g;
        var upperCase = /[A-Z]/g;
        var numbers = /[0-9]/g;
        var symbol = /^(?=.*\W)/;
        var space = /\s/;
        if (!new_pass.match(lowerCase)) {
            return false;
        } else if (!new_pass.match(upperCase)) {
            return false;
        } else if (!new_pass.match(numbers)) {
            return false;
        } else if (!new_pass.match(symbol)) {
            return false;
        } else if (new_pass.length < 8) {
            return false;
        }
        else if (new_pass.match(space)) {
            return false;
        } else {
            // console.log("password true")
            return true;
        }
    }

    function handleEmail(email) {
        var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
        if (!email.match(validRegex)) {
            return false;
        } else {
            return true;
        }
    }

    function displayErrorMsg(errorMsg) {
        return <Typography variant="errorMessage1">{errorMsg}</Typography>
    }

    function getMaxErrStr(num, fieldname) {
        return displayErrorMsg(intl.formatMessage({ id: 'noMoreThenNWords' }, { num: num, fieldname: fieldname ? intl.formatMessage({ id: fieldname }) + ": " : "" }));
    }
    function getRequiredErrStr(fieldname) {
        return displayErrorMsg(intl.formatMessage({ id: 'require' }, { fieldname: fieldname ? intl.formatMessage({ id: fieldname }) : "" }));
    }

    const formik = useFormik({
        initialValues: ({
            username: '',
            enName: '',
            chName: '',
            email: '',
            emailConfirm: '',
            address1: '',
            address2: '',
            address3: '',
            password: '',
            confirmPassword: '',
            phone: '',
            phoneCountryCode: '852',
            idNo: '',
            checkDigit: '',
            submit: null,
            fax: '',
            faxCountryCode: '852',
            idDocType: '',
            captchaField: ''
        }),
        validationSchema: yup.object().shape({
            username: yup.string().min(6, displayErrorMsg(intl.formatMessage({ id: 'atLeast6CharAccount' }))).max(30, getMaxErrStr(30)).required(displayErrorMsg(intl.formatMessage({ id: 'requireUsername' })))
                .matches(/^[aA-zZ0-9\s]+$/, { message: displayErrorMsg(intl.formatMessage({ id: 'noSpecialCharAccount' })) })
                .matches(/^\S*$/, { message: displayErrorMsg(intl.formatMessage({ id: 'noSpaceAccount' })) }),
            password: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'atLeast8CharPassword' }))).max(60, getMaxErrStr(60)).required(displayErrorMsg(intl.formatMessage({ id: 'requirePassword' })))
                .matches(/^\S*$/, { message: displayErrorMsg(intl.formatMessage({ id: 'noSpacePassword' })) })
                .matches(/^(?=.*[a-z])/, { message: displayErrorMsg(intl.formatMessage({ id: 'atLeastOneSmallLetter' })) })
                .matches(/^(?=.*[A-Z])/, { message: displayErrorMsg(intl.formatMessage({ id: 'atLeastOneCapLetter' })) })
                .matches(/^(?=.*[0-9])/, { message: displayErrorMsg(intl.formatMessage({ id: 'atLeast1Number' })) })
                .matches(/^(?=.*\W)/, { message: displayErrorMsg(intl.formatMessage({ id: 'atLeast1SpecialChar' })) }),
            confirmPassword: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'atLeast8CharPassword' }))).required(displayErrorMsg(intl.formatMessage({ id: 'pleaseConfirmPassword' }))).oneOf([yup.ref('password'), null], displayErrorMsg(intl.formatMessage({ id: 'samePassword' }))),
            chName: yup.string().max(6, getMaxErrStr(6)),
            enName: yup.string().max(40, getMaxErrStr(40)).when('chName', {
                is: (chName) => chName?false:true,
                then: yup.string().required(displayErrorMsg(intl.formatMessage({ id: 'registerNameLabel' })))
            }),
            
            address1: yup.string().max(40, getMaxErrStr(40, "addressLine1")).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
            address2: yup.string().max(40, getMaxErrStr(40, "addressLine2")),
            address3: yup.string().max(40, getMaxErrStr(40, "addressLine3")),
            email: yup.string().email(displayErrorMsg(intl.formatMessage({ id: 'validEmailFormat' }))).max(128, getMaxErrStr(128)).required(displayErrorMsg(intl.formatMessage({ id: 'requireEmail' }))),
            emailConfirm: yup.string().email(displayErrorMsg(intl.formatMessage({ id: 'validEmailFormat' }))).max(128, getMaxErrStr(128)).required(displayErrorMsg(intl.formatMessage({ id: 'requireEmail' }))).oneOf([yup.ref('email'), null], displayErrorMsg(intl.formatMessage({ id: 'validSameEmail' }))),
            idNo: yup.string().required(getRequiredErrStr('number'))
                .matches(/^[aA-zZ0-9\s]+$/, { message: displayErrorMsg(`${selectedIdDocInputType}${intl.formatMessage({ id: 'noSpecialCharacter' })}`) })
                .matches(/^\S*$/, { message: displayErrorMsg(`${selectedIdDocInputType}${intl.formatMessage({ id: 'noSpace' })}`) })
                .test('checkIDCardFormat', displayErrorMsg(`${intl.formatMessage({ id: 'requiredValid' })}${selectedIdDocInputType==undefined?"":selectedIdDocInputType}${intl.formatMessage({ id: 'number' })}`), function (value) {
                    const idDocType = selectedIdDocType.type;
                    var pattern_HKIDv1 = /^[A-Z]{1}[0-9]{6}$/;
                    var pattern_HKIDv2 = /^[A-Z]{2}[0-9]{6}$/;
                    var pattern_passport = /^[A-Z]{1}[0-9]{8}$/;
                    var pattern_CHID = /^[0-9]{6}(20|19)[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9X]{1}/;
                    var pattern_otherCert = /^[A-Z]{1}[0-9]{5,}/;
                    if (value !== undefined) {
                        switch (idDocType) {
                            case "HKID":
                                if (value.match(pattern_HKIDv1)) {
                                    return true
                                } else if (value.match(pattern_HKIDv2)) {
                                    return true
                                } else {
                                    return false
                                }
                            case "passport":
                                if (value.match(pattern_passport)) {
                                    return true
                                } else {
                                    return false
                                }
                            case "CNID":
                                if (value.match(pattern_CHID)) {
                                    const subStr_year = value.substring(6, 10)
                                    const subStr_month = value.substring(10, 12)
                                    const subStr_date = value.substring(12, 14)

                                    const today = new Date()
                                    const inputDate = new Date(`${subStr_year}-${subStr_month}-${subStr_date}`)

                                    if (inputDate > today || inputDate === "Invalid Date" || inputDate.getFullYear().toString() !== subStr_year || (inputDate.getMonth() + 1).toString().padStart(2, "0") !== subStr_month || inputDate.getDate().toString().padStart(2, "0") !== subStr_date) {
                                        return false
                                    } else {
                                        return true
                                    }
                                } else {
                                    return false
                                }
                            case "otherCert":
                                if (value.match(pattern_otherCert)) {
                                    return true
                                } else {
                                    return false
                                }
                            default:
                                break;
                        }
                    }
                }),
            checkDigit: yup.string().max(1, getMaxErrStr(1)).required(displayErrorMsg(intl.formatMessage({ id: 'requiredNumberInQuote' }))),
            idDocType: yup.string().max(255, getMaxErrStr(255)).required(displayErrorMsg(intl.formatMessage({ id: 'requireIdDocType' }))),
            phoneCountryCode: yup.string().min(2, displayErrorMsg(intl.formatMessage({ id: 'requireAtLeast2Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))),
            // faxCountryCode: yup.string().min(3,'請輸入3位數字'),
            phone: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'requireAtLeast8Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireContactNumber' }))),
            // fax: yup.string().min(8,'請輸入8位數字'),
            captchaField: yup.string().max(5, getMaxErrStr(5)).required(displayErrorMsg(intl.formatMessage({ id: 'requireVerify' }))).min(5, displayErrorMsg(intl.formatMessage({ id: 'requireVerify' }))),//.oneOf([captcha], displayErrorMsg('請輸入有效驗證')),
        }),
    });

    const handleReset = (resetForm) => {
        resetForm();
        setSelectedAddress4("")
        setSelectedAddress5(ComboData.country[0])
        setCheckCountry(false)
        setSelectedIdDocType({})
        setSelectedIdDocInputType("");
        setFileList([])
        setFileListData([])
        onCaptchaChange()
        // setSelectedIdDocLabel("")
    };

    const handleCCPChange = (e) => {
        e.preventDefault();
    };

    const { values } = formik

    useEffect(() => {
        if (!props.step0GuardRef) return;
        props.step0GuardRef.current = async () => {
            const syncOk = computeStep0ValidSync(values);
            if (!syncOk) {
                setisValid(false);
                if (!isDistrictSelectionValid()) {
                    setDistrictErrStr(getRequiredErrStr("district"));
                    setCheckDistrict(true);
                    notifyActionError(intl.formatMessage({ id: 'require' }, { fieldname: intl.formatMessage({ id: 'district' }) }));
                }
                return false;
            }
            try {
                const taken = await checkEmailRegistered(values.email);
                setCheckEmail(taken);
                if (taken) {
                    setisValid(false);
                    notifyActionError(intl.formatMessage({ id: 'emailUsed' }));
                    return false;
                }
            } catch (error) {
                notifyActionError(intl.formatMessage({ id: 'connectionError' }));
                return false;
            }
            setisValid(true);
            return true;
        };
    }, [values, selectedAddress4, selectedAddress5, termsAndConAccept, fileList, checkUsername, checkEmail, checkIdDocNumber, selectedIdDocType]);

    useEffect(() => {
        checkDataField(values)
    }, [values])

    return (
        <FormikProvider value={formik}>
            <form onSubmit={handleSubmit(_onSubmit)}>
                {/* Input Form */}
                <FormGroup id={"inputForm"} sx={{ display: props.step === 0 ? "" : "none" }}>
                    <Grid container spacing={3}>
                        <Grid item xs={12} md={12}>
                            <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                <Button
                                    variant="outlined"
                                    type="reset"
                                    onClick={handleReset.bind(null, formik.resetForm)}
                                    sx={{
                                        height: '40px',
                                        borderColor: '#616161',
                                        color: '#424242',
                                        '&:hover': { borderColor: '#424242', backgroundColor: 'rgba(97,97,97,0.08)' },
                                    }}
                                >
                                    <Typography variant="pnspsFormHeader">
                                        <FormattedMessage id="reset" />
                                    </Typography>
                                </Button>
                                <div style={{ borderBottom: "3px solid #1A4399", width: "100%", margin_right: "15px" }}>
                                    <Typography display="inline" variant="h3" sx={{ color: '#1A4399' }}>
                                        <FormattedMessage id="becomeNewPersonalUser" />
                                    </Typography>
                                </div>
                                <Typography mt={0.25} variant="h6" sx={{ color: '#B00020' }}>
                                    <FormattedMessage id="requireString" />
                                </Typography>
                                <Typography mt={0.25} variant="h4" sx={{ color: 'primary.primary' }}>
                                    <FormattedMessage id="yourLoginInformation" />
                                </Typography>
                            </Stack>
                        </Grid>
                        <Grid item xs={12} md={12}>
                            <Grid container spacing={1}>
                                <Grid item xs={12} md={12} >
                                    <Stack spacing={1}>
                                        <InputLabel htmlFor="username-signup">
                                            <Typography variant="pnspsFormHeader">
                                                <FormattedMessage id="userLoginName" />
                                                <span style={{ color: '#B00020' }}>*</span>
                                                {/*<Button*/}
                                                {/*    variant="contained"*/}
                                                {/*    onClick={handleCheckUsername}*/}
                                                {/*    sx={{ ml: 2, height: "40px" }}>*/}
                                                {/*    <Typography variant="h6">檢查是否重覆</Typography>*/}
                                                {/*</Button> **/}
                                            </Typography>
                                        </InputLabel>
                                        <OutlinedInput
                                            id="username-signup"
                                            type="text"
                                            value={formik.values.username.trim()}
                                            name="username"
                                            onChange={(e) => {
                                                setCheckUsername(false)
                                                props.setUsername(e.target.value)
                                                formik.handleChange(e)
                                            }}
                                            placeholder={intl.formatMessage({ id: 'userLoginName' })}
                                            fullWidth
                                            autoFocus
                                            error={Boolean((formik.touched.username && formik.errors.username) || checkUsername)}
                                            onBlur={formik.handleBlur}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "userLoginName" }),
                                                "aria-describedby": 'helper-text-username-signup',
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        {formik.touched.username && formik.errors.username && (
                                            <FormHelperText error id="helper-text-username-signup">
                                                {formik.errors.username}
                                            </FormHelperText>
                                        )}
                                        {checkUsername && (
                                            <FormHelperText error id="helper-text-username-signup">
                                                <FormattedMessage id="usernameTaken" />
                                            </FormHelperText>
                                        )}
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={12}>
                                    <Grid container>
                                        <Grid item xs={12} md={6} >
                                            <Stack spacing={1} sx={{ mr: { md: 1 }, mb: 1 }}>
                                                <Stack direction="row" justifyContent="space-between">
                                                    <InputLabel htmlFor="password-signup">
                                                        <Typography variant="pnspsFormHeader">
                                                            <FormattedMessage id="userPassword" />
                                                            <span style={{ color: '#B00020' }}>*</span>
                                                        </Typography>
                                                    </InputLabel>
                                                </Stack>
                                                <OutlinedInput
                                                    fullWidth
                                                    error={Boolean(formik.touched.password && formik.errors.password)}
                                                    id="password-signup"
                                                    type={showPassword ? 'text' : 'password'}
                                                    value={formik.values.password.trim()}
                                                    name="password"
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                        changePassword(e.target.value);
                                                    }}
                                                    endAdornment={
                                                        <InputAdornment position="end">
                                                            <IconButton
                                                                aria-label={intl.formatMessage({
                                                                    id: showPassword ? "ariaHidePassword" : "ariaShowPassword"
                                                                })}
                                                                onClick={handleClickShowPassword}
                                                                onMouseDown={handleMouseDownPassword}
                                                                edge="end"
                                                                size="large"
                                                            >
                                                                {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                            </IconButton>
                                                        </InputAdornment>
                                                    }
                                                    placeholder={intl.formatMessage({ id: 'userPassword' })}
                                                    onBlur={formik.handleBlur}
                                                    inputProps={{
                                                        "aria-label": intl.formatMessage({ id: "userPassword" }),
                                                        "aria-describedby": 'helper-text-password-signup',
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                />
                                                {formik.touched.password && formik.errors.password && (
                                                    <FormHelperText error id="helper-text-password-signup">
                                                        {formik.errors.password}
                                                    </FormHelperText>
                                                )}
                                            </Stack>
                                            <FormControl fullWidth sx={{ mt: 2 }}>
                                                <Grid container spacing={2} alignItems="center">
                                                    <Grid item>
                                                        <Box sx={{ bgcolor: level?.color, width: 85, height: 8, borderRadius: '7px' }} />
                                                    </Grid>
                                                    <Grid item>
                                                        <Typography variant="subtitle1">
                                                            <FormattedMessage id={level ? level?.label : "pwWeak"} />
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </FormControl>
                                        </Grid>
                                        <Grid item xs={12} md={6} >
                                            <Stack spacing={1}>
                                                <InputLabel htmlFor="confirmPassword-signup">
                                                    <Typography variant="pnspsFormHeader">
                                                        <FormattedMessage id="confirmPassword" />
                                                        <span style={{ color: '#B00020' }}>*</span>
                                                    </Typography>
                                                </InputLabel>
                                                <OutlinedInput
                                                    id="confirmPassword-signup"
                                                    type={showConfirmPassword ? 'text' : 'password'}
                                                    value={formik.values.confirmPassword.trim()}
                                                    name="confirmPassword"
                                                    onBlur={formik.handleBlur}
                                                    onCut={handleCCPChange}
                                                    onCopy={handleCCPChange}
                                                    onPaste={handleCCPChange}
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                        // changePassword(e.target.value);
                                                    }}
                                                    inputProps={{
                                                        "aria-label": intl.formatMessage({ id: "confirmPassword" }),
                                                        "aria-describedby": 'helper-text-confirmPassword-signup',
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    endAdornment={
                                                        <InputAdornment position="end">
                                                            <IconButton
                                                                aria-label={intl.formatMessage({
                                                                    id: showConfirmPassword ? "ariaHidePassword" : "ariaShowPassword"
                                                                })}
                                                                onClick={handleClickShowConfirmPassword}
                                                                onMouseDown={handleMouseDownPassword}
                                                                edge="end"
                                                                size="large"
                                                            >
                                                                {showConfirmPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                            </IconButton>
                                                        </InputAdornment>
                                                    }
                                                    placeholder={intl.formatMessage({ id: 'confirmPassword' })}
                                                    fullWidth
                                                    error={Boolean(formik.touched.confirmPassword && formik.errors.confirmPassword)}
                                                />
                                                {formik.touched.confirmPassword && formik.errors.confirmPassword && (
                                                    <FormHelperText error id="helper-text-confirmPassword-signup">
                                                        {formik.errors.confirmPassword}
                                                    </FormHelperText>
                                                )}
                                            </Stack>
                                            <Grid container spacing={2} alignItems="center">
                                                <Grid item sx={{ mt: 1 }}>
                                                    <Typography variant="subtitle1">
                                                        •<FormattedMessage id="pwRemark1" /><br />
                                                        •<FormattedMessage id="pwRemark2" /><br />
                                                        •<FormattedMessage id="pwRemark3" /><br />
                                                        •<FormattedMessage id="pwRemark4" /><br />
                                                        •<FormattedMessage id="pwRemark5"/><br />
                                                    </Typography>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} mt={1} mb={1}>
                                    <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="yourPersonalInformation" />
                                        </Typography>
                                        {/* <Typography component={Link} to="/login" variant="body1" sx={{ textDecoration: 'none' }} color="primary">
                                            Already have an account?
                                        </Typography> */}
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={12} >
                                    <Grid container sx={{ mb: 1 }}>
                                        <Stack spacing={1}>
                                            <InputLabel htmlFor="idDocType-signup">
                                                <Typography variant="pnspsFormHeader">
                                                    <FormattedMessage id="userIdDoc" />
                                                    <span style={{ color: '#B00020' }}>*</span>
                                                </Typography>
                                            </InputLabel>
                                            {/* {formik.touched.enName && formik.errors.enName && (
                                                <FormHelperText error id="helper-text-enName-signup">
                                                {formik.errors.enName}
                                                </FormHelperText>
                                            )} */}
                                        </Stack>
                                    </Grid>

                                    <Grid container>
                                        <Grid item xs={12} md={6} >
                                            <Stack spacing={1} sx={{ mr: { md: 1 } }}>
                                                <Autocomplete
                                                    disablePortal
                                                    id="idDocType"
                                                    label={intl.formatMessage({ id: "idDocType" })}
                                                    //value={selectedIdDocType}
                                                    size="small"
                                                    options={idDocTypeComboList}
                                                    onBlur={formik.handleBlur}
                                                    filterOptions={(options) => options}
                                                    inputValue={selectedIdDocInputType}
                                                    getOptionLabel={(option) => option.label ? intl.formatMessage({ id: option.label }) : ""}
                                                    onChange={(event, newValue) => {
                                                        if (newValue != null) {
                                                            setSelectedIdDocInputType(intl.formatMessage({ id: newValue.label }));
                                                            setSelectedIdDocType(newValue);
                                                            if (newValue.type !== "HKID") {
                                                                formik.setFieldValue("checkDigit", "")
                                                            }
                                                        } else {
                                                            setSelectedIdDocInputType("");
                                                            setSelectedIdDocType({});
                                                        }
                                                    }}
                                                    sx={{
                                                        '& .MuiInputBase-root': { alignItems: 'center' },
                                                        '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                                        '& .MuiOutlinedInput-root': { height: 40 }
                                                    }}
                                                    renderInput={(params) => <TextField
                                                        {...params}
                                                        error={formik.touched.idDocType && (selectedIdDocType === null || selectedIdDocType?.type == null)}
                                                        placeholder={intl.formatMessage({ id: 'idDocType' })}
                                                    />}
                                                    clearText={intl.formatMessage({ id: "muiClear" })}
                                                    closeText={intl.formatMessage({ id: "muiClose" })}
                                                    openText={intl.formatMessage({ id: "muiOpen" })}
                                                    noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                                                />
                                                {formik.touched.idDocType && (
                                                    selectedIdDocType === null || selectedIdDocType?.type == null ?
                                                        <FormHelperText error id="helper-text-idDocType-signup" sx={{ fontSize: 16, fontWeight: 'bold', }}>
                                                            <FormattedMessage id="requireIdDocType" />
                                                        </FormHelperText> : ''
                                                )}
                                            </Stack>
                                        </Grid>
                                        {selectedIdDocType.type === "HKID" ?
                                            <>
                                                <Grid item xs={9} md={5}>
                                                    <Stack spacing={1} sx={{ mr: { md: 1 } }}>
                                                        <OutlinedInput
                                                            id="idNo-hkid-login"
                                                            type="text"
                                                            name="idNo"
                                                            value={formik.values.idNo}
                                                            onChange={async (e) => {
                                                                const ele = document.getElementById('idNo-hkid-login')
                                                                const startPos = ele.selectionStart
                                                                if (e.type === "change") {
                                                                    if (!(e.target.value.match(/\s/g))) {
                                                                        const newValue = await e.target.value.toUpperCase()
                                                                        await formik.setFieldValue("idNo", newValue)
                                                                        ele.setSelectionRange(startPos, startPos)
                                                                    } else {
                                                                        await formik.setFieldValue("idNo", formik.values.idNo)
                                                                        ele.setSelectionRange(startPos - 1, startPos - 1)
                                                                    }
                                                                }
                                                            }}
                                                            placeholder={intl.formatMessage({ id: 'idDocNumber' })}
                                                            fullWidth
                                                            sx={{ mr: 1 }}
                                                            error={Boolean(formik.touched.idNo && formik.errors.idNo || checkIdDocNumber)}
                                                            onBlur={formik.handleBlur}
                                                            inputProps={{
                                                                "aria-label": intl.formatMessage({ id: "idDocNumber" }),
                                                                "aria-describedby": 'helper-text-idNo-signup',
                                                                maxLength: selectedIdDocType.type === 'HKID' ? 8 : 18,
                                                                onKeyDown: (e) => {
                                                                    // console.log(e)
                                                                    if (e.key === 'Enter') {
                                                                        e.preventDefault();
                                                                    }
                                                                },
                                                            }}
                                                        />
                                                        {formik.touched.idNo && formik.errors.idNo && (
                                                            <FormHelperText error id="helper-text-idNo-signup">
                                                                {formik.errors.idNo}
                                                            </FormHelperText>
                                                        )}
                                                        {formik.touched.checkDigit && formik.errors.checkDigit && (
                                                            <FormHelperText error id="helper-text-checkDigit-signup">
                                                                {formik.errors.checkDigit}
                                                            </FormHelperText>
                                                        )}
                                                        {checkIdDocNumber && (
                                                            <FormHelperText error id="helper-text-idNo-signup">
                                                                <FormattedMessage id="idNoTaken" />
                                                            </FormHelperText>
                                                        )}
                                                        {checkHKIdDocWithCheckDigit && (
                                                            <FormHelperText error id="helper-text-idNo-checkdigit-signup">
                                                                <FormattedMessage id="requiredNumberInQuote" />
                                                            </FormHelperText>
                                                        )}
                                                    </Stack>
                                                </Grid>
                                                <Grid item xs={3} md={1}>
                                                    <Stack spacing={1}>
                                                        <OutlinedInput
                                                            id="checkDigit-login"
                                                            type="text"
                                                            value={formik.values.checkDigit.trim()}
                                                            name="checkDigit"
                                                            onChange={formik.handleChange}
                                                            //placeholder="( )"
                                                            // sx={{height:"53px"}}
                                                            startAdornment={<InputAdornment position="start">(</InputAdornment>}
                                                            endAdornment={<InputAdornment position="end">)</InputAdornment>}
                                                            sx={{
                                                                '& .MuiOutlinedInput-input': {
                                                                    padding: '5px 2px 5px 2px', // Set the desired padding inline
                                                                },
                                                            }}
                                                            inputProps={{
                                                                maxLength: 1,
                                                                onKeyDown: (e) => {
                                                                    if (e.key === 'Enter') {
                                                                        e.preventDefault();
                                                                    }
                                                                },
                                                            }}
                                                            fullWidth
                                                            error={Boolean(formik.touched.checkDigit && formik.errors.checkDigit || checkIdDocNumber)}
                                                            onBlur={formik.handleBlur}
                                                        />
                                                    </Stack>
                                                </Grid>
                                            </> :
                                            <Grid item xs={12} md={6}>
                                                <Stack spacing={1}>
                                                    <OutlinedInput
                                                        id="idNo-login"
                                                        type="text"
                                                        value={formik.values.idNo}
                                                        name="idNo"
                                                        onChange={async (e) => {
                                                            const ele = document.getElementById('idNo-login')
                                                            const startPos = ele.selectionStart
                                                            if (e.type === "change") {
                                                                if (!(e.target.value.match(/\s/g))) {
                                                                    const newValue = await e.target.value.toUpperCase()
                                                                    await formik.setFieldValue("idNo", newValue)
                                                                    ele.setSelectionRange(startPos, startPos)
                                                                } else {
                                                                    await formik.setFieldValue("idNo", formik.values.idNo)
                                                                    ele.setSelectionRange(startPos - 1, startPos - 1)
                                                                }
                                                            }
                                                        }}
                                                        placeholder={intl.formatMessage({ id: 'idDocNumber' })}
                                                        fullWidth
                                                        sx={{ mr: 1 }}
                                                        error={Boolean(formik.touched.idNo && formik.errors.idNo || checkIdDocNumber)}
                                                        onBlur={formik.handleBlur}
                                                        inputProps={{
                                                            "aria-label": intl.formatMessage({ id: "idDocNumber" }),
                                                            "aria-describedby": 'helper-text-idNo-signup',
                                                            maxLength: 18,
                                                            onKeyDown: (e) => {
                                                                if (e.key === 'Enter') {
                                                                    e.preventDefault();
                                                                }
                                                            },
                                                        }}
                                                    />
                                                    {formik.touched.idNo && formik.errors.idNo && (
                                                        <FormHelperText error id="helper-text-idNo-signup">
                                                            {formik.errors.idNo}
                                                        </FormHelperText>
                                                    )}
                                                    {checkIdDocNumber && (
                                                        <FormHelperText error id="helper-text-idNo-signup">
                                                            <FormattedMessage id="idNoTaken" />
                                                        </FormHelperText>
                                                    )}
                                                </Stack>
                                            </Grid>
                                        }
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} md={12}>
                                    <Typography variant="subtitle1">
                                        <FormattedMessage id="registerNameLabel" />
                                    </Typography>
                                </Grid>
                                <Grid item xs={12} md={6}>
                                    <Stack spacing={1}>
                                        <InputLabel htmlFor="enName-signup">
                                            <Typography variant="pnspsFormHeader">
                                                <FormattedMessage id="userEnglishName" />
                                                {selectedIdDocType.type === "CNID" ? "" : <span style={{ color: '#B00020' }}></span>}
                                            </Typography>
                                        </InputLabel>
                                        <OutlinedInput
                                            id="enName-signup"
                                            type="enName"
                                            value={formik.values.enName}
                                            name="enName"
                                            onChange={formik.handleChange}
                                            placeholder={intl.formatMessage({ id: 'sameAsYourIdDoc' })}
                                            fullWidth
                                            error={Boolean(formik.touched.enName && formik.errors.enName && selectedIdDocType.type !== "CNID")}
                                            onBlur={formik.handleBlur}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "userEnglishName" }),
                                                "aria-describedby": 'helper-text-enName-signup',
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        {formik.touched.enName && formik.errors.enName && selectedIdDocType.type !== "CNID" && (
                                            <FormHelperText error id="helper-text-enName-signup">
                                                {formik.errors.enName}
                                            </FormHelperText>
                                        )}
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={6}>
                                    <Stack spacing={1}>
                                        <InputLabel htmlFor="chName-signup">
                                            <Typography variant="pnspsFormHeader">
                                                <FormattedMessage id="userChineseName" />
                                                <span style={{ color: '#B00020' }}></span>
                                            </Typography>
                                        </InputLabel>
                                        <OutlinedInput
                                            fullWidth
                                            error={Boolean(formik.touched.chName && formik.errors.chName)}
                                            id="chName-signup"
                                            type="text"
                                            value={formik.values.chName.trim()}
                                            name="chName"
                                            onChange={formik.handleChange}
                                            placeholder={intl.formatMessage({ id: 'sameAsYourIdDoc' })}
                                            onBlur={formik.handleBlur}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "userChineseName" }),
                                                "aria-describedby": 'helper-text-chName-signup',
                                                maxLength: 6,
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        {formik.touched.chName && formik.errors.chName && (
                                            <FormHelperText error id="helper-text-chName-signup">
                                                {formik.errors.chName}
                                            </FormHelperText>
                                        )}
                                    </Stack>
                                </Grid>
                                <Grid item xs={12}>
                                    <Stack spacing={1}>
                                        <InputLabel htmlFor="address1-signup">
                                            <Typography variant="pnspsFormHeader">
                                                <FormattedMessage id="formAddress" />
                                                <span style={{ color: '#B00020' }}>*</span>
                                            </Typography>
                                        </InputLabel>
                                        <OutlinedInput
                                            fullWidth
                                            error={Boolean(formik.touched.address1 && formik.errors.address1)}
                                            id="address1-signup"
                                            value={formik.values.address1}
                                            name="address1"
                                            onChange={formik.handleChange}
                                            placeholder={intl.formatMessage({ id: 'addressLine1' })}
                                            onBlur={formik.handleBlur}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "addressLine1" }),
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        <OutlinedInput
                                            fullWidth
                                            error={Boolean(formik.touched.address2 && formik.errors.address2)}
                                            id="address2-signup"
                                            value={formik.values.address2}
                                            name="address2"
                                            onChange={formik.handleChange}
                                            onBlur={formik.handleBlur}
                                            placeholder={intl.formatMessage({ id: 'addressLine2' })}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "addressLine2" }),
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        <OutlinedInput
                                            fullWidth
                                            error={Boolean(formik.touched.address3 && formik.errors.address3)}
                                            id="address3-signup"
                                            value={formik.values.address3}
                                            name="address3"
                                            onChange={formik.handleChange}
                                            onBlur={formik.handleBlur}
                                            placeholder={intl.formatMessage({ id: 'addressLine3' })}
                                            inputProps={{
                                                "aria-label": intl.formatMessage({ id: "addressLine3" }),
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                        e.preventDefault();
                                                    }
                                                },
                                            }}
                                        />
                                        <Autocomplete
                                            disablePortal
                                            id="address4-combo"
                                            value={selectedAddress4}
                                            options={ComboData.district}
                                            disabled={checkCountry}
                                            // error={Boolean(districtErrStr != "")}
                                            // onBlur={formik.handleBlur}
                                            getOptionLabel={(option) => option.type ? intl.formatMessage({ id: option.type }) : ""}
                                            onChange={(event, newValue) => {
                                                setSelectedAddress4(newValue);
                                            }}
                                            sx={{
                                                '& .MuiInputBase-root': { alignItems: 'center' },
                                                '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                                '& .MuiOutlinedInput-root': { height: 40 }
                                            }}
                                            renderInput={(params) => <TextField error={checkDistrict} {...params} placeholder={intl.formatMessage({ id: 'region' })}
                                            />}
                                            clearText={intl.formatMessage({ id: "muiClear" })}
                                            closeText={intl.formatMessage({ id: "muiClose" })}
                                            openText={intl.formatMessage({ id: "muiOpen" })}
                                            noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                                        />
                                        <Autocomplete
                                            disablePortal
                                            id="address5-combo"
                                            value={selectedAddress5}
                                            options={ComboData.country}
                                            disabled= {true}
                                            getOptionLabel={(option) => option.type ? intl.formatMessage({ id: option.type }) : ""}
                                            onChange={(event, newValue) => {
                                                if (newValue !== null) {
                                                    setSelectedAddress5(newValue);
                                                    if (newValue.type === 'hongKong') {
                                                        setCheckCountry(false)
                                                        if(formik.values.phone==""){
                                                            formik.values.phoneCountryCode = "852";
                                                        }
                                                        if(formik.values.fax==""){
                                                            formik.values.faxCountryCode = "852";
                                                        }
                                                    } else {
                                                        if (newValue.type === 'mainland'){
                                                            if(formik.values.phone==""){
                                                                formik.values.phoneCountryCode = "86";
                                                            }
                                                            if(formik.values.fax==""){
                                                                formik.values.faxCountryCode = "86";
                                                            }
                                                        }else if(newValue.type === 'macau'){
                                                            if(formik.values.phone==""){
                                                                formik.values.phoneCountryCode = "853";
                                                            }
                                                            if(formik.values.fax==""){
                                                                formik.values.faxCountryCode = "853";
                                                            }
                                                        }

                                                        setSelectedAddress4("");
                                                        setCheckCountry(true)
                                                    }
                                                } else {
                                                    setSelectedAddress4("");
                                                    setCheckCountry(true)
                                                }
                                            }}
                                            sx={{
                                                '& .MuiInputBase-root': { alignItems: 'center' },
                                                '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                                '& .MuiOutlinedInput-root': { height: 40 }
                                            }}
                                            renderInput={(params) => <TextField {...params} placeholder={intl.formatMessage({ id: 'regionOrCountry' })} />}
                                            clearText={intl.formatMessage({ id: "muiClear" })}
                                            closeText={intl.formatMessage({ id: "muiClose" })}
                                            openText={intl.formatMessage({ id: "muiOpen" })}
                                            noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                                        />
                                        {formik.touched.address1 && formik.errors.address1 && (
                                            <FormHelperText error id="helper-text-address1-signup">
                                                {formik.errors.address1}
                                            </FormHelperText>
                                        )}
                                        {formik.touched.address2 && formik.errors.address2 && (
                                            <FormHelperText error id="helper-text-address2-signup">
                                                {formik.errors.address2}
                                            </FormHelperText>
                                        )}
                                        {formik.touched.address3 && formik.errors.address3 && (
                                            <FormHelperText error id="helper-text-address3-signup">
                                                {formik.errors.address3}
                                            </FormHelperText>
                                        )}
                                        {checkDistrict && (
                                            <FormHelperText error >
                                                {districtErrStr}
                                            </FormHelperText>
                                        )}
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} mt={1} mb={1}>
                                    <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="yourContact" />
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={12}>
                                    <Grid container>
                                        <Grid item xs={12} md={6}>
                                            <Stack spacing={1} sx={{ mr: { md: 1 }, mb: 1 }}>
                                                <InputLabel htmlFor="email-login">
                                                    <Typography variant="pnspsFormHeader">
                                                        <FormattedMessage id="userContactEmail" />
                                                        <span style={{ color: '#B00020' }}>*</span>
                                                    </Typography>
                                                </InputLabel>
                                                <OutlinedInput
                                                    fullWidth
                                                    error={Boolean((formik.touched.email && formik.errors.email) || checkEmail)}
                                                    id="email-login"
                                                    type="email"
                                                    value={formik.values.email.trim()}
                                                    name="email"
                                                    onChange={formik.handleChange}
                                                    placeholder={intl.formatMessage({ id: 'userContactEmail' })}
                                                    onBlur={formik.handleBlur}
                                                    inputProps={{
                                                        "aria-label": intl.formatMessage({ id: "userContactEmail" }),
                                                        "aria-describedby": "helper-text-email-signup",
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                />
                                                {formik.touched.email && formik.errors.email && (
                                                    <FormHelperText error id="helper-text-email-signup">
                                                        {formik.errors.email}
                                                    </FormHelperText>
                                                )}
                                                {checkEmail && (
                                                    <FormHelperText error id="helper-text-email-signup">
                                                        <FormattedMessage id="emailUsed" />
                                                    </FormHelperText>
                                                )}
                                            </Stack>
                                        </Grid>
                                        <Grid item xs={12} md={6}>
                                            <Stack spacing={1} >
                                                <InputLabel htmlFor="emailConfirm-login">
                                                    <Typography variant="pnspsFormHeader">
                                                        <FormattedMessage id="confirmEmail" />
                                                        <span style={{ color: '#B00020' }}>*</span>
                                                    </Typography>
                                                </InputLabel>
                                                <OutlinedInput
                                                    fullWidth
                                                    error={Boolean(formik.touched.emailConfirm && formik.errors.emailConfirm)}
                                                    id="emailConfirm-login"
                                                    type="email"
                                                    value={formik.values.emailConfirm.trim()}
                                                    name="emailConfirm"
                                                    // onBlur={formik.handleBlur}
                                                    onChange={formik.handleChange}
                                                    placeholder={intl.formatMessage({ id: 'confirmEmail' })}
                                                    onBlur={formik.handleBlur}
                                                    onCut={handleCCPChange}
                                                    onCopy={handleCCPChange}
                                                    onPaste={handleCCPChange}
                                                    inputProps={{
                                                        "aria-label": intl.formatMessage({ id: "confirmEmail" }),
                                                        "aria-describedby": "helper-text-emailConfirm-signup",
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                />
                                                {formik.touched.emailConfirm && formik.errors.emailConfirm && (
                                                    <FormHelperText error id="helper-text-emailConfirm-signup">
                                                        {formik.errors.emailConfirm}
                                                    </FormHelperText>
                                                )}
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} md={12}>
                                    <Grid container>
                                        <Grid item xs={12} md={6}>
                                            <Grid container>
                                                <Grid item xs={12} md={12}>
                                                    <Stack direction="column" spacing={1} sx={{ mr: { md: 1 }, mb: 1 }}>
                                                        <InputLabel htmlFor="phone-signup">
                                                            <Typography variant="pnspsFormHeader">
                                                                <FormattedMessage id="userContactNumber" />
                                                                <span style={{ color: '#B00020' }}>*</span>
                                                            </Typography>
                                                        </InputLabel>
                                                        <Stack direction="row">
                                                            <OutlinedInput
                                                                id="phoneCountryCode-signup"
                                                                type="phoneCountryCode"
                                                                value={formik.values.phoneCountryCode.trim()}
                                                                name="phoneCountryCode"
                                                                // onBlur={formik.handleBlur}
                                                                // onChange={formik.handleChange}
                                                                onChange={(event) => {
                                                                    const value = event.target.value;
                                                                    if (value.match(/[^0-9]/)) {
                                                                        return event.preventDefault();
                                                                    }
                                                                    formik.setFieldValue("phoneCountryCode", value);
                                                                }}
                                                                placeholder={intl.formatMessage({ id: 'dialingCode' })}
                                                                error={Boolean(formik.touched.phone && formik.errors.phone)}
                                                                onBlur={formik.handleBlur}
                                                                endAdornment={<InputAdornment position="end">-</InputAdornment>}
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "dialingCode" }),
                                                                    maxLength: 3,
                                                                    onKeyDown: (e) => {
                                                                        if (e.key === 'Enter') {
                                                                            e.preventDefault();
                                                                        }
                                                                    },
                                                                }}
                                                                sx={{ width: '33%', mr: 1 }}
                                                            />
                                                            <OutlinedInput
                                                                id="phone-signup"
                                                                type="phone"
                                                                value={formik.values.phone.trim()}
                                                                name="phone"
                                                                // onBlur={formik.handleBlur}
                                                                // onChange={formik.handleChange}
                                                                onChange={(event) => {
                                                                    const value = event.target.value;
                                                                    if (value.match(/[^0-9]/)) {
                                                                        return event.preventDefault();
                                                                    }
                                                                    formik.setFieldValue("phone", value);
                                                                }}
                                                                placeholder={intl.formatMessage({ id: 'userContactNumber' })}
                                                                error={Boolean(formik.touched.phone && formik.errors.phone)}
                                                                onBlur={formik.handleBlur}
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "userContactNumber" }),
                                                                    "aria-describedby": 'helper-text-phone-signup',
                                                                    maxLength: 11,
                                                                    onKeyDown: (e) => {
                                                                        if (e.key === 'Enter') {
                                                                            e.preventDefault();
                                                                        }
                                                                    },
                                                                }}
                                                                sx={{ width: '66%' }}
                                                            />
                                                        </Stack>
                                                        {formik.touched.phone && formik.errors.phone && (
                                                            <FormHelperText error id="helper-text-phone-signup">
                                                                {formik.errors.phone}
                                                            </FormHelperText>
                                                        )}
                                                    </Stack>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                        <Grid item xs={12} md={6}>
                                            <Grid container>
                                                <Grid item xs={12} md={12}>
                                                    <Stack spacing={1} direction="column">
                                                        <InputLabel htmlFor="fax-signup">
                                                            <Typography variant="pnspsFormHeader">
                                                                <FormattedMessage id="userFaxNumber" />
                                                            </Typography>
                                                        </InputLabel>
                                                        <Stack direction="row">
                                                            <OutlinedInput
                                                                error={Boolean(formik.touched.fax && formik.errors.fax)}
                                                                id="faxCountryCode-signup"
                                                                type="faxCountryCode"
                                                                value={formik.values.faxCountryCode.trim()}
                                                                name="faxCountryCode"
                                                                // onChange={formik.handleChange}
                                                                onChange={(event) => {
                                                                    const value = event.target.value;
                                                                    if (value.match(/[^0-9]/)) {
                                                                        return event.preventDefault();
                                                                    }
                                                                    formik.setFieldValue("faxCountryCode", value);
                                                                }}
                                                                placeholder={intl.formatMessage({ id: 'dialingCode' })}
                                                                onBlur={formik.handleBlur}
                                                                endAdornment={<InputAdornment position="end">-</InputAdornment>}
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "faxCountryCode" }),
                                                                    maxLength: 3,
                                                                    onKeyDown: (e) => {
                                                                        if (e.key === 'Enter') {
                                                                            e.preventDefault();
                                                                        }
                                                                    },
                                                                }}
                                                                sx={{ width: '33%', mr: 1 }}
                                                            />
                                                            <OutlinedInput
                                                                id="fax-signup"
                                                                type="fax"
                                                                value={formik.values.fax.trim()}
                                                                name="fax"
                                                                onBlur={formik.handleBlur}
                                                                // onChange={formik.handleChange}
                                                                onChange={(event) => {
                                                                    const value = event.target.value;
                                                                    if (value.match(/[^0-9]/)) {
                                                                        return event.preventDefault();
                                                                    }
                                                                    formik.setFieldValue("fax", value);
                                                                }}
                                                                placeholder={intl.formatMessage({ id: 'userFaxNumber' })}
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "userFaxNumber" }),
                                                                    maxLength: 8,
                                                                    onKeyDown: (e) => {
                                                                        if (e.key === 'Enter') {
                                                                            e.preventDefault();
                                                                        }
                                                                    },
                                                                }}
                                                                sx={{ width: '66%' }}
                                                            />
                                                        </Stack>
                                                    </Stack>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12} md={12} mt={1} mb={1}>
                                    <Grid container>
                                        <Grid item xs={12} md={12}>
                                            <Stack spacing={1} direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                                <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                                    <FormattedMessage id="userIdDoc" />
                                                    <span style={{ color: '#B00020' }}>*</span></Typography>
                                                <Typography display="inline" variant="subtitle1" sx={{ color: 'primary.primary' }}>
                                                    <FormattedMessage id="pleaseUploadIdDoc" />
                                                </Typography>
                                                <Typography display="inline" variant="subtitle1" sx={{ color: 'primary.primary' }}>
                                                    <FormattedMessage id="pleaseUploadIdDocSubTitle" />
                                                </Typography>
                                                <Stack mt={1} direction="row" justifyContent="flex-start" alignItems="center" spacing={2}>
                                                    <ThemeProvider theme={PNSPS_LONG_BUTTON_THEME}>
                                                        <Button
                                                            variant="contained"
                                                            sx={{ height: '40px' }}
                                                            type="button"
                                                            onClick={() => {
                                                                if (fileInputRef.current) {
                                                                    fileInputRef.current.click();
                                                                }
                                                            }}
                                                            onKeyDown={(event) => {
                                                                if (event.key === 'Enter' || event.key === ' ') {
                                                                    event.preventDefault();
                                                                    if (fileInputRef.current) {
                                                                        fileInputRef.current.click();
                                                                    }
                                                                }
                                                            }}
                                                        >
                                                            <FormattedMessage id="uploadIdDoc" />
                                                        </Button>
                                                        <input
                                                            accept="image/png, .jpg, .bmp, .pdf"
                                                            //className={classes.input}
                                                            id="contained-button-file"
                                                            multiple
                                                            type="file"
                                                            onChange={handleFileUpload}
                                                            ref={fileInputRef}
                                                            style={{ display: 'none' }}
                                                        />
                                                    </ThemeProvider>
                                                    {/*<Typography xs={12} sm={9} md={3} display="inline" variant="subtitle1" sx={{ color: 'primary.primary' }}>如: 香港身份證; 護照; 中國內地身份證等</Typography>*/}
                                                </Stack>
                                                {fileList != null && props.step === 0 ?
                                                    <UploadFileTable key="uploadTable" recordList={fileListData} setUpdateRows={setUpdateRows} /> : null}
                                                {/* <Stack mt={1} direction="row" justifyContent="flex-start" alignItems="center" spacing={2}>
                                                    <Button variant="contained" type="submit" sx={{ fontSize: 12,height:'25px'}}>Submit</Button>
                                                    <Button disabled={!formik.isValid} variant="contained" type="submit" sx={{ fontSize: 12,height:'25px'}}>Submit</Button>
                                                </Stack> */}
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={12}>
                                <Grid container>
                                    <Grid item xs={12} md={12}>
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="termsAndCondition" />
                                            <span style={{ color: '#B00020' }}>*</span>
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12}>
                                        <Grid container>
                                            <Grid item xs={12} md={12}>
                                                <Typography variant="h6" height="100%" sx={{ textAlign: "left", /*overflow: "scroll",*/ borderRadius: "inherit", borderStyle: "solid", borderWidth: "1px", borderColor: "#0C489E" }}>
                                                <div style={{padding: 12}} dangerouslySetInnerHTML={{__html: intl.formatMessage({id: "termsAndCon"})}} />
                                                </Typography>
                                            </Grid>
                                        </Grid>
                                        <Grid item xs={12} s={12} md={12} lg={12}>
                                            <Grid container>
                                                <Grid item xs={6} sm={6} md={11} lg={11}>
                                                    <Grid container>
                                                        <Grid item sx={{ display: 'flex', alignItems: 'center' }}>
                                                            <Checkbox
                                                                checked={termsAndConAccept}
                                                                onChange={handleCheckBoxChange}
                                                                name="termsAndConAccept"
                                                                color="primary"
                                                                size="small"
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "iConfirm" })
                                                                }}
                                                            />
                                                            <Typography variant="pnspsFormHeader">
                                                                <FormattedMessage id="iConfirm" />
                                                            </Typography>
                                                        </Grid>
                                                    </Grid>
                                                </Grid>
                                                <Grid item xs={6} s={6} md={3} lg={3}>
                                                    <Grid container style={{ display: "none" }}>
                                                        <Grid item sx={{ display: 'flex', alignItems: 'center' }}>
                                                            <Checkbox
                                                                checked={termsAndConNotAccept}
                                                                onChange={handleCheckBoxChange}
                                                                name="termsAndConNotAccept"
                                                                color="primary"
                                                                size="small"
                                                                inputProps={{
                                                                    "aria-label": intl.formatMessage({ id: "rejectTerms" })
                                                                }}
                                                            />
                                                            <Typography variant="pnspsFormHeader">
                                                                <FormattedMessage id="rejectTerms" />
                                                            </Typography>
                                                        </Grid>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} lg={12}>
                                <Grid container>
                                    <Stack direction="column">
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="verify" />
                                            <span style={{ color: '#B00020' }}>*</span>
                                        </Typography>
                                        <Stack spacing={1} direction="row">
                                            <Grid item xs={5} lg={5} style={{ "border": "1px solid black" }}>
                                                <img src={captchaImg} alt="" />
                                            </Grid>
                                            <Grid item xs={1} lg={1} style={{ "border": "0px solid black" }}>
                                                <IconButton aria-label={intl.formatMessage({ id: 'ariaRefreshCaptcha' })} size="large" onClick={() => { onCaptchaChange() }}>
                                                    <LoopIcon fontSize="inherit" />
                                                </IconButton>
                                            </Grid>
                                            <Grid item xs={6} lg={6}>
                                                <OutlinedInput
                                                    fullWidth
                                                    id="captchaField"
                                                    type="text"
                                                    value={formik.values.captchaField.trim()}
                                                    onBlur={formik.handleBlur}
                                                    error={Boolean(formik.touched.captchaField && formik.errors.captchaField)}
                                                    name="captchaField"
                                                    onChange={(event) => {
                                                        const value = event.target.value;
                                                        props.setCheckCode(event.target.value);
                                                        setCheckCode(event.target.value);
                                                        formik.setFieldValue("captchaField", value);
                                                    }}
                                                    sx={{ width: '75%' }}
                                                    inputProps={{
                                                        "aria-label": intl.formatMessage({ id: "verify" }),
                                                        "aria-describedby": 'helper-text-captcha-signup'
                                                    }}
                                                />
                                            </Grid>
                                        </Stack>
                                        {formik.touched.captchaField && formik.errors.captchaField && (
                                            <FormHelperText error id="helper-text-captcha-signup">
                                                {formik.errors.captchaField}
                                            </FormHelperText>
                                        )}
                                        <Stack spacing={1} direction="row" sx={{ mt: 0.25 }}>
                                            <Button
                                                variant="contained"
                                                onClick={playCaptchaAudio}
                                                aria-label={intl.formatMessage({ id: "captchaPlayAudio" })}
                                                sx={{
                                                    backgroundColor: '#0C489E',
                                                    color: '#FFFFFF',
                                                    '&:hover': { backgroundColor: '#093A7A' },
                                                }}
                                            >
                                                <FormattedMessage id="captchaPlayAudio" />
                                            </Button>
                                        </Stack>
                                    </Stack>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </FormGroup>
                {/* Preview Form */}
                <FormGroup id={"previewForm"} sx={{ display: props.step === 1 ? "" : "none" }}>
                    <Grid container spacing={3}>
                        <Grid item xs={12} md={12}>
                            <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                <div style={{ borderBottom: "3px solid #1A4399", width: "100%", margin_right: "15px" }}>
                                    <Typography display="inline" variant="h3" sx={{ color: '#1A4399' }}>
                                        <FormattedMessage id="becomeNewPersonalUser" />
                                    </Typography>
                                </div>
                                {/* <Typography mt={0.25} variant="h6" sx={{ fontSize: 12,color: '#B00020'}}>註有*的項目必須輸入資料</Typography> */}
                                <Typography mt={0.25} variant="h4" sx={{ color: 'primary.primary' }}>
                                    <FormattedMessage id="yourLoginInformation" />
                                </Typography>
                                {/* <Typography component={Link} to="/login" variant="body1" sx={{ textDecoration: 'none' }} color="primary">
                                Already have an account?
                                </Typography> */}
                            </Stack>
                        </Grid>
                        <Grid item xs={12} md={12}>
                            <Grid container spacing={2}>
                                <Grid item xs={12} >
                                    <Stack spacing={2} direction="row">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userLoginName" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="preview-username-login">
                                            {formik.values.username}
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} mt={1} mb={1}>
                                    <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="yourPersonalInformation" />
                                        </Typography>
                                        {/* <Typography component={Link} to="/login" variant="body1" sx={{ textDecoration: 'none' }} color="primary">
                                        Already have an account?
                                    </Typography> */}
                                    </Stack>
                                </Grid>
                                {/* <Grid item xs={12} md={12} >
                                    <Stack spacing={1}>
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userIdDoc" />
                                        </Typography>
                                    </Stack>
                                </Grid> */}

                                <Grid item xs={12} md={6} >
                                    <Stack spacing={1} direction="row" >
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="idDocType" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" name="preview-idDocType">
                                            {selectedIdDocType?.label? intl.formatMessage({ id: selectedIdDocType.label}): " "}

                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={6}>
                                    <Stack direction="row" >
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]} sx={{mr:1}}>
                                            <FormattedMessage id="idDocNumber" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="idNo-f4-login">
                                            {formik.values.idNo.slice(0, 4)}
                                        </Typography>
                                
                                        <Typography variant="pnspsFormHeader" id="idNo-exf4-login" 
                                            type={showId ? "text" : "password"}
                                        >
                                            {showId ?formik.values.idNo.slice(4):"****"}{showId ?selectedIdDocType.type == "HKID" ? '(' + formik.values.checkDigit + ')' : null:null}
                                        </Typography>
                                    
                                        <IconButton
                                            aria-label={intl.formatMessage({ id: 'ariaToggleIdVisibility' })}
                                            onClick={handleClickShowId}
                                            onMouseDown={handleMouseDownId}
                                            edge="end"
                                            size="medium"
                                        >
                                            {showId ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                        </IconButton>                                                               
                                    </Stack>
                                </Grid>

                                <Grid item xs={12} md={6}>
                                    <Stack spacing={1} direction="row">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userEnglishName" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="preview-enName-signup">
                                            {formik.values.enName}
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={6}>
                                    <Stack spacing={1} direction="row">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userChineseName" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="preview-chName-signup">
                                            {formik.values.chName}
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12}>
                                    <Stack spacing={1} direction="column">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="formAddress" />:
                                        </Typography>
                                        <Stack spacing={1} direction="column">
                                            <Typography variant="pnspsFormHeader" id="preview-address1-signup">
                                                {formik.values.address1}
                                            </Typography>
                                            {formik.values.address2 != null ?
                                                <Typography variant="pnspsFormHeader" id="preview-address2-signup">
                                                    {formik.values.address2}
                                                </Typography>
                                                : null}
                                            {formik.values.address3 != null ?
                                                <Typography variant="pnspsFormHeader" id="preview-address3-signup">
                                                    {formik.values.address3}
                                                </Typography>
                                                : null}
                                            {selectedAddress5.type === "hongKong" ?
                                                <Stack direction="column">
                                                    {/* <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]} id="preview-address4-signup">
                                                        <FormattedMessage id="region" />:
                                                    </Typography> */}
                                                    <Typography variant="pnspsFormHeader">
                                                        {!selectedAddress4 ? "" : intl.formatMessage({ id: selectedAddress4.type })}
                                                    </Typography>
                                                </Stack>
                                                : null}
                                            <Stack direction="column">
                                                {/* <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]} id="preview-address5-signup">
                                                    <FormattedMessage id="regionOrCountry" />:
                                                </Typography> */}
                                                <Typography variant="pnspsFormHeader">
                                                    {intl.formatMessage({ id: selectedAddress5.type })}
                                                </Typography>
                                            </Stack>
                                        </Stack>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} mt={1} mb={1}>
                                    <Stack direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                        <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                            <FormattedMessage id="yourContact" />
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={12}>
                                    <Stack spacing={1} direction="row">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userContactEmail" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="preview-email-signup">
                                            {formik.values.email}
                                        </Typography>
                                    </Stack>
                                </Grid>
                                <Grid item xs={12} md={6}>
                                    <Stack spacing={1} direction="row">
                                        <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                            <FormattedMessage id="userContactNumber" />:
                                        </Typography>
                                        <Typography variant="pnspsFormHeader" id="preview-phone-signup">
                                            +{formik.values.phoneCountryCode} {formik.values.phone}
                                        </Typography>
                                    </Stack>
                                </Grid>
                                {formik.values.faxCountryCode != "" && formik.values.fax != "" ?
                                    <Grid item xs={12} md={6}>
                                        <Stack spacing={1} direction="row">
                                            <Typography variant="pnspsFormHeader" color={theme.palette.grey[600]}>
                                                <FormattedMessage id="userFaxNumber" />:
                                            </Typography>
                                            <Typography variant="pnspsFormHeader" id="preview-fax-signup">
                                                +{formik.values.faxCountryCode} {formik.values.fax}
                                            </Typography>
                                        </Stack>
                                    </Grid>
                                    : null}
                                <Grid item xs={12} md={12} mt={1} mb={1}>
                                    <Grid container>
                                        <Grid item xs={12} md={12}>
                                            <Stack spacing={1} direction="column" justifyContent="space-between" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                                                <Typography display="inline" variant="h4" sx={{ color: 'primary.primary' }}>
                                                    <FormattedMessage id="userIdDoc" />
                                                </Typography>
                                                {fileList != null && props.step === 1 ?
                                                    <PreviewUploadFileTable key="previewTable" recordList={fileListData} /> : null}
                                            </Stack>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </FormGroup>
                {/* Submit page */}
                <FormGroup id={"submitForm"} sx={{ display: props.step === 2 ? "" : "none" }}>
                    <Grid container spacing={3}>
                        {isLoading ?
                            <LoadingComponent /> :
                            <Grid item xs={12}>
                                {checkUpload ?
                                    // SUCCESS page
                                    <Stack mt={1} direction="column" justifyContent="flex-start" alignItems="center" spacing={2}>
                                        <CheckCircleOutlineIcon color="success" sx={{ width: "200px", height: "200px" }} />
                                        <Typography display="inline" variant="h4">
                                            <FormattedMessage id="registerSubmitted" />
                                        </Typography>
                                        <Typography display="inline" variant="h4">
                                            <FormattedMessage id="emailSent" />
                                        </Typography>
                                        <Button variant="outlined" component={Link} to="/login" ><Typography variant="pnspsFormHeader">
                                            <FormattedMessage id="backToLogin" />
                                        </Typography></Button>
                                    </Stack>
                                    :
                                    // ERROR page
                                    <Stack mt={1} direction="column" justifyContent="flex-start" alignItems="center" spacing={2}>
                                        {/* <Button disabled={true} hidden={true} variant="contained" type="submit" sx={{ fontSize: 12,height:'25px'}}>Submit</Button> */}
                                        <CancelOutlinedIcon color="error" sx={{ width: "200px", height: "200px" }} />
                                        <Typography display="inline" variant="h4">
                                            <FormattedMessage id="registerFail" />
                                        </Typography>
                                        <Button color="error" variant="outlined" component={Link} to="/login" ><Typography variant="pnspsFormHeader">
                                            <FormattedMessage id="backToLogin" />
                                        </Typography></Button>
                                    </Stack>
                                }
                            </Grid>
                        }
                    </Grid>
                </FormGroup>
            </form>
        </FormikProvider>
    );
}

export default CustomFormWizard;