import React from "react";
import { useNavigate, useLocation } from "react-router";
import { useSelector } from "react-redux";
import DetailTitle from "../../component/DetailTitle.jsx";
import Pagination from "../../component/Pagination.jsx";

import CommonUtil from "../../../resources/js/CommonUtil.js";

export default function QandASelect() {
    const navigate = useNavigate();
    const location = useLocation();

    //전역 변수 저장 객체
    const state = useSelector((state) => {return state});
    const defaultGovernmentId = CommonUtil.isEmpty(state.loginUser) ? null : state.loginUser['government_id'];
	const defaultAgencyId = CommonUtil.isEmpty(state.loginUser) ? null : state.loginUser['agency_id'];
    const defaultUserId = CommonUtil.isEmpty(state.loginUser) == false
                        && (state.loginUser['authority'] == 'ROLE_SENIOR'
                            || state.loginUser['authority'] == 'ROLE_GUARDIAN')
                        ? state.loginUser['user_id'] : null;


	//기관 계층 구조 목록
	const [orgListOfHierarchy, setOrgListOfHierarchy] = React.useState([]);
	//기관(관리, 시행) 계층 구조 목록 조회
	const orgSelectListOfHierarchy = () => {
        const param = {
            'government_id': defaultGovernmentId,
            'agency_id': defaultAgencyId
        }
        if (CommonUtil.isEmpty(state.loginUser) == false
            && state.loginUser['authority'] == 'ROLE_ADMIN') {
            param['government_id'] = null;
            param['agency_id'] = null;
        }

		fetch("/org/orgSelectListOfHierarchy.json", {
			method: "POST",
			headers: {
			    'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify(param),
		}).then((response) => response.json()).then((data) => {
			console.log("기관(관리, 시행) 계층 구조 목록 조회 : ", data);
			setOrgListOfHierarchy(data);
		}).catch((error) => {
			console.log('orgSelectListOfHierarchy() /org/orgSelectListOfHierarchy.json error : ', error);
		});
	};

    const [search, setSearch] = React.useState({
        'government_id': defaultGovernmentId,
        'agency_id': defaultAgencyId,
        'user_id': defaultUserId,

        'equipment_serial_number': null,
        'inquiry_answer_user_id': null,

        'searchType': null,
        'searchText': null,
        'currentPage': 0,
        'perPage': 10,
    });
    const searchingEnter = (key) => {
		if (key == 'Enter') {
			searching();
		} else {
			return;
		}
	}
	const searching = () => {
		equipmentInquirySelectList(1);
	}

    //문의 목록
    const [equipmentInquiry, setEquipmentInquiry] = React.useState({
        equipmentInquiryList: [],
        equipmentInquiryListCount: 0, 
    });
	//문의 목록 조회
	const equipmentInquirySelectList = (currentPage) => {
        search.currentPage = CommonUtil.isEmpty(currentPage) ? 1 : currentPage;
		fetch("/equipment/equipmentInquirySelectList.json", {
			method: "POST",
			headers: {
			    'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify(search),
		}).then((response) => response.json()).then((data) => {
			console.log("문의 목록 조회 : ", data);
			setEquipmentInquiry(data);
		}).catch((error) => {
			console.log('equipmentInquirySelectList() /equipment/equipmentInquirySelectList.json error : ', error);
		});
	};


    //문의 상세조회 페이지 이동
    const equipmentInquirySelectOnePage = (item) => {
        navigate("/QandASelectOne", {state: {
            'inquiry_idx': item['inquiry_idx'],
        }});
    }


    React.useEffect(() => {
        orgSelectListOfHierarchy();
        searching();
    }, []);
    
    return (
        <main>
            <div className="search-management flex-end margin-bottom2 margin-top gap">						
				<select style={{maxWidth: '150px'}} value={search['equipment_serial_number']}
					onChange={(e) => {search['equipment_serial_number'] = e.target.value; setSearch({...search});}}>
					<option value="">문의구분</option>
                    <option value="IS_NULL">일반문의</option>
                    <option value="IS_NOT_NULL">장비문의</option>
				</select>
                <select style={{maxWidth: '150px'}} value={search['inquiry_answer_user_id']}
					onChange={(e) => {search['inquiry_answer_user_id'] = e.target.value; setSearch({...search});}}>
					<option value="">상태</option>
                    <option value="IS_NULL">답변대기중</option>
                    <option value="IS_NOT_NULL">답변완료</option>
				</select>
				<select style={{maxWidth: '150px'}} value={search['searchType']}
					onChange={(e) => {search['searchType'] = e.target.value; setSearch({...search});}}>
					<option value="">전체</option>
					<option value="user_name">문의자 이름</option>
					<option value="user_id">문의자 ID</option>
                    <option value="user_phonenumber">문의자 연락처</option>
                    <option value="inquiry_title">제목</option>
                    <option value="inquiry_content">문의내용</option>
                    <option value="inquiry_answer_content">답변내용</option>
                    <option value="equipment_serial_number">시리얼 넘버</option>
				</select>
				<input type="text"
					value={search['searchText']}
					onChange={(e) => {search['searchText'] = e.target.value; setSearch({...search});}}
					onKeyUp={(e) => searchingEnter(e.key)}
				/>
				<button className="btn-small gray-btn" style={{maxWidth: '150px'}} onClick={searching}>검색</button>
			</div>

            <div className="content-wrap">
                <DetailTitle contentTitle={"Q&A"} />
                <div className="board-wrap" style={{ marginTop: "3rem" }} >
                    {CommonUtil.isEmpty(state.loginUser) == false && state.loginUser['authority'] != 'ROLE_ADMIN' ?
                        <div className="btn-wrap flex-end margin-bottom">
                            <button className="btn-small gray-btn" onClick={() => {navigate("/QandAInsert");}}>문의하기</button>
                        </div>
                    : null}
                    <table class="equipment-detail senior-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>관리기관</th>
                                <th>시행기관</th>
                                <th>제목</th>
                                <th>작성자</th>
                                <th>작성일시</th>
                                <th>문의구분</th>
                                <th>처리여부</th>
                            </tr>
                        </thead>
                        <tbody>
                            {equipmentInquiry.equipmentInquiryList.map((item, idx) => { return (
                            <tr key={idx} onClick={() => equipmentInquirySelectOnePage(item)}>
                                <td data-label="No">{equipmentInquiry.equipmentInquiryListCount - idx - (search.currentPage - 1) * search.perPage}</td>
                                <td data-label="관리기관">{item['insert_user_government_name']}</td>
                                <td data-label="시행기관">{item['insert_user_agency_name']}</td>
                                <td data-label="제목">{item['inquiry_title']}</td>
                                <td data-label="작성자">{item['insert_user_name']}</td>
                                <td data-label="작성일시">{item['inquiry_insert_datetime']}</td>
                                <td data-label="문의구분">
                                    {CommonUtil.isEmpty(item['inquiry_type']) == false ? `장비(${item['inquiry_type']})` : '일반문의'}
                                </td>
                                <td data-label="처리여부">
                                    {CommonUtil.isEmpty(item['inquiry_answer_user_id']) == false ? '답변완료' : '답변대기중'}
                                </td>
                            </tr>
                            )})}
                            {CommonUtil.isEmpty(equipmentInquiry.equipmentInquiryList) ?
                            <tr>
                                <td colSpan={8}>조회된 데이터가 없습니다</td>
                            </tr>
                            : null}
                        </tbody>
                    </table>
                    <Pagination
                        currentPage={search.currentPage}
                        perPage={search.perPage}
                        totalCount={equipmentInquiry.equipmentInquiryListCount}
                        maxRange={5}
                        click={equipmentInquirySelectList}
                    />
                    
                </div>
            </div>
        </main>
    );
}

