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

import SubTitle from "../../component/SubTitle.jsx";
import DetailTitle from "../../component/DetailTitle.jsx";
import Pagination from "../../component/Pagination.jsx";

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


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

  //전역 변수 저장 객체
  const state = useSelector((state) => { return state });

  //검색(엔터)
  const searchingEnter = (key) => {
    if (key == 'Enter') {
      searching();
    } else {
      return;
    }
  }
  //검색
  const searching = () => {
    if (CommonUtil.isEmpty(state.loginUser) == false
      && state.loginUser['authority'] == 'ROLE_AGENCY' && isMySenior) {
      senior.search['agent_id'] = state.loginUser['user_id'];
    } else {
      senior.search['agent_id'] = null;
    }

    setSenior({ ...senior });

    seniorSelectList(1);
  }

  const [seniorNum, setSeniorNum] = React.useState();
  const [isMySenior, setIsMySenior] = React.useState(true);
  React.useEffect(() => {
    searching();
  }, [isMySenior])
  //보호사(간호사)의 돌봄 대상자(시니어)
  const [senior, setSenior] = React.useState({
    seniorList: [], seniorListCount: 0, search: {
      'government_id': CommonUtil.isEmpty(state.loginUser) ? null : state.loginUser['government_id'],
      'agency_id': CommonUtil.isEmpty(state.loginUser) ? null : state.loginUser['agency_id'],
      'searchType': null,
      'searchText': null,
      'currentPage': 1,
      'perPage': 10,
    }
  });
  //보호사(간호사)의 돌봄 대상자(시니어) 목록 조회
  const seniorSelectList = (currentPage) => {
    senior.search.currentPage = CommonUtil.isEmpty(currentPage) ? 1 : currentPage;

    fetch("/user/seniorSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(senior.search),
    }).then((response) => response.json()).then((data) => {
      data.search = senior.search;
      data.seniorList.map((item, idx) => {
        setSeniorNum(item);
        seniorMedicationSelectList(item);
        seniorTemperatureSelectListByDay(item);
      })
      console.log("돌봄 대상자(시니어) 목록 조회 : ", data);
      setSenior(data);
    }).catch((error) => {
      console.log('seniorSelectList() /user/seniorSelectList.json error : ', error);
    });
  }

  //특정 대상자의 실제 복약 정보
  const [seniorMedicationList, setSeniorMedicationList] = React.useState([]);
  const [showMedicationTimeCode, setShowMedicationTimeCode] = React.useState({});
  //특정 대상자의 실제 복약 정보 목록 조회
  const seniorMedicationSelectList = (seniorNum) => {
    fetch("/user/seniorMedicationSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorNum),
    }).then((response) => response.json()).then((data) => {
      setSeniorMedicationList(data, seniorNum);
      seniorMedicationSelectListByDay(data, seniorNum);
    }).catch((error) => {
      console.log('seniorMedicationSelectList() /user/seniorMedicationSelectList.json error : ', error);
    });
  };

  //특정 대상자의 일별, 복약시간별 복약 목록
  const [stackChartData, setStackChartData] = React.useState([]);
  //특정 대상자의 일별, 복약시간별 복약 목록 조회
  const seniorMedicationSelectListByDay = (seniorMedicationList, seniorNum) => {
    fetch("/user/seniorMedicationSelectListByDay.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorNum),
    }).then((response) => response.json()).then((data) => {
      let showMedicationTimeCode = {};
      for (let i = 0; i < seniorMedicationList.length; i++) {
        showMedicationTimeCode[seniorMedicationList[i]] = true;
      }
      setShowMedicationTimeCode(showMedicationTimeCode);

      if (CommonUtil.isEmpty(data) == false) {
        let _stackChartData = [];
        for (let i = data.length - 1; i >= data.length - 3; i--) {
          let sum = 0;      // 실제 복약량
          let counter = 0;  // 복약해야하는 양
          let chartData = {
            xName: data[i]['medication_default_date']
          };
          for (let j = 0; j < data[i]['medication_time_code_list'].length; j++) {
            if (CommonUtil.isEmpty(showMedicationTimeCode[data[i]['medication_time_code_list'][j]]) == false) {
              chartData[data[i]['medication_time_code_list'][j]] = data[i]['medication_time_code_count_list'][j];
              counter++;
              if (i > 0) {
                sum += data[i]['medication_time_code_count_list'][j];
              }
            } else {
              continue;
            }
          }
          _stackChartData.push({ "sum": sum, "total": counter })
        }
        seniorNum.seniorMedicationList = _stackChartData;
      }
    }).catch((error) => {
      console.log('seniorMedicationSelectListByDay() /user/seniorMedicationSelectListByDay.json error : ', error);
    });
  };


  const seniorTemperatureList = ['02:00', '10:00', '14:00', '23:00']

  //특정 대상자의 일별, 시간별 온도 목록
  const [seniorTemperatureListByDay, setSeniorTemperatureListByDay] = React.useState([]);
  const [stackTemperatureData, setStackTemperatureData] = React.useState([]);
  //특정 대상자의 일별, 시간별 온도 목록 조회
  const seniorTemperatureSelectListByDay = (seniorNum) => {
    fetch("/user/seniorTemperatureSelectListByDay.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorNum),
    }).then((response) => response.json()).then((data) => {
      console.log("seniorTemperatureListByDay data : ", data);
      setSeniorTemperatureListByDay(data);

      if (CommonUtil.isEmpty(data) == false) {
        let _stackTemperatureData = [];
        let chartData = {};
        for (let i = data.length - 1; i >= (data.length > 12 ? data.length - 12 : 0); i--) {
          chartData = {
            xName: data[i]['temperature_date'],
          };
          chartData['temperature'] = data[i]['temperature_data'];
          chartData['time'] = data[i]['temperature_time'];

          if (data[i]['temperature_date'].substr(5, 2) >= 11 || data[i]['temperature_date'].substr(5, 2) <= 2) {
            _stackTemperatureData.unshift(chartData);
          } else {
            _stackTemperatureData.push(chartData);
          }
        }

        seniorNum.seniorTemperatureList = _stackTemperatureData;
        console.log('_stackTemperatureData : ', _stackTemperatureData);
      }
    }).catch((error) => {
      console.log('seniorTemperatureSelectListByDay() /user/seniorTemperatureSelectListByDay.json error : ', error);
    });
  };

  const Temperature = ({ data }) => {
    let seniorTemperature = [];
    if (data['seniorTemperatureList'] && data['seniorTemperatureList'].length > 0) {
      data['seniorTemperatureList'].map((data, dataIdx) => {
        seniorTemperature.push(data['temperature']);
      })
      if (data['seniorTemperatureList'].length < 12) {
        for (let i = 0; i < 12 - data['seniorTemperatureList'].length; i++) {
          seniorTemperature.push('-');
        }
      }
    }

    console.log(">>", seniorTemperature)

    if (seniorTemperature.length > 0) {
      return (
        seniorTemperature.map((item, idx) => {
          return (
            <td>{item}</td>
          )
        })
      )
    } else {
      return (
        <td colSpan={12}>집계된 정보가 없습니다.</td>
      )
    }
  }

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


  //현재 탭 Index
  const [tabIndex, setTabIndex] = React.useState(0);
  //탭 초기화
  const tab = [{
    title: `복약관리`,
    content: (
      <div>
        <div className="flex equip-tab">
          <SubTitle explanation={"돌봄 대상자 클릭 시, 상세페이지로 이동합니다."} />
        </div>
        <table className={"protector-user"}>
          <thead>
            <tr>
              <th rowSpan={2}>No</th>
              <th rowSpan={2}>소속기관명</th>
              <th rowSpan={2}>이름</th>
              <th rowSpan={2}>생년월일</th>
              <th rowSpan={2}>성별</th>
              <th rowSpan={2}>연락처</th>
              <th colSpan={3}>최근복약률(집계/전체)</th>
            </tr>
            <tr>
              <th>최근 하루 전</th>
              <th>최근 이틀 전</th>
              <th>최근 사흘 전</th>
            </tr>
          </thead>
          <tbody>
            {senior.seniorList.map((item, idx) => {
              return (
                <tr key={idx} onClick={() => {
                  navigate("/HealthcareSelectOne", {
                    state: {
                      'senior_id': item['senior_id'],
                      'user_name': item['user_name'],
                    }
                  })
                }}>
                  <td data-label="No">{senior.seniorListCount - idx - (senior.search.currentPage - 1) * senior.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="연락처">{item['user_phonenumber']}</td>
                  {
                    item['seniorMedicationList'] && item['seniorMedicationList'].length > 0 ?
                      item['seniorMedicationList'].map((date, dataIdx) => {
                        return (
                          <td data-label="최근복약률">
                            {date['sum']}/{date['total']}
                          </td>
                        )
                      })
                      : <td colSpan={3}>집계된 정보가 없습니다.</td>}
                </tr>
              )
            })}
            {CommonUtil.isEmpty(senior.seniorList) ?
              <tr>
                <td colSpan={18}>조회된 데이터가 없습니다</td>
              </tr>
              : null}
          </tbody>
        </table>
        <Pagination
          currentPage={senior.search.currentPage}
          perPage={senior.search.perPage}
          totalCount={senior.seniorListCount}
          maxRange={5}
          click={seniorSelectList}
        />
      </div >
    )
  }, {
    title: `댁내온도관리`,
    content: (
      <div>
        <div className="flex equip-tab">
          <SubTitle explanation={"돌봄 대상자 클릭 시, 상세페이지로 이동합니다."} />
        </div>
        <table className={"protector-user"}>
          <thead>
            <tr>
              <th rowSpan={2}>No</th>
              <th rowSpan={2}>소속기관명</th>
              <th rowSpan={2}>이름</th>
              <th rowSpan={2}>생년월일</th>
              <th rowSpan={2}>성별</th>
              <th rowSpan={2}>연락처</th>
              <th colSpan={12}>최근온도 (℃)</th>
            </tr>
            <tr>
              <th colSpan={4}>최근 하루 전</th>
              <th colSpan={4}>최근 이틀 전</th>
              <th colSpan={4}>최근 사흘 전</th>
            </tr>
          </thead>
          <tbody>
            {senior.seniorList.map((item, idx) => {
              return (
                <tr key={idx} onClick={() => {
                  navigate("/HealthcareSelectOne", {
                    state: {
                      'senior_id': item['senior_id'],
                      'user_name': item['user_name'],
                    }
                  })
                }}>
                  <td data-label="No">{senior.seniorListCount - idx - (senior.search.currentPage - 1) * senior.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="연락처">{item['user_phonenumber']}</td>
                  <Temperature data={item} />
                </tr>
              )
            })}
            {CommonUtil.isEmpty(senior.seniorList) ?
              <tr>
                <td colSpan={18}>조회된 데이터가 없습니다</td>
              </tr>
              : null}
          </tbody>
        </table>
        <Pagination
          currentPage={senior.search.currentPage}
          perPage={senior.search.perPage}
          totalCount={senior.seniorListCount}
          maxRange={5}
          click={seniorSelectList}
        />
      </div>
    )
  }, {
    title: `방문/전화 관리`,
    content: (
      <div>
        <div className="flex equip-tab">
          <SubTitle explanation={"돌봄 대상자 클릭 시, 상세페이지로 이동합니다."} />
        </div>
        <table className={"protector-user"}>
          <thead>
            <tr>
              <th>No</th>
              <th>소속기관명</th>
              <th>이름</th>
              <th>생년월일</th>
              <th>성별</th>
              <th>연락처</th>

              {/* <th>최근방문일</th>
							<th>방문목적</th> */}
            </tr>
          </thead>
          <tbody>
            {senior.seniorList.map((item, idx) => {
              return (
                <tr key={idx} onClick={() => {
                  navigate("/HealthcareSelectOne", {
                    state: {
                      'senior_id': item['senior_id'],
                      'user_name': item['user_name'],
                    }
                  })
                }}>
                  <td data-label="No">{senior.seniorListCount - idx - (senior.search.currentPage - 1) * senior.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="연락처">{item['user_phonenumber']}</td>

                  {/* <td>2023-04-11</td>
							<td>정기방문</td> */}
                </tr>
              )
            })}
            {CommonUtil.isEmpty(senior.seniorList) ?
              <tr>
                <td colSpan={6}>조회된 데이터가 없습니다</td>
              </tr>
              : null}
          </tbody>
        </table>
        <Pagination
          currentPage={senior.search.currentPage}
          perPage={senior.search.perPage}
          totalCount={senior.seniorListCount}
          maxRange={5}
          click={seniorSelectList}
        />
      </div>
    )
  }];

  return (
    <main>
      <div className="search-management flex-start margin-bottom2">
        <select style={{ maxWidth: '150px' }}
          onChange={(e) => { senior.search.searchType = e.target.value; setSenior({ ...senior }); }}>
          <option value="" selected={CommonUtil.isEmpty(senior.search.searchType)}>전체</option>
          <option value="user_name" selected={senior.search.searchType == 'user_name'}>이름</option>
          <option value="user_id" selected={senior.search.searchType == 'user_id'}>아이디</option>
          <option value="user_phonenumber" selected={senior.search.searchType == 'user_phonenumber'}>연락처</option>
        </select>
        <input type="text" className="senior-search" value={senior.search.searchText}
          onChange={(e) => { senior.search.searchText = e.target.value; setSenior({ ...senior }); }}
          onKeyUp={(e) => searchingEnter(e.key)} />
        <button className="btn-small gray-btn" onClick={searching}>검색</button>
      </div>

      <div className="content-wrap">
        <DetailTitle contentTitle={"대상자의 복약 / 댁내온도 / 방문전화 관리를 할 수 있습니다."} />

        <div style={{ height: "calc(100% - 61px)" }}>
          <div className="right" style={{ height: "100%", }}>
            <div style={{ height: "100%" }}>
              <div className="tab-container" style={{ marginTop: "5rem" }}>
                {/* {CommonUtil.isEmpty(state.loginUser) == false && state.loginUser['authority'] == 'ROLE_AGENCY' ?
                                <div className="flex-end margin-bottom">
                                    <div className="flex searchselect" style={{width: 'auto'}}>

                                        <input type="radio" id="my_senior" name="senior" checked={isMySenior}
                                            onChange={(e) => {e.target.checked ? setIsMySenior(true) : null}}/>
                                        <label for="my_senior" style={{marginRight: '3rem'}}>나의 대상자 보기</label>

                                        <input type="radio" id="all_senior" name="senior" checked={!isMySenior}
                                            onChange={(e) => {e.target.checked ? setIsMySenior(false) : null}}/>
                                        <label for="all_senior" style={{marginRight: '0'}}>전체 대상자 보기</label>

                                    </div>
                                </div>
                                :null} */}
                <ul className="tab-menu flex-end">
                  {tab.map((item, idx) => {
                    return (
                      <li onClick={() => setTabIndex(idx)} className={idx == tabIndex ? 'active' : null}>
                        {item.title}
                      </li>
                    )
                  })}
                </ul>
                <div className="content-wrap userlist">

                  <ul className="tab-content">
                    <li>
                      {tab[tabIndex].content}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}
