import React, {useCallback, useEffect, useState} from "react";
import Form from "react-bootstrap/Form";
import * as EgovNet from "api/egovFetch";

function CheckBox({name, grpCd, selectedValue}){

    const [checkBox, setCheckBox] = useState();

    useEffect(() => {
        getCodeItemList()
    }, []);

    useEffect(() => {
        if(checkBox&&selectedValue){
            const itemCdAry = selectedValue.split(',');
            itemCdAry.forEach(function(itemCd){
                document.querySelector(`#chkBox_${itemCd}`).checked = true;
            })
        }
    }, [checkBox]);

    function getCodeItemList() {
        EgovNet.requestFetch(
            '/commonCode/code-item?grpCd='+grpCd,
            {
                method: "GET"
            },
            (resp) => {
                let checkBoxTag = [];
                resp.result.codeList.forEach(function (item, index) {
                    checkBoxTag.push(
                        <Form.Check inline
                                    label={item.itemNm}
                                    id={`chkBox_${item.itemCd}`}
                                    key={`chkBox_${item.itemCd}_${index}`}
                                    name={name}
                                    value={item.itemCd}
                                    />
                    );
                });
                setCheckBox(checkBoxTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    }

    return (
        <div id={`${grpCd}_checkBoxDiv`} key={`checkBox_${grpCd}`}>
            {checkBox}
        </div>
    )
}

export default CheckBox;