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

import SubTitle from "../../component/SubTitle.jsx";
import Modal_Guardian from "../../component/Modal_Guardian.jsx";
import Modal_SeniorInsert from "../../component/Modal_SeniorInsert.jsx";


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


  //대상자(시니어) 등록 모달 오픈 여부
  const [modalSeniorInsertIsOpen, setModalSeniorInsertIsOpen] = React.useState(false);
  //대상자(시니어) 등록 모달 오픈
  const modalSeniorInsertOpen = () => {
    setModalSeniorInsertIsOpen(true);
  };
  //대상자(시니어) 등록 모달 닫기
  const modalSeniorInsertClose = () => {
    setModalSeniorInsertIsOpen(false);
  };


  //시니어 정보
  const [agent, setAgent] = React.useState({
    'user_id': location.state['agent_id'],
    'user_name': null,
    'user_password': null,
    'user_phonenumber': null,
    'user_birth': null,
    'user_gender': null,
    'user_address': null,
    'user_email': null,
    'authority': 'ROLE_AGENCY',
    'agency_id': null,
    'government_id': null,

    'agent_id': location.state['agent_id'],
  });
  //시니어 상세 조회
  const agentSelectOne = () => {
    fetch("/user/userSelectOne.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(agent),
    }).then((response) => response.json()).then((data) => {
      console.log("agentSelectOne data : ", data);
      data['agent_id'] = location.state['agent_id'];
      setAgent(data);
    }).catch((error) => {
      console.log('agentSelectOne() /user/userSelectOne.json error : ', error);
    });
  };

  //생활보호사의 대상자 목록
  const [seniorByAgent, setSeniorByAgent] = React.useState({ seniorListByAgent: [], seniorListCountByAgent: 0 });
  //생활보호사의 선택한 대상자 정보
  const [senior, setSenior] = React.useState({});
  //생활보호사의 대상자 목록 조회
  const seniorSelectListByAgent = () => {
    fetch("/user/seniorSelectListByAgent.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(agent),
    }).then((response) => response.json()).then((data) => {
      console.log("seniorSelectListByAgent data : ", data);
      setSeniorByAgent(data);
    }).catch((error) => {
      console.log('seniorSelectListByAgent() /user/seniorSelectListByAgent.json error : ', error);
    });
  };

  //선택한 보호자 정보 관리
  const guardianByAgentManagement = (item) => {
    setSenior(item);
  }

  //가입승인
  const userUpdate = () => {
    agent['is_accept'] = true;

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



  //보호자의 대상자 제거
  const agentSeniorDelete = (senior) => {
    if (confirm('해당 보호대상자의 케어를 종료하시겠습니까?') == false) {
      return;
    }

    fetch("/user/agentSeniorDelete.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(senior),
    }).then((response) => response.json()).then((data) => {
      console.log("보호자의 대상자 제거 결과(건수) : ", data);
      if (data > 0) {
        alert("케어종료완료");
        seniorSelectListByAgent();
      } else {
        alert("케어종료에 실패하였습니다. 관리자에게 문의바랍니다.");
      }
    }).catch((error) => {
      console.log('agentSeniorDelete() /user/agentSeniorDelete.json error : ', error);
    });
  }

  React.useEffect(() => {
    agentSelectOne();
    seniorSelectListByAgent();
  }, [])


  return (
    <main>
      <Modal_SeniorInsert
        open={modalSeniorInsertIsOpen}
        close={modalSeniorInsertClose}
        seniorInsertCallback={() => { seniorSelectListByAgent(); modalSeniorInsertClose(); }}
        defaultAgentId={agent['agent_id']}
        defaultAgencyId={agent['agency_id']}
        defaultGovernmentId={agent['government_id']}
      />

      <div className="content-wrap row">
        <SubTitle explanation={"대상자 상세 프로필"} className="margin-bottom" />
        <div className="margin-bottom5">
          <table className="margin-bottom senior-detail">
            <tbody>
              <tr>
                <th>관리기관</th>
                <td>
                  <span>{agent['government_name']}</span>
                </td>
              </tr>

              <tr>
                <th>시행기관</th>
                <td>
                  <span>{agent['agency_name']}</span>
                </td>
              </tr>

              <tr>
                <th>이름(아이디)</th>
                <td>
                  <span>{agent['user_name']}({agent['user_id']})</span>
                </td>
              </tr>

              <tr>
                <th>연락처</th>
                <td>
                  <span>{agent['user_phonenumber']}</span>
                </td>
              </tr>

              <tr>
                <th>이메일</th>
                <td>
                  <span>{agent['user_email']}</span>
                </td>
              </tr>

              <tr>
                <th>계정활성화여부</th>
                <td>
                  <span>{agent['user_use'] ? '활성화' : '비활성화'}</span>
                </td>
              </tr>

            </tbody>
          </table>
          <div className="btn-wrap flex-center">
            <button className={"btn-large gray-btn"} onClick={() => { navigate("/UserEdit", { state: { 'user_id': agent['user_id'] } }) }}>수정</button>
            <button className={"btn-large red-btn"} onClick={() => alert("삭제할 수 없습니다.")}>삭제</button>
          </div>
        </div>

        <SubTitle explanation={"생활보호사의 보호대상자"} className="margin-bottom display-inline-block" />
        <button className={"btn-small gray-btn display-inline-block float-right"} onClick={() => modalSeniorInsertOpen()}>보호대상자 추가</button>
        <div className="margin-bottom5">
          <table className={"agent-user"}>
            <thead>
              <tr>
                <th>No</th>
                {/* <th>관리기관명</th>
                <th>소속기관명</th> */}
                <th>이름</th>
                <th>연락처</th>
                <th>생년월일</th>
                <th>성별</th>
                <th>상태</th>
                <th>배정시작일</th>
                <th>배정종료일</th>
                <th>상세보기</th>
              </tr>
            </thead>
            <tbody>
              {seniorByAgent.seniorListByAgent.map((item, idx) => {
                return (
                  <tr key={idx}>
                    <td>{idx + 1}</td>
                    {/* <td>{item['government_name']}</td>
                  <td>{item['agency_name']}</td> */}
                    <td>{item['user_name']}</td>
                    <td>{item['user_phonenumber']}</td>
                    <td>{item['user_birth']}</td>
                    <td>{item['user_gender']}</td>
                    <td>{item['agent_match_state'] ? <span className="green">케어중</span> : <span className="grey">케어완료</span>}</td>
                    <td>{item['agent_match_start_date']}</td>
                    <td>
                      {item['agent_match_state'] ?
                        <button className={"btn-small red-btn"} onClick={() => { agentSeniorDelete(item) }}>케어종료</button>
                        : item['agent_match_end_date']
                      }
                    </td>
                    <td>
                      <button className={"btn-small lightgray-btn"} onClick={() => { navigate("/SeniorSelectOne", { state: { 'senior_id': item['user_id'] } }) }}>상세 페이지 이동</button>
                    </td>
                  </tr>
                )
              })}
              {seniorByAgent.seniorListByAgent == null || seniorByAgent.seniorListByAgent.length == 0 ?
                <tr>
                  <td colSpan={9}>조회된 데이터가 없습니다</td>
                </tr>
                : null}
            </tbody>
          </table>
        </div>

        <div className="btn-wrap flex-center">
          <button className={"btn-large gray-btn"} onClick={() => navigate(-1)}>이전</button>
        </div>

      </div>

    </main>
  );
}
