import React, {useCallback, useEffect, useState} from 'react';
import {Link} from "react-router-dom";
import URL from "constants/url";

import { default as EgovLeftNav } from 'components/leftmenu/EgovLeftNavAdmin';
import EgovPaging from "components/EgovPaging";
import * as EgovNet from "api/egovFetch";
import Modal from "react-bootstrap/Modal";
import UserInfoModal from "./UserInfoModal";
import CODE from "../../../constants/code";


function List({}) {

    const [searchCondition, setSearchCondition] = useState({
        pageIndex: 1,
        userSe: '',
        searchCondition: 'id',
        searchKeyword: ''
    });

    const [listTag, setListTag] = useState([]);

    const [paginationInfo, setPaginationInfo] = useState({});

    const [show, setShow] = useState(false);
    const [modalBody, setModalBody] = useState();

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    const retrieveList = useCallback((searchCondition) => {
        const params = EgovNet.convParams(searchCondition);
        EgovNet.requestFetch(
            '/admin/users/list'+params,
            {
                method: "GET"
            },
            (resp) => {
                setPaginationInfo(resp.result.paginationInfo);
                let mutListTag = [];

                setListTag([]);
                // 리스트 항목 구성
                resp.result.userList.forEach(function (item, index) {
                    mutListTag.push(
                        <div className={"list_item"} key={"userListDiv_"+index}>
                            <div><a href={"#"} onClick={()=>{userInfoModal(item)}}>{item.userId}</a></div>
                            <div>{item.userNm}</div>
                            <div>{item.email}</div>
                            <div>{item.phoneNum}</div>
                            <div>{item.statusValue}</div>
                            <div><button className={"btn btn_red_h31 px-1"} onClick={()=>{removeUserInfo(item.userSeq)}}>삭제</button></div>
                        </div>
                    );
                });
                if(!mutListTag.length) mutListTag.push(<p className="no_data" key="0">검색된 결과가 없습니다.</p>); // 게시판 목록 초기값

                setListTag(mutListTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    },[]);

    useEffect(() => {
        retrieveList(searchCondition);
    }, []);

    useEffect(() => {
        retrieveList(searchCondition);
    }, [searchCondition.pageIndex]);

    const movePage = useCallback((passedPage) => {
        setSearchCondition({...searchCondition, pageIndex: passedPage})
    });

    function userInfoModal(userInfo){
        handleShow()
        setModalBody(<UserInfoModal savedInfo={userInfo} reloadFunction={retrieveList}></UserInfoModal>)
    }
    
    const removeUserInfo = useCallback((seq)=>{
        if(window.confirm("삭제하시겠습니까?\n복구할 수 없습니다.")){
            EgovNet.requestFetch(
                '/admin/users/info',
                {
                    method: "DELETE",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify({userSeq: seq})
                },
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                        alert("삭제되었습니다.")
                        retrieveList(searchCondition)
                    }else{
                        alert("삭제를 실패하였습니다.")
                    }
                }
            )
        }
    });

    return (
        <div className="container">
            <div className="c_wrap">
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li>사이트관리</li>
                        <li>사용자 관리</li>
                        <li><Link to={URL.ADMIN__USERS__LIST}>사용자 목록</Link></li>
                    </ul>
                </div>
                <div className="layout">
                    {/* <!-- Navigation --> */}
                    <EgovLeftNav/>
                    <div className="contents NOTICE_LIST" id="contents">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h1 className="tit_1">사용자 목록</h1>
                        </div>
                        <h2 className="tit_2"></h2>
                        {/* <!-- 검색조건 --> */}
                        <div className="condition">
                            <ul>
                                <li className="third_1 L">
                                    <label className="f_select" htmlFor="sel1">
                                        <select id="sel1" title="조건" defaultValue={searchCondition.searchCondition}
                                                onChange={(e) => {setSearchCondition({...searchCondition, searchCondition: e.target.value})}}>
                                            <option value="id">아이디</option>
                                            <option value="name">이름</option>
                                            <option value="email">이메일</option>
                                            <option value="phoneNum">연락처</option>
                                        </select>
                                    </label>
                                </li>
                                <li className="third_2 R">
                                    <span className="f_search w_500">
                                        <input type="text" name="" defaultValue={searchCondition.searchKeyword} placeholder=""
                                               onChange={(e) => {setSearchCondition({...searchCondition, searchKeyword: e.target.value})}}/>
                                        <button type="button" onClick={() => {retrieveList(searchCondition)}}>조회</button>
                                    </span>
                                </li>
                            </ul>
                        </div>

                        <div className="board_list userList">
                            <div className="head">
                                <span>아이디</span>
                                <span>이름</span>
                                <span>이메일</span>
                                <span>연락처</span>
                                <span>상태</span>
                                <span>삭제</span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>

                        <div className="board_bot">
                            <EgovPaging pagination={paginationInfo} moveToPage={passedPage => {movePage(passedPage)}} />
                        </div>
                    </div>
                </div>
            </div>
            <Modal show={show} onHide={handleClose} keyboard={false}>
                {modalBody}
            </Modal>
        </div>
    );
}

export default List;