import React from "react";
import { useNavigate, useLocation } from "react-router";
import { useSelector } from "react-redux";

import Modal from "../../component/Modal.jsx";
import ContentTitle from "../../component/ContentTitle.jsx";
import SubTitle from "../../component/SubTitle.jsx";
import Pagination from "../../component/Pagination.jsx";

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

export default function QandASelectOne() {
    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'];
	let defaultSeniorId = null;
	if (CommonUtil.isEmpty(state.loginUser) == false) {
		if (state.loginUser['authority'] == 'ROLE_SENIOR') {
			defaultSeniorId = state.loginUser['user_id'];
		} else if (state.loginUser['authority'] == 'ROLE_GUARDIAN' && CommonUtil.isEmpty(state.seniorList) == false) {
			defaultSeniorId = state.seniorList[state.currentSeniorIndex]['user_id'];
		}
	} else {
		defaultSeniorId = null;
	}

	//권한 타입 종류
	const [authorities, setAuthorities] = React.useState([]);
	//권한 타입 종류 목록 조회
	const authoritiesSelect = () => {
	  fetch("/common/systemCode/authoritiesSelect.json", {
		method: "POST",
		headers: {
		  'Content-Type': 'application/json; charset=UTF-8'
		},
		body: JSON.stringify({}),
	  }).then((response) => response.json()).then((data) => {
		console.log("권한 타입 종류 목록 조회 : ", data);
		setAuthorities(data);
	  }).catch((error) => {
		console.log('authoritiesSelect() /common/systemCode/authoritiesSelect.json error : ', error);
	  });
	};

	// 시스템 코드 - 장비 상태
	const [equipmentStates, setEquipmentStates] = React.useState({});
	// 시스템 코드 - 장비 상태 조회
	const equipmentStatesSelect = () => {
		console.log('equipmentStatesSelect Function Run');

		//fetch post
		fetch("/common/systemCode/equipmentStatesSelect.json", {
			method: "POST",
			headers: {
				'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify({})
		}).then((response) => response.json()).then((data) => {
			console.log('equipmentStatesSelect response : ', data);
			setEquipmentStates(data);
		}).catch((error) => {
			console.log('equipmentStatesSelect error : ', error);
		});
	}


	const equipmentInit = {
		'equipment_serial_number': null,
		'equipment_name': null,
		'agency_name': null,
		'rental_detail_insert_user_name': null,
		'rental_detail_insert_user_id': null,
		'user_name': null,
		'user_id': null,
		'user_address': null,
		'equipment_state': null,
	}
	//문의 정보
	const [equipmentInquiry, setEquipmentInquiry] = React.useState({
        'inquiry_idx': location.state['inquiry_idx'],
        'inquiry_type': null,
        'inquiry_title': null,
        'inquiry_content': null,
        'inquiry_state': null,
        'inquiry_insert_user_id': null,
        'inquiry_insert_datetime': null,
        'inquiry_answer_content': null,
        'inquiry_answer_user_id': null,
        'inquiry_update_datetime': null,

		'equipment_serial_number': null,
		//문의할 장비 정보
		equipment: {...equipmentInit}
    });
	const equipmentInquiryRef = React.useRef({...equipmentInquiry})

	//문의 상세 조회
	const equipmentInquirySelectOne = () => {
		fetch("/equipment/equipmentInquirySelectOne.json", {
			method: "POST",
			headers: {
				'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify(equipmentInquiry),
		}).then((response) => response.json()).then((data) => {
			console.log("문의 상세 조회 결과 : ", data);
			setEquipmentInquiry(data);
		}).catch((error) => {
			console.log('equipmentInquirySelectOne() /equipment/equipmentInquirySelectOne.json error : ', error);
		});
	}


	//문의 수정 페이지 이동
    const equipmentInquiryUpdatePage = () => {
        navigate("/QandAUpdate", {state: {
            'inquiry_idx': location.state['inquiry_idx'],
        }})
    }




	//문의 답변 등록
	const equipmentInquiryAnswerUpdate = () => {
		if (CommonUtil.isEmpty(equipmentInquiry['inquiry_answer_content'])) {
			equipmentInquiryRef.current['inquiry_answer_content'].focus();
			alert("답변을 입력해주세요.");

			equipmentInquiry['inquiry_answer_content'] = "[접수완료] 문제를 조속히 처리하여 불편을 해결해드릴 수 있도록 하겠습니다. ";
			setEquipmentInquiry({...equipmentInquiry});

			return;
		}

		if (confirm("해당 문의글의 답변을 등록하시겠습니까?") == false) {
			return;
		}

		fetch("/equipment/equipmentInquiryAnswerUpdate.json", {
			method: "POST",
			headers: {
				'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify(equipmentInquiry),
		}).then((response) => response.json()).then((data) => {
			console.log("문의 답변 등록 결과(건수) : ", data);
			if (data > 0) {
				alert("답변 등록완료");
				navigate('/QandASelect');
			} else {
				alert("답변 등록에 실패하였습니다. 관리자에게 문의바랍니다.");
			}
		}).catch((error) => {
			console.log('equipmentInquiryAnswerUpdate() /equipment/equipmentInquiryAnswerUpdate.json error : ', error);
		});
	}

	//문의 삭제
	const equipmentInquiryDelete = () => {
		if (confirm('해당 문의글을 삭제하시겠습니까?') == false) {
			return;
		}

		fetch("/equipment/equipmentInquiryDelete.json", {
			method: "POST",
			headers: {
				'Content-Type': 'application/json; charset=UTF-8'
			},
			body: JSON.stringify(equipmentInquiry),
		}).then((response) => response.json()).then((data) => {
			console.log("문의 삭제 결과(건수) : ", data);
			if (data > 0) {
				alert("삭제완료");
				navigate('/QandASelect');
			} else {
				alert("삭제에 실패하였습니다. 관리자에게 문의바랍니다.");
			}
		}).catch((error) => {
			console.log('equipmentInquiryDelete() /equipment/equipmentInquiryDelete.json error : ', error);
		});
	}


	//장비 관리 페이지 이동
	const equipmentSelectPage = () => {
		navigate('/EquipmentSelect', {state: {
			searchType: 'equipment_serial_number',
			searchText: equipmentInquiry.equipment['equipment_serial_number'],
			tabIndex: 1,

			'government_id': equipmentInquiry['insert_user_government_id']
		}});
	}

	React.useEffect(() => {
		authoritiesSelect();
		equipmentStatesSelect();
		equipmentInquirySelectOne();
	}, [])

  return (
    <main>
		
		<div className="content-wrap row">
			<ContentTitle contentTitle={"문의글 작성"} className={"margin-bottom2"} />
			<SubTitle explanation={"문의 정보"} className={"margin-bottom2"}/>
			<table className="margin-bottom2 qna-insert senior-detail">
				<tr>
					<th>구분</th>
					<td colSpan={3}>
						{CommonUtil.isEmpty(equipmentInquiry['equipment_serial_number']) ? '일반문의' : '장비문의'}
					</td>
				</tr>
				{equipmentInquiry['equipment_serial_number'] != null ?
				<tr>
					<th>장비문의 구분</th>
					<td colSpan={3}>
						{equipmentInquiry['inquiry_type']}
					</td>
				</tr>
				: null}
				<tr>
					<th>문의제목</th>
					<td colSpan={3}>
						{equipmentInquiry['inquiry_title']}
					</td>
				</tr>
				<tr>
					<th>내용</th>
					<td colSpan={3}>
						{equipmentInquiry['inquiry_content']}
					</td>
				</tr>
				{CommonUtil.isEmpty(state.loginUser) == false
				 && equipmentInquiry['insert_user_id'] != state.loginUser['user_id']
				? <>
					<tr>
						<th>작성자</th>
						<td>{equipmentInquiry['insert_user_name']}({equipmentInquiry['insert_user_id']})</td>
						<th>구분</th>
						<td>{authorities[equipmentInquiry['insert_user_authority']]}</td>
					</tr>
					<tr>
						<th>관리기관</th>
						<td>{equipmentInquiry['insert_user_government_name']}</td>
						<th>시행기관</th>
						<td>{equipmentInquiry['insert_user_agency_name']}</td>
					</tr>
					<tr>
						<th>연락처</th>
						<td colSpan={3}>{equipmentInquiry['insert_user_phonenumber']}</td>
					</tr>
				</>: null}
			</table>
			
			{equipmentInquiry['equipment_serial_number'] != null
			?<>
				<SubTitle explanation={'장비 정보'} className={"display-inline-block margin-bottom2"}/>
				{CommonUtil.isEmpty(equipmentInquiry.equipment['equipment_serial_number']) == false ?
				<>
					<table className="margin-bottom2 qna-insert senior-detail">
						<tr>
							<th>장비 시리얼넘버</th>
							<td colSpan={3}>
								{equipmentInquiry.equipment['equipment_serial_number']} 
								{CommonUtil.isEmpty(state.loginUser) == false && state.loginUser['authority'] == 'ROLE_ADMIN'
								 ? <button className="btn-small gray-btn margin-left2" onClick={() => equipmentSelectPage()}>관리페이지이동</button>
								: null}
							</td>
						</tr>
						<tr>
							<th>모델명</th>
							<td>
								{equipmentInquiry.equipment['equipment_name']}
							</td>
							<th>장비상태</th>
							<td>
								{equipmentStates[equipmentInquiry.equipment['equipment_state']]}
							</td>
						</tr>
						<tr>
							<th>소속기관</th>
							<td>
								{equipmentInquiry.equipment['agency_id'] == null ? equipmentInquiry.equipment['government_name'] : equipmentInquiry.equipment['agency_name']}
							</td>
							<th>대여시행자</th>
							<td>
								{CommonUtil.isEmpty(equipmentInquiry.equipment['equipment_serial_number']) == false
								&& CommonUtil.isEmpty(equipmentInquiry.equipment['rental_detail_insert_user_id']) == false
									? <>
										{equipmentInquiry.equipment['rental_detail_insert_user_name']}
										({equipmentInquiry.equipment['rental_detail_insert_user_id']})
									</>
								: '미대여'}
							</td>
						</tr>
						<tr>
							<th>장비사용대상자</th>
							<td>
								{equipmentInquiry.equipment['user_id'] == null ? '미대여' : equipmentInquiry.equipment['user_name']}
							</td>
							<th>대상자 ID</th>
							<td>
								{equipmentInquiry.equipment['user_id'] == null ? '미대여' : equipmentInquiry.equipment['user_id']}
							</td>
						</tr>
						<tr>
							<th>대상자 주소</th>
							<td colSpan={3}>
								{equipmentInquiry.equipment['user_id'] == null ? '미대여' : equipmentInquiry.equipment['user_address']}
							</td>
						</tr>
					</table>
				</>: null}
			</>: null}

			{CommonUtil.isEmpty(state.loginUser) == false
			 && state.loginUser['authority'] == 'ROLE_ADMIN'
			? <>
				<SubTitle explanation={'문의 답변'} className={"display-inline-block margin-bottom2"}/>
				<table className="margin-bottom2 qna-insert senior-detail">
					<tr>
						<th>답변</th>
						<td colSpan={3}>
							<textarea className="medicine" cols="30" rows="2"
								value={equipmentInquiry['inquiry_answer_content']}
								onChange={(e) => {equipmentInquiry['inquiry_answer_content'] = e.target.value; setEquipmentInquiry({...equipmentInquiry});}}
								ref={el => equipmentInquiryRef.current['inquiry_answer_content'] = el}
							></textarea>
						</td>
					</tr>
				</table>
			</>
			: null}
		
			<div className="btn-wrap flex-center margin-top5">
				<button className="btn-large gray-btn" onClick={() => navigate(-1)}>이전</button>

				{CommonUtil.isEmpty(state.loginUser) == false
				 && equipmentInquiry['insert_user_id'] == state.loginUser['user_id']
				 ? <button className="btn-large red-btn" onClick={() => equipmentInquiryUpdatePage()}>수정</button>
				 : null}
				 {CommonUtil.isEmpty(state.loginUser) == false
				  && state.loginUser['authority'] == 'ROLE_ADMIN'
				 ? <>
				 	<button className="btn-large red-btn" onClick={() => equipmentInquiryAnswerUpdate()}>답변등록</button>
					<button className="btn-large red-btn" onClick={() => equipmentInquiryDelete()}>삭제</button>
				 </>
				 : null}
			</div>

		</div>
	</main>
  );
}
