import React, {useState, useImperativeHandle, forwardRef} from "react";
import * as EgovNet from "api/egovFetch";
import {Container} from "react-bootstrap";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Form from 'react-bootstrap/Form'
import Button from "react-bootstrap/Button";
import CODE from "../../../../constants/code";

function ChildCodeDiv({}, ref){

    const [codeItemRow, setCodeItemRow] = useState();
    const [grpCd, setGrpCd] = useState();

    useImperativeHandle(ref, ()=>({
        getCodeItemList
    }))

    async function getCodeItemList(parentCd){
        setCodeItemRow([]);
        setGrpCd(parentCd)
        EgovNet.requestFetch(
            '/admin/config/code-item?grpCd='+parentCd,
            {
                method: "GET"
            },
            (resp) => {
                const codeItemList = resp.result.codeItemList;
                const itemTag = [];
                codeItemList.forEach(function (item, index){
                    itemTag.push(
                        <Row className={"py-2 border-bottom"}>
                            <Col xs={3}><Form.Control type={"text"} size={"sm"} className={"itemCd"} defaultValue={item.itemCd}/></Col>
                            <Col xs={4}><Form.Control type={"text"} size={"sm"} className={"itemNm"} defaultValue={item.itemNm}/></Col>
                            <Col xs={2}><Form.Control type={"text"} size={"sm"} className={"grpOrder"} defaultValue={item.grpOrder}/></Col>
                            <Col xs={1}><Button variant={"danger"} size={"sm"} onClick={(e)=>{modifyCodeItem(e, "delete")}}>삭제</Button></Col>
                            <Col xs={1}><Button variant={"primary"} size={"sm"} onClick={(e)=>{modifyCodeItem(e, "modify")}}>수정</Button></Col>
                        </Row>
                    )
                })
                setCodeItemRow(itemTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    }

    function addCodeItem(){
        const itemCd =  document.querySelector("#itemCd");
        const itemNm =  document.querySelector("#itemNm");
        const grpOrder =  document.querySelector("#grpOrder");
        if(!itemCd.value || !itemNm.value){
            alert("코드와 코드명을 입력해주세요.")
        }else{
            EgovNet.requestFetch(
                '/admin/config/code-item',
                {
                    method: "POST",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify({
                        itemCd: itemCd.value,
                        grpCd: document.querySelector("#codeItemDiv").querySelector("#grpCd").value,
                        itemNm: itemNm.value,
                        grpOrder: grpOrder.value
                    })
                },
                (resp) => {
                    switch (resp.resultCode) {
                        case Number(CODE.RCV_SUCCESS):
                            itemCd.value = "";
                            itemNm.value = "";
                            grpOrder.value = "";
                            getCodeItemList(grpCd);
                            break;
                        case Number(CODE.RCV_ERROR_SAVE)||Number(CODE.RCV_ERROR_AUTH):
                            alert(resp.resultMessage);
                            break;
                    }
                },
                function (resp) {
                    console.log("err response : ", resp);
                }
            );
        }

    }

    function modifyCodeItem(e, action){
        const row = e.target.parentElement.parentElement;
        const selectedGrpCd = document.querySelector("#codeItemDiv").querySelector("#grpCd").value;
        const codeItem = {
            grpCd: selectedGrpCd,
            itemCd: row.querySelector(".itemCd").value,
            itemNm: row.querySelector(".itemNm").value,
            grpOrder: row.querySelector(".grpOrder").value,
            useYn: action==="modify"?'Y':'N'
        }
        EgovNet.requestFetch(
            '/admin/config/code-item',
            {
                method: "PUT",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(codeItem)
            },
            (resp) => {
                switch (resp.resultCode) {
                    case Number(CODE.RCV_SUCCESS):
                        getCodeItemList(selectedGrpCd);
                        break;
                    case Number(CODE.RCV_ERROR_SAVE)||Number(CODE.RCV_ERROR_AUTH):
                        alert(resp.resultMessage);
                        break;
                }
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );

    }

    return (
        <Container className={"pt-3"} id={"codeItemDiv"}>
            <input type={"hidden"} id={"grpCd"} value={grpCd}/>
            <Row className={"py-2 bg-light border-bottom"}>
                <Col xs={3}>코드</Col>
                <Col xs={4}>코드명</Col>
                <Col xs={2}>순번</Col>
                <Col xs={3}>삭제&nbsp;&nbsp;&nbsp;&nbsp;수정</Col>
            </Row>
            {codeItemRow}
            {grpCd!=null?(
                <Row className={"py-1"}>
                    <Col xs={3}>
                        <Form.Control type={"text"} placeholder={"코드"} size={"sm"} id={"itemCd"}/>
                    </Col>
                    <Col xs={4}>
                        <Form.Control type={"text"} placeholder={"코드명"} size={"sm"} id={"itemNm"}/>
                    </Col>
                    <Col xs={2}>
                        <Form.Control type={"text"} placeholder={"순번"} size={"sm"} id={"grpOrder"}/>
                    </Col>
                    <Col xs={2}><Button type={"button"} variant={"primary"} size={"sm"} onClick={addCodeItem}>등록</Button></Col>
                </Row>
            ):(
                <Row className={"py-1"}>
                    <Col>코드 그룹을 선택해주세요.</Col>
                </Row>
            )}
        </Container>
    );
}

export default forwardRef(ChildCodeDiv);