import React from "react";
import { useNavigate } from "react-router";
import { useSelector } from "react-redux";
import { useStateWithCallbackLazy } from 'use-state-with-callback';
import DetailTitle from "../../component/DetailTitle.jsx";
import SubTitle from "../../component/SubTitle.jsx";
import Modal from "../../component/Modal.jsx";

import House from "../../../resources/files/icon/house.png";
import Arrow from "../../../resources/files/icon/arrow.png";
import Pagination from "../../component/Pagination.jsx";

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

export default function GovernmentEquipmentSelect() {

  const navigate = useNavigate();

  //전역 변수 저장 객체
  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 [orgListOfHierarchy, setOrgListOfHierarchy] = React.useState([]);
  //기관(관리, 시행) 계층 구조 목록 조회
  const orgSelectListOfHierarchy = () => {
    fetch("/org/orgSelectListOfHierarchy.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'government_id': defaultGovernmentId,
        'agency_id': defaultAgencyId
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("기관(관리, 시행) 계층 구조 목록 조회 : ", data);
      setOrgListOfHierarchy(data);
    }).catch((error) => {
      console.log('orgSelectListOfHierarchy() /org/orgSelectListOfHierarchy.json error : ', error);
    });
  };
  //검색 변수 (초기화값)
  const [org, setOrg] = React.useState({
    'government_id': defaultGovernmentId,
    'agency_id': defaultAgencyId,
  });
  //올잇메디 선택
  const adminChange = () => {
    org['government_id'] = null;
    org['agency_id'] = null;
    setOrg({ ...org });
  }
  //관리 기관 선택
  const governmentChange = (government_id) => {
    org['government_id'] = government_id;
    org['agency_id'] = null;
    setOrg({ ...org });
    rentalEquipmentSelectList(1);
  }
  //시행 기관 선택
  const agencyChange = (government_id, agency_id) => {
    org['government_id'] = government_id;
    org['agency_id'] = agency_id;
    setOrg({ ...org });
    rentalEquipmentSelectList(1);
  }



  // 시스템 코드 - 장비 상태
  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 [equipmentSearch, setEquipmentSearch] = React.useState({
    'equipment_state': null,

    'searchType': null,
    'searchText': null,
  });
  //장비 정보 변경
  const equipmentSearchChange = (targetKey, value) => {
    equipmentSearch[targetKey] = value;
    setEquipmentSearch({ ...equipmentSearch });
  }
  //장비 검색
  const equipmentSearching = () => {
    for (const key in equipmentSearch) {
      deliveryEquipmentSearch[key] = equipmentSearch[key];
      rentalEquipmentSearch[key] = equipmentSearch[key];
    }
    setDeliveryEquipmentSearch({ ...deliveryEquipmentSearch });
    setRentalEquipmentSearch({ ...rentalEquipmentSearch });

    deliveryEquipmentSelectList(1);
    rentalEquipmentSelectList(1);
  }
  const equipmentSearchingEnter = (key) => {
    if (key == 'Enter') {
      equipmentSearching();
    } else {
      return;
    }
  }

  //입고 및 미대여 장비 검색 정보
  const [deliveryEquipmentSearch, setDeliveryEquipmentSearch] = React.useState({
    'government_id': defaultGovernmentId,
    'senior_id': 'IS_NULL',
    'currentPage': 1,
    'perPage': 10,
  });
  //입고 및 미대여 목록
  const [deliveryEquipment, setDeliveryEquipment] = React.useState({ equipmentList: [], equipmentListCount: 0 });
  //입고 및 미대여 목록 조회
  const deliveryEquipmentSelectList = (currentPage) => {
    deliveryEquipmentSearch.currentPage = CommonUtil.isEmpty(currentPage) ? 1 : currentPage;
    setDeliveryEquipmentSearch({ ...deliveryEquipmentSearch });

    fetch("/equipment/equipmentSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(deliveryEquipmentSearch)
    }).then((response) => response.json()).then((data) => {
      console.log('deliveryEquipmentSelectList response : ', data);
      setDeliveryEquipment(data);
    }).catch((error) => {
      console.log('deliveryEquipmentSelectList error : ', error);
    });
  }

  //입고 및 미대여 장비 검색 정보
  const [rentalEquipmentSearch, setRentalEquipmentSearch] = React.useState({
    'government_id': defaultGovernmentId,
    'agency_id': org['agency_id'],
    'senior_id': 'IS_NOT_NULL',
    'currentPage': 1,
    'perPage': 10,
  });
  //입고 및 미대여 목록
  const [rentalEquipment, setRentalEquipment] = React.useState({ equipmentList: [], equipmentListCount: 0 });
  //입고 및 미대여 목록 조회
  const rentalEquipmentSelectList = (currentPage) => {
    rentalEquipmentSearch.currentPage = CommonUtil.isEmpty(currentPage) ? 1 : currentPage;
    rentalEquipmentSearch['agency_id'] = org['agency_id'];
    setRentalEquipmentSearch({ ...rentalEquipmentSearch });

    fetch("/equipment/equipmentSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(rentalEquipmentSearch)
    }).then((response) => response.json()).then((data) => {
      console.log('rentalEquipmentSelectList response : ', data);
      setRentalEquipment(data);
    }).catch((error) => {
      console.log('rentalEquipmentSelectList error : ', error);
    });
  }

  //장비 초기값
  const equipmentInit = {
    'equipment_serial_number': null,
    'equipment_type': 'SMART_PILLBOX',
    'equipment_name': null,
    'equipment_state': null,
    'equipment_product_date': null,
    'equipment_stock_date': null,
    'equipment_insert_datetime': null,
    'equipment_insert_user_id': null,
    'equipment_update_datetime': null,
    'equipment_update_user_id': null,
    'government_id': defaultGovernmentId,
    'agency_id': defaultAgencyId,
    'senior_id': null
  }
  //장비
  const [equipment, setEquipment] = useStateWithCallbackLazy({ ...equipmentInit });
  //각 데이터별로 Dom 정보 담을 Ref 생성
  const equipmentRef = React.useRef({ ...equipmentInit });
  //장비 정보 변경
  const equipmentValueChange = (targetKey, value) => {
    let newEquipment = { ...equipment };
    newEquipment[targetKey] = value;
    setEquipment(newEquipment);
  }
  //장비 유효성 검사
  const equipmentValidation = () => {
    const target = equipment;
    const targetRef = equipmentRef;

    if (CommonUtil.isEmpty(target['equipment_name']) == true) {
      targetRef.current['equipment_name'].focus();
      alert("모델명을 입력해 주세요.");
      return false;
    }
    if (CommonUtil.isEmpty(target['equipment_serial_number']) == true) {
      targetRef.current['equipment_serial_number'].focus();
      alert("S/N을 입력해 주세요.");
      return false;
    }
    /* if (CommonUtil.isEmpty(target['equipment_product_date']) == true) {
      targetRef.current['equipment_product_date'].focus();
      alert("생산일자를 선택해 주세요.");
      return false;
    } */
    if (CommonUtil.isEmpty(target['equipment_stock_date']) == true) {
      targetRef.current['equipment_stock_date'].focus();
      alert("입고일자를 선택해 주세요.");
      return false;
    }

    return true;
  }
  //시리얼 번호 중복 확인
  const [isSerialNumberCheck, setIsSerialNumberCheck] = React.useState(false);
  const [isEquipmentCheck, setIsEquipmentCheck] = React.useState(false);
  //시리얼 번호 중복 검사
  const serialNumberCheck = () => {
    if (CommonUtil.isEmpty(equipment['equipment_serial_number']) == true) {
      equipmentRef.current['equipment_serial_number'].focus();
      alert("모델명을 입력해 주세요.");
      return false;
    }

    fetch("/equipment/equipmentSelectSerialNumber.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(equipment),
    }).then((response) => response.json()).then((data) => {
      console.log("시리얼 번호 중복 검사 : ", data);
      if (CommonUtil.isEmpty(data['equipment']) != false) {
        setIsSerialNumberCheck(true);
        if (data['serialNumberChk']['count'] == 1) {
          setIsEquipmentCheck(true);
        } else {
          setIsEquipmentCheck(false);
        }
        equipmentRef.current['equipment_product_date'].focus();
        alert("사용가능한 시리얼 번호 입니다.");
        buttonChange();
      } else {
        setIsSerialNumberCheck(false);
        equipmentRef.current['equipment_serial_number'].focus();
        alert("이미 존재하는 시리얼 번호 입니다.");
      }
    }).catch((error) => {
      console.log('userIdCheck() /user/equipmentSelectSerialNumber.json error : ', error);
    });
  }
  //장비 등록
  const equipmentInsert = () => {
    if (equipmentValidation() == false) {
      return;
    }
    if (isSerialNumberCheck == false) {
      alert("시리얼 번호 중복확인을 해주세요.");
      equipmentRef.current['equipment_serial_number'].focus();
      return;
    }
    console.log('equipmentInsert equipment : ', equipment);

    fetch("/equipment/equipmentInsert.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(equipment),
    }).then((response) => response.json()).then((data) => {
      console.log("장비 등록 결과(건수) : ", data);
      if (data > 0) {
        alert("등록완료");
        equipmentSearching();
        modalEquipmentClose();
      } else {
        alert("등록에 실패하였습니다. 관리자에게 문의바랍니다.");
      }
    }).catch((error) => {
      console.log('equipmentInsert() /equipment/equipmentInsert.json error : ', error);
    });
  }
  // 미확인 장비 등록
  const equipmentInsertUpdate = () => {
    if (equipmentValidation() == false) {
      return;
    }

    equipment['equipment_state'] = 'AVAILABLE';

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

  //장비 수정
  const equipmentUpdate = () => {
    if (equipmentValidation() == false) {
      return;
    }

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

  //장비 삭제
  const equipmentDelete = () => {
    if (confirm('해당 장비를 삭제하시겠습니까?') == false) {
      return;
    }

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



  // 장비 관리(등록,수정) 모달창
  const [modalEquipmentIsOpen, setModalEquipmentIsOpen] = React.useState(false);
  // 장비 관리(등록,수정) 모달창 열기
  const modalEquipmentOpen = (item) => {
    if (CommonUtil.isEmpty(item)) {
      //equipment['equipment_insert_datetime'] = null;

      /* if (CommonUtil.isEmpty(orgListOfHierarchy[0]['agencyList']) == false) {
        equipmentInit['agency_id'] = orgListOfHierarchy[0]['agencyList'][0]['agency_id'];
      } */

      setIsSerialNumberCheck(false);
      setEquipment({ ...equipmentInit });
    } else {
      setEquipment(item);
    }
    setModalEquipmentIsOpen(true);
  };
  // 장비 관리(등록,수정) 모달창 닫기
  const modalEquipmentClose = () => {
    setModalEquipmentIsOpen(false);
  };


  //장비 대여 모달 여부
  const [modalRentalIsOpen, setModalRentalIsOpen] = React.useState(false);
  //장비 대여 오픈
  const modalRentalOpen = (item) => {
    setSelectEquipment(item);
    mySenior['search']['agency_id'] = item['agency_id'];
    mySeniorSelectList(1);
    setModalRentalIsOpen(true);
  };
  //장비 대여 닫기
  const modalRentalClose = () => {
    setModalRentalIsOpen(false);
  };

  //장비 대여 등록 정보
  const [selectEquipment, setSelectEquipment] = React.useState()

  //장비 대여 등록
  const equipmentRentalInsert = (senior) => {
    if (confirm('해당 장비를 추가하시겠습니까?') == false) {
      return;
    }

    selectEquipment['agency_id'] = senior['agency_id']; // 장비에 시행기관이 '없음'일 경우 배포한 시니어의 시행기관을 등록 
    selectEquipment['senior_id'] = senior['senior_id'];
    selectEquipment['rental_start_date'] = new Date();

    fetch("/equipment/equipmentRentalInsert.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(selectEquipment),
    }).then((response) => response.json()).then((data) => {
      console.log("장비 대여 등록 결과(건수) : ", data);
      if (data > 0) {
        alert("추가완료");
        orgSelectListOfHierarchy();
        equipmentStatesSelect();
        equipmentSearching();
        modalRentalClose();
      } else {
        alert("장비추가에 실패하였습니다. 관리자에게 문의바랍니다.");
      }
    }).catch((error) => {
      console.log('seniorSelectOne() /user/seniorSelectOne.json error : ', error);
    });
  };

  // 소속기관 내 시니어
  const [mySenior, setMySenior] = React.useState({
    seniorList: [],
    seniorListCount: 0,
    search: {
      'government_id': defaultGovernmentId,
      'agency_id': defaultAgencyId,
      'user_use': true,
      'equipment_search': 'IS_NULL',
      'currentPage': 1,
      'perPage': 5,
    }
  });
  // 소속기관 내 시니어 목록 조회
  const mySeniorSelectList = (currentPage) => {
    mySenior.search.currentPage = CommonUtil.isEmpty(currentPage) ? 1 : currentPage;

    fetch("/user/seniorSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(mySenior.search),
    }).then((response) => response.json()).then((data) => {
      data.search = mySenior.search;
      console.log(" 소속기관 내 시니어 목록 조회 : ", data);
      setMySenior(data);
    }).catch((error) => {
      console.log('seniorSelectList() /user/seniorSelectList.json error : ', error);
    });
  }

  //Mounted
  React.useEffect(() => {
    orgSelectListOfHierarchy();
    equipmentStatesSelect();
    equipmentSearching();
  }, []);


  //대여(사용) 중 장비 목록 내용
  const rentalContent = (
    <>
      <table class="caregiver-user protector-user">
        <thead>
          <tr>
            <th>No</th>
            <th>모델명</th>
            <th>시리얼넘버</th>
            <th>입고일자</th>
            <th>장비상태</th>
            <th>기관</th>
            <th>대여시행자</th>
            <th>대여일</th>
            <th>대여여부</th>
            <th>장비사용대상자</th>
          </tr>
        </thead>
        <tbody>
          {rentalEquipment.equipmentList.map((item, idx) => {
            return (
              <tr>
                <td data-label="No">{rentalEquipment.equipmentListCount - idx - (rentalEquipmentSearch.currentPage - 1) * rentalEquipmentSearch.perPage}</td>
                <td data-label="모델명">{item['equipment_name']}</td>
                <td data-label="시리얼넘버">{item['equipment_serial_number']}</td>
                <td data-label="입고일자">{item['equipment_stock_date']}</td>
                <td data-label="장비상태">{equipmentStates[item['equipment_state']]}</td>
                <td>{item['agency_name']}</td>
                <td data-label="대여시행자">
                  {item['rental_detail_insert_user_name']}
                  ({item['rental_detail_insert_user_id']})
                </td>
                <td data-label="대여일">{item['rental_start_date']}</td>
                <td data-label="대여여부">{CommonUtil.isEmpty(item['user_name']) == false ? '대여중' : '미대여'}</td>
                <td data-label="장비사용대상자">{item['user_name']}</td>
              </tr>
            )
          })}
          {CommonUtil.isEmpty(rentalEquipment.equipmentList) ?
            <tr>
              <td colSpan={10}>조회된 데이터가 없습니다</td>
            </tr>
            : null}
        </tbody>
      </table>
      <Pagination
        currentPage={rentalEquipmentSearch.currentPage}
        perPage={rentalEquipmentSearch.perPage}
        totalCount={rentalEquipment.equipmentListCount}
        maxRange={5}
        click={rentalEquipmentSelectList}
      />
    </>
  );


  //현재 탭 Index
  const [tabIndex, setTabIndex] = React.useState(0);
  //탭 초기화
  const tab = [{
    title: `사용가능 장비 (${deliveryEquipment.equipmentListCount})`,
    content: (
      <div>
        <div className="flex equip-tab">
          <SubTitle explanation={"현재 기관에 입고된 장비 중 돌봄 대상자에게 대여하지 않은 장비 목록입니다."} />
          <div className="btn-wrap flex-end margin-bottom ">
            <button className={"btn-small gray-btn"} onClick={() => { modalEquipmentOpen() }}>장비 등록</button>
          </div>
        </div>
        <table class="caregiver-user protector-user">
          <thead>
            <tr>
              <th>No </th>
              <th>모델명</th>
              <th>시리얼넘버</th>
              <th>입고일자</th>
              <th>장비상태</th>
              <th>기관</th>
              <th>장비대여</th>
              <th>관리</th>
            </tr>
          </thead>
          <tbody>
            {deliveryEquipment.equipmentList.map((item, idx) => {
              return (
                <tr>
                  <td data-label="No">{deliveryEquipment.equipmentListCount - idx - (deliveryEquipmentSearch.currentPage - 1) * deliveryEquipmentSearch.perPage}</td>
                  <td data-label="모델명">{item['equipment_name']}</td>
                  <td data-label="시리얼넘버">{item['equipment_serial_number']}</td>
                  <td data-label="입고일자">{item['equipment_stock_date']}</td>
                  <td data-label="장비상태">{equipmentStates[item['equipment_state']]}</td>
                  <td data-label="기관">{item['agency_name'] != null ? item['agency_name'] : '없음'}</td>
                  <td cata-label="장비대여">
                    <button className={"btn-small gray-btn"} onClick={() => modalRentalOpen(item)}>장비 배포</button>
                  </td>
                  <td data-label="관리">
                    <button className={"btn-small gray-btn"} onClick={() => modalEquipmentOpen(item)}>정보 수정</button>
                  </td>
                </tr>
              )
            })}
            {CommonUtil.isEmpty(deliveryEquipment.equipmentList) ?
              <tr>
                <td colSpan={8}>조회된 데이터가 없습니다</td>
              </tr>
              : null}
          </tbody>
        </table>
        <Pagination
          currentPage={deliveryEquipmentSearch.currentPage}
          perPage={deliveryEquipmentSearch.perPage}
          totalCount={deliveryEquipment.equipmentListCount}
          maxRange={5}
          click={deliveryEquipmentSelectList}
        />
      </div >
    )
  }, {
    title: `사용중인 장비 (${rentalEquipment.equipmentListCount})`,
    content: (
      <div>
        <div className="flex-align-start userauthoriylist gap5">
          <div className="left">
            <SubTitle explanation={"기관 리스트"} />
            <div style={{ fontSize: '16px', marginTop: '0px' }} className="category">
              {/* {state.loginUser['authority'] == 'ROLE_ADMIN' ?
								<a onClick={adminChange}
									className={org['government_id'] == null && org['agency_id'] == null ? "active" : ""}>
									올잇메디
								</a>
							: null} */}
              <ul style={{ marginLeft: '15px' }}>
                {orgListOfHierarchy.map((item, idx) => {
                  return (
                    <li style={{ margin: '10px 0px' }} key={idx}>
                      <span style={{ marginRight: '5px' }}><img src={House} alt="" /></span>
                      <a onClick={() => { governmentChange(item['government_id']) }}
                        className={item['government_id'] == org['government_id'] ? "active" : ""}>
                        {item['government_name']}
                      </a>
                      {item['agencyList'] != undefined && item['agencyList'] != null ?
                        <ul style={{ marginLeft: '15px' }}>
                          {item['agencyList'].map((item2, idx2) => {
                            return (
                              <li style={{ margin: '10px 0px' }} key={idx2}>
                                <span style={{ marginRight: '5px' }}><img src={Arrow} alt="" /></span>
                                <a onClick={() => { agencyChange(item['government_id'], item2['agency_id']) }}
                                  className={item2['agency_id'] == org['agency_id'] ? "active" : ""}>
                                  {item2['agency_name']}
                                </a>
                              </li>
                            )
                          })}
                        </ul>
                        : null
                      }
                    </li>
                  )
                })}
              </ul>
            </div>
          </div>
          <div className="right">
            <div className="flex equip-tab">
              <SubTitle explanation={"선택한 기관의 돌봄 대상자가 사용중인 장비 목록입니다."} />
              <div className="btn-wrap flex-end margin-bottom ">
                {/* <button className={"btn-small gray-btn"} onClick={() => {modalEquipmentOpen()}}>등록</button> */}
              </div>
            </div>
            {rentalContent}
          </div>
        </div>
      </div>
    )
  }];


  return (
    <main>
      <Modal open={modalEquipmentIsOpen} close={modalEquipmentClose} header="장비 등록">
        <div className="board-wrap">
          <div>
            <table className="flex70 margin-bottom detail-table">
              <tbody className="equipment-insert ">
                <tr>
                  <th><span style={{ color: "red" }}>*</span>종류</th>
                  <td>
                    <select>
                      <option value="SMART_PILLBOX" selected>스마트 약상자</option>
                      {/* <option value="ECG" disabled>심전도계</option>
											<option value="SPHYGMOMANOMETER" disabled>혈압계</option> */}
                    </select>
                  </td>
                </tr>
                <tr>
                  <th><span style={{ color: "red" }}>*</span>모델명</th>
                  <td>
                    <input type="text" placeholder="모델명을 입력해 주세요"
                      value={equipment['equipment_name']}
                      ref={el => equipmentRef.current['equipment_name'] = el}
                      onChange={(e) => equipmentValueChange('equipment_name', e.target.value)} />
                  </td>
                </tr>
                <tr>
                  <th><span style={{ color: "red" }}>*</span>시리얼넘버</th>
                  <td>

                    {CommonUtil.isEmpty(equipment['equipment_insert_datetime'])
                      ? <>
                        <input type="text" placeholder="S/N를 입력해 주세요"
                          style={{ width: 'calc(100% - 110px)' }}
                          value={equipment['equipment_serial_number']}
                          ref={el => equipmentRef.current['equipment_serial_number'] = el}
                          onChange={(e) => { equipmentValueChange('equipment_serial_number', e.target.value); setIsSerialNumberCheck(false); }}
                        />
                        <button className={"btn-small red-btn"} style={{ width: '110px' }} onClick={serialNumberCheck}>중복확인</button>
                      </>
                      : <input type="text"
                        value={equipment['equipment_serial_number']}
                        disabled={true}
                      />
                    }
                  </td>
                </tr>
                <tr>
                  <th>생산일자</th>
                  <td>
                    <input type="date"
                      value={equipment['equipment_product_date']}
                      ref={el => equipmentRef.current['equipment_product_date'] = el}
                      onChange={(e) => equipmentValueChange('equipment_product_date', e.target.value)} />
                  </td>
                </tr>
                <tr>
                  <th><span style={{ color: "red" }}>*</span>입고일자</th>
                  <td>
                    <input type="date"
                      value={equipment['equipment_stock_date']}
                      ref={el => equipmentRef.current['equipment_stock_date'] = el}
                      onChange={(e) => equipmentValueChange('equipment_stock_date', e.target.value)} />
                  </td>
                </tr>
                {CommonUtil.isEmpty(equipment['equipment_insert_datetime']) == false
                  ? <tr>
                    <th><span style={{ color: "red" }}>*</span>장비상태</th>
                    <td>
                      <div className="gender flex-start gap2">
                        {Object.keys(equipmentStates).map((key, idx) => {
                          return (
                            <div className="flex-start">
                              <input type="radio" name="equipment_state" id={key} key={key} value={key}
                                style={{ width: '25px' }}
                                checked={equipment['equipment_state'] == key}
                                onChange={(e) => { e.target.checked ? equipmentValueChange('equipment_state', e.target.value) : null }}
                              />
                              <label for={key}>{equipmentStates[key]}</label>
                            </div>
                          )
                        })}
                      </div>
                    </td>
                  </tr>
                  : null}
                <tr>
                  <th>시행기관 선택</th>
                  {/* <td>
                    {orgListOfHierarchy.map((item, idx) => {
                      return (
                        <select onChange={(e) => {
                          console.log('e.target.value : ', e.target.value);
                          equipmentValueChange('agency_id', e.target.value);
                        }}>
                          <option value="">시행기관을 선택해주세요.</option>
                          {item['agencyList'] != undefined && item['agencyList'] != null ?
                            item['agencyList'].map((item2, idx2) => {
                              return (
                                <option key={idx2} value={item2['agency_id']}
                                  selected={equipment['agency_id'] == item2['agency_id']}>
                                  {item2['agency_name']}
                                </option>
                              )
                            })
                            : null}
                        </select>
                      )
                    })}
                  </td> */}

                  <td>
                    <select onChange={(e) => {
                      console.log('e.target.value : ', e.target.value);
                      equipmentValueChange('agency_id', e.target.value);
                    }}>
                      <option value="">시행기관을 선택해주세요.</option>
                      {orgListOfHierarchy && orgListOfHierarchy[0] && orgListOfHierarchy[0]['agencyList'] != undefined ?
                        orgListOfHierarchy[0]['agencyList'].map((item2, idx2) => {
                          return (
                            <option key={idx2} value={item2['agency_id']}
                              selected={equipment['agency_id'] == item2['agency_id']}>
                              {item2['agency_name']}
                            </option>
                          )
                        })
                        : null}
                    </select>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div className="flex-center">
            {CommonUtil.isEmpty(equipment['equipment_insert_datetime'])
              ?
              !isEquipmentCheck ?
                <button className={"btn-small gray-btn"} onClick={equipmentInsert}>등록</button>
                :
                <button className={"btn-small gray-btn"} onClick={equipmentInsertUpdate}>등록</button>
              : <>
                <button className={"btn-small gray-btn"} onClick={equipmentUpdate}>수정</button>
                <button className={"btn-small red-btn"} onClick={equipmentDelete}>삭제</button>
              </>
            }
          </div>
        </div>
      </Modal>

      <Modal open={modalRentalIsOpen} close={modalRentalClose} header="장비 배포 시니어 선택">
        <div className="board-wrap">
          <table className={"protector-user"}>
            <thead>
              <tr>
                <th>No</th>
                <th>소속기관명</th>
                <th>이름</th>
                <th>생년월일</th>
                <th>성별</th>
                <th>배포</th>
              </tr>
            </thead>
            <tbody>
              {mySenior.seniorList.map((item, idx) => {
                return (
                  <tr key={idx}>
                    <td data-label="No">{mySenior.seniorListCount - idx - (mySenior.search.currentPage - 1) * mySenior.search.perPage}</td>
                    <td data-label="소속기관명">{item['agency_name']}</td>
                    <td data-label="이름">{item['user_name']}</td>
                    <td data-label="생년월일">{item['user_birth']}</td>
                    <td data-label="성별">{item['user_gender']}</td>
                    <td data-label="배포">
                      <button className="btn-small gray-btn" onClick={() => { equipmentRentalInsert(item) }}>배포하기</button>
                    </td>
                  </tr>
                )
              })}
              {CommonUtil.isEmpty(mySenior.seniorList) ?
                <tr>
                  <td colSpan={8}>조회된 데이터가 없습니다</td>
                </tr>
                : null}
            </tbody>
          </table>
          <Pagination
            currentPage={mySenior.search.currentPage}
            perPage={mySenior.search.perPage}
            totalCount={mySenior.seniorListCount}
            maxRange={5}
            click={mySeniorSelectList}
          />
        </div>
      </Modal>

      {/* <Modal open={modalDeliveryIsOpen} close={modalDeliveryClose} header="납품 기관 선택">
				<div className="board-wrap">
					<div>
						<div style={{textAlign:'left', fontSize: '16px',margin:'2rem 0'}} className="category">
							<div className="search-management flex-end margin-bottom2 margin-top">						
								<div style={{width: '90px', fontWeight: '600'}}>납품일자</div>
								<input type="date"
									value={equipmentDelivery['delivery_date']}
									onChange={(e) => {
										equipmentDelivery['delivery_date'] = e.target.value;
										setEquipmentDelivery({...equipmentDelivery})}
									}/>	
							</div>
							<ul style={{marginLeft: '15px'}}>
							{orgListOfHierarchy.map((item, idx) => { return (
								<li style={{margin: '10px 0px'}} key={idx}>
									<span style={{marginRight: '5px'}}><img src={House} alt="" /></span>
									<a>{item['government_name']}</a>
									<button onClick={() => {
										if (confirm(`'${item['government_name']}'에 장비를 납품하시겠습니까?`)) {
											equipmentDeliveryInsert(item['government_id'])
										} else {
											return;
										}
									}}>선택</button>
								</li>
							)})}
							</ul>
						</div>
					</div>
				</div>
			</Modal> */}

      <div className="search-management flex-end margin-bottom2 margin-top gap">
        <select style={{ maxWidth: '150px' }}
          onChange={(e) => equipmentSearchChange('equipment_state', e.target.value)}>
          <option value="">상태</option>
          {Object.keys(equipmentStates).map((key, idx) => {
            return (
              <option key={key} value={key}>
                {equipmentStates[key]}
              </option>
            )
          })}
        </select>
        <select style={{ maxWidth: '150px' }}
          onChange={(e) => equipmentSearchChange('searchType', e.target.value)}>
          <option value="">전체</option>
          <option value="equipment_name">모델명</option>
          <option value="equipment_serial_number">시리얼넘버</option>
        </select>
        <input type="text"
          value={equipmentSearch.searchText}
          onChange={(e) => equipmentSearchChange('searchText', e.target.value)}
          onKeyUp={(e) => equipmentSearchingEnter(e.key)}
        />
        <button className={"btn-small gray-btn"} style={{ maxWidth: '150px' }} onClick={equipmentSearching}>검색</button>
      </div>

      <div className="tab-container">
        <ul className="tab-menu flex-start">
          {tab.map((item, idx) => {
            return (
              <li onClick={() => setTabIndex(idx)} className={idx == tabIndex ? 'active' : null}>
                {item.title}
              </li>
            )
          })}
        </ul>
        <div className="content-wrap">
          <ul className="tab-content">
            <li>
              {tab[tabIndex].content}
            </li>
          </ul>
        </div>
      </div>
    </main >
  );
}
