import React, { useState } from "react";
import { useSelector } from "react-redux";



import { MapContainer, TileLayer, LayerGroup, Marker, Circle, CircleMarker, Tooltip, Popup, useMap } from 'react-leaflet';
import L, { CRS, latLng, bounds } from 'leaflet';


import Title from "../../component/Title.jsx";
/* import Map from "../../component/chart/Map.jsx"; */
import Chart5 from "../../component/chart/Chart5.jsx";
import Chart5_agencyadmin from "../../component/chart/Chart5_agencyadmin.jsx";
import Chart8 from "../../component/chart/Chart8.jsx";
import Chart2_govern from "../../component/chart/Chart2_govern.jsx";
import Donut1_govern from "../../component/chart/Donut1_govern.jsx";
import RowChart_govern from "../../component/chart/RowChart_govern.jsx";
import AddCircleIcon from "@mui/icons-material/AddCircle";
import BatteryCharging20Icon from '@mui/icons-material/BatteryCharging20';
import DeviceThermostatIcon from '@mui/icons-material/DeviceThermostat';
import MedicationIcon from '@mui/icons-material/Medication';
import ElderlyIcon from '@mui/icons-material/Elderly';

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

import "leaflet/dist/leaflet.css";

export default function Main_agencyAdmin() {

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

  const [cityName, setCityName] = useState(state.loginUser['agency_name']);

  //대상자(시니어) 목록 조회  
  const [seniorNum, setSeniorNum] = React.useState();
  const [senior, setSenior] = React.useState({ userList: [], userListCount: 0 });
  const seniorSelectList = () => {
    fetch("/user/userSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
        'authority': 'ROLE_SENIOR',
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("대상자(시니어) 목록 조회 : ", data);
      setSenior(data);
      data.userList.map((item, idx) => {
        console.log(">>", item['user_id'])
      })
    }).catch((error) => {
      console.log('seniorSelectList() /user/userSelectList.json error : ', error);
    });
  }

  //전체 대상자(시니어) 수 조회
  const [seniorCount, setSeniorCount] = React.useState(0);
  const seniorCountTotal = () => {
    fetch("/stats/agencySeniorCount.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("전체 대상자(시니어) 수 조회 : ", data);
      setSeniorCount(data);
    }).catch((error) => {
      console.log('agencySeniorCount() /stats/agencySeniorCount.json error : ', error);
    });
  }

  //온도 위험 대상자(시니어) 수 조회
  const [temperatureCount, setTemperatureCount] = React.useState(0);
  const temperatureRiskCount = () => {
    fetch("/stats/agencyTemperatureRisk.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("온도 위험 대상자(시니어) 수 조회 : ", data);
      setTemperatureCount(data);
    }).catch((error) => {
      console.log('temperatureRiskCount() /stats/agencyTemperatureRisk.json error : ', error);
    });
  }

  //배터리 부족 대상자(시니어) 수 조회
  const [batteryCount, setbatteryCount] = React.useState(0);
  const batteryRiskCount = () => {
    fetch("/stats/agencyBatteryRisk.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("배터리 부족 대상자(시니어) 수 조회 : ", data);
      setbatteryCount(data);
    }).catch((error) => {
      console.log('batteryRiskCount() /stats/agencyBatteryRisk.json error : ', error);
    });
  }

  //월별 방문 횟수 조회
  const [visit, setVisit] = React.useState([]);
  const visitByMonthList = () => {
    fetch("/stats/visitByMonthList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("월별 방문 횟수 조회 : ", data);
      setVisit(data);
    }).catch((error) => {
      console.log('visitByMonthList() /stats/visitByMonthList.json error : ', error);
    });
  }

  //생활보호사별 대상자(시니어) 등록 현황
  const [seniorEnroll, setSeniorEnroll] = React.useState([]);
  const seniorByAgent = () => {
    fetch("/stats/seniorByAgent.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        'agency_id': state.loginUser['agency_id'],
      }),
    }).then((response) => response.json()).then((data) => {
      data.map((item, idx) => {
        if (item['agent_name'] == null) {
          item['agent_name'] = "미배정";
        }
      })
      console.log("생활보호사별 시니어 등록 현황 : ", data);
      setSeniorEnroll(data);
    }).catch((error) => {
      console.log('seniorByAgent() /stats/seniorByAgent.json error : ', error);
    });
  }

  const iconHouse = new L.Icon({
    iconUrl: '/client/resources/files/images/house.png',
    iconRetinaUrl: '/client/resources/files/images/house.png',
    iconSize: [20, 20],
    className: 'leaflet-background-radius-icon'//leaflet-div-icon
  });

  //특정 대상자의 최근 복용률
  const [medicationSelectListByNew, setMedicationSelectListByNew] = React.useState([]);
  //특정 대상자의 최근 복용률 조회
  const seniorMedicationSelectListByNew = () => {
    fetch("/user/seniorMedicationSelectListByNew.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({ "agency_id": state.loginUser['agency_id'] }),
    }).then((response) => response.json()).then((data) => {
      console.log("seniorMedicationSelectListByNew : ", data);
      setMedicationSelectListByNew(data)
    }).catch((error) => {
      console.log('seniorMedicationSelectListByNew() /user/seniorMedicationSelectListByNew.json error : ', error);
    });
  };

  // 복용률 목록
  const [medicationSelectListByMonth, setMedicationSelectListByMonth] = React.useState([]);
  const [medicationSelectListByYear, setMedicationSelectListByYear] = React.useState([]);
  // 복용률 목록 조회
  const seniorMedicationSelectListByMonth = () => {
    let totalYearArr = [];
    let yearArr = [];

    fetch("/user/seniorMedicationSelectListByMonth.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({ "agency_id": state.loginUser['agency_id'] }),
    }).then((response) => response.json()).then((data) => {
      data.map((item, idx) => {
        item['year'] = item['medication_default_date'].substr(0, 4);
        item['month'] = item['medication_default_date'].substr(5, 2);
        totalYearArr.push(item['medication_default_date'].substr(0, 4));
        item['date'] = new Date(item['medication_default_date']).getTime();
      })

      const setYearArr = [...new Set(totalYearArr)];
      console.log("totalYearArr: ", setYearArr);

      setYearArr.map((year, yearIdx) => {
        let sum = 0;
        let count = 0;
        let avg = 0;

        let monthArr = ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'];

        data.map((item, idx) => {
          if (item['year'] == year) {
            sum += item['average'];
            count++;
            monthArr[Number(item['month'])] = item['average'];
          }
        })

        avg = parseInt(sum / count);
        yearArr.push({ "year": [year], "average": avg, "data": monthArr });
      })

      console.log("yearArr : ", yearArr);
      setMedicationSelectListByYear(yearArr);

      console.log("seniorMedicationSelectListByMonth : ", data);
      setMedicationSelectListByMonth(data);
    }).catch((error) => {
      console.log('seniorMedicationSelectListByMonth() /user/seniorMedicationSelectListByMonth.json error : ', error);
    });
  };

  React.useEffect(() => {
    seniorSelectList();
    seniorCountTotal();
    temperatureRiskCount();
    batteryRiskCount();
    visitByMonthList();
    seniorByAgent();
    seniorMedicationSelectListByNew();
    seniorMedicationSelectListByMonth();
  }, []);

  return (
    <main>
      <div className="main-grid-government">
        <div className="sub-grid-government">
          <ul className="content-box statistics-govern" background="#f7acba">
            <li>
              <p><ElderlyIcon sx={{ width: "50px", height: "50px", color: "#ffffff", background: "#bf0629", borderRadius: "50px" }} /></p>
              <p>{cityName} 전체 대상자</p>
              <p>{seniorCount}</p>
            </li>
          </ul>
          <ul className="content-box statistics-govern" background="#8ef3d1">
            <li>
              <p><MedicationIcon sx={{ width: "50px", height: "50px", color: "#ffffff", background: "#076143", borderRadius: "50px" }} /></p>
              <p>{cityName} 미복약 위험 대상자</p>
              <p>0</p>
            </li>
          </ul>
          <ul className="content-box statistics-govern" background="#ebe7b9" >
            <li>
              <p><DeviceThermostatIcon sx={{ width: "50px", height: "50px", color: "#ffffff", background: "#f1de05", borderRadius: "50px" }} /></p>
              <p>{cityName} 댁내 온도 위험 대상자</p>
              <p>{temperatureCount}</p>
            </li>
          </ul>
          <ul className="content-box statistics-govern" background="#5f9af3">
            <li>
              <p><BatteryCharging20Icon sx={{ width: "50px", height: "50px", color: "#ffffff", background: "#5f9af3", borderRadius: "50px" }} /></p>
              <p>{cityName} 배터리 부족 대상자 </p>
              <p>{batteryCount}</p>
            </li>
          </ul>
        </div>
        <div className="content-box combine-left-government combine-bottom-government2 main-main">
          <div className="flex">
            <Title title={"지역별 케어 대상자 분포 현황"} explanation={"지역 선택 시 해당 지역의 대상자리스트가 보여집니다."} />
          </div>
          <div style={{ height: 'calc(100% - 60px)' }}>
            <MapContainer center={latLng(35.8713802646197, 128.601805491072)} zoom={13} scrollWheelZoom={true} style={{ height: '100%' }}>
              <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              />
              {/* <Marker position={[128.601405491072, 35.8913802646197]}>
                        <Popup>
                            A pretty CSS3 popup. <br /> Easily customizable.
                        </Popup>
                        </Marker> */}

              <LayerGroup>
                {senior.userList.map((item, idx) => {
                  return item['y'] != null && item['x'] != null ? (
                    <Marker position={[item['y'], item['x']]} icon={iconHouse}>
                      <Popup>
                        <div>
                          {item['user_name']}({item['user_birth']} - {item['user_gender']})
                        </div>
                      </Popup>
                    </Marker>
                  ) : null
                })}
              </LayerGroup>
            </MapContainer>
          </div>
          {/* <Map setCityName={setCityName} /> */}
        </div>
        <div className="content-box combine-all-government combine-bottom-government2 visitlist">
          <div className="flex">
            <Title title={`${cityName} 복용률 순위`} explanation={""} />
          </div>
          <div style={{ height: 'calc(100% - 60px)' }}>
            <Chart8 data={medicationSelectListByNew} />
          </div>
        </div>
        <div className="content-box combine-left-government2">
          <div className="flex">
            <Title title={`${cityName} 복용률 평균`} explanation={"해당 지역의 대상자 복용률이 그래프로 보여집니다."} />
          </div>
          <Chart2_govern data={medicationSelectListByMonth} />
        </div>
        <div className="content-box combine-right-government2">
          <div className="flex">
            <Title title={`${cityName} 월별 방문 횟수`} explanation={"최근 6개월간 방문 횟수의 변화를 확인할 수 있습니다."} />
          </div>
          <RowChart_govern data={visit} />
        </div>
        <div className="content-box combine-right-government">
          <div className="flex">
            <Title title={`생활보호사별 대상자 등록 현황`} explanation={"약상자 사용자의 데이터 차트가 보여집니다."} />
          </div>
          <Chart5_agencyadmin data={seniorEnroll} />
        </div>
        <div className="content-box span4">
          <table className="visit-data-table">
            <thead>
              <tr>
                <th>년도</th>
                <th>총계</th>
                <th>1월</th>
                <th>2월</th>
                <th>3월</th>
                <th>4월</th>
                <th>5월</th>
                <th>6월</th>
                <th>7월</th>
                <th>8월</th>
                <th>9월</th>
                <th>10월</th>
                <th>11월</th>
                <th>12월</th>
              </tr>
            </thead>
            <tbody>
              {medicationSelectListByYear.map((item, idx) => {
                return (
                  <tr>
                    <td>{item['year']}</td>
                    <td>{item['average'] == '-' ? '-' : item['average'] + '%'}</td>
                    {CommonUtil.isEmpty(item['data']) == false ? (
                      item['data'].map((item1, idx1) => {
                        return (
                          <>
                            <td>{item1 == '-' ? '-' : item1 + '%'}</td>
                          </>
                        )
                      })
                    ) : null}
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>
    </main>
  );
}
