/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-06-25 17:01:46
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-03-13 18:07:26
 * @FilePath: /MediScreen/src/layouts/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import styles from './index.less';
import { useEffect, useRef, useState } from 'react';

import BarChartComponent from '@/components/BarChartComponent';

import NumberAnimation from '@/components/NumberAnimation';
import CircularProgressBar from '@/components/CircularProgressBar';
import CustomBarLineChart from '@/components/CustomBarLineChart';

import TimeSeriesChart from '@/components/TimeSeriesChart';
import SingleBarChartComponent from '@/components/SingleBarChartComponent';
import { Link, useLocation } from 'umi';

import request from '@/utils/request';
import SmoothLineChart from '@/components/SmoothLineChart';
import BarChartZuhe from '@/components/BarChartZuhe';

// 获取当前完整时间，格式为 "YYYY-MM-DD HH:MM"
function getCurrentFormattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取当前日期，格式为 "YYYY-MM-DD"
function getCurrentFormattedDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const defaultDate = getCurrentFormattedDate();

const convertObjectToArray = (dataObject: any) => {
  if (!dataObject) return [];
  return Object.keys(dataObject).map(key => ({
    label: key,
    prePharmacistCount: dataObject[key].prePharmacistCount,
    disPharmacistCount: dataObject[key].disPharmacistCount,
    totalCount: dataObject[key].totalCount
  }));
};

const convertDataToArray = (dataObject: { [x: string]: any; }) => {
  if (!dataObject) return [];
  return Object.keys(dataObject).map(key => ({
    name: key,
    value: dataObject[key]
  }));
};

export default function Index() {

  const [time, setTime] = useState(getCurrentFormattedTime());
  const location = useLocation();
  const [drugStock, set_drugStock] = useState<undefined | any>(undefined);
  const [taskTimeDistribution, set_taskTimeDistribution] = useState<number[]>([]);
  const [drugTop10, set_drugTop10] = useState<any[]>([]);
  const [pharmacyOperationStatistics, set_pharmacyOperationStatistics] = useState<any>(undefined);
  const [windowMonitoring, set_windowMonitoring] = useState<any>(undefined);
  const [prescriptionTimeCount, set_prescriptionTimeCount] = useState<any>(undefined);
  const [pharmacistWorkloadStatistics, set_pharmacistWorkloadStatistics] = useState<any>(undefined);
  const [equipmentDrugExpire, set_equipmentDrugExpire] = useState<any>(undefined);
  const [departmentPrescriptionTop10, set_departmentPrescriptionTop10] = useState<any>(undefined);
  const [refreshRates, setRefreshRates] = useState<any[]>([]);
  const [hospInfo, set_hospInfo] = useState<any>(undefined);
  const [date, set_date] = useState<string|undefined>(defaultDate);

  const getRefreshRates = async () => {
    const response: any[] = await request.get(`/dashBoard/getDict?dictCode=refresh_rate`);
    if (response) {
      setRefreshRates(response);
    }
  };

  const getHospInfo = async () => {
    const response = await request.get(`/dashBoard/getSysParameter?parameterCode=HOSPITAL_NAME`);
    if (response) {
      set_hospInfo(response);
    }
  };
  // 当 DEFAULT_DATE 已关闭时直接使用当前日期
  const getDate = async () => {
    const response: any = await request.get(`/dashBoard/getSysParameter?parameterCode=DEFAULT_DATE`);
    if (response) {
      set_date(response.value ? response.value : defaultDate);
    } else {
      set_date(defaultDate);
    }
  };

  const getDrugsStock = async (date:string) => {
    const response = await request.get(`/dashBoard/drugStock?date=${date}`);
    if (response) {
      set_drugStock(response);
    }
  };
  const gettaskTimeDistribution = async (date:string) => {
    const response: any = await request.get(`/dashBoard/taskTimeDistribution?date=${date}`);
    if (response) {
      const data = [response.lessFiveCount, response.lessTenCount, response.lessFifteenCount, response.lessThirtyCount, response.lessSixtyCount,]
      set_taskTimeDistribution(data);
    }
  };

  const getDrugTop10 = async (date:string) => {
    const response: any[] = await request.get(`/dashBoard/drugTop10?date=${date}`);
    if (response) {
      set_drugTop10(response);
    }
  };

  const getPharmacyOperationStatistics = async (date:string) => {
    const response = await request.get(`/dashBoard/pharmacyOperationStatistics?date=${date}`);
    if (response) {
      set_pharmacyOperationStatistics(response);
    }
  };

  const getWindowMonitoring = async (date:string) => {
    const padZero = (num: number) => (num < 10 ? '0' : '') + num;  // 补零函数
    const hours = padZero(new Date().getHours());
    const minutes = padZero(new Date().getMinutes());
    const seconds = padZero(new Date().getSeconds());
    const _date = `${date} ${hours}:${minutes}:${seconds}`
    const response = await request.get(`/dashBoard/windowMonitoring?dateTime=${_date}`);
    if (response) {
      set_windowMonitoring(response);
    }
  };

  const getPrescriptionTimeCount = async (date:string) => {
    const response = await request.get(`/dashBoard/prescriptionTimeCount?date=${date}`);
    if (response) {
      set_prescriptionTimeCount(response);
    }
  };

  const getPharmacistWorkloadStatistics = async (date:string) => {
    const response = await request.get(`/dashBoard/PharmacistWorkloadStatistics?date=${date}`);
    if (response) {
      set_pharmacistWorkloadStatistics(response);
    }
  };

  const getEquipmentDrugExpire = async (date:string) => {
    const response = await request.get(`/dashBoard/equipmentDrugExpire?date=${date}`);
    if (response) {
      set_equipmentDrugExpire(response);
    }
  };
  const getDepartmentPrescriptionTop10 = async (date:string) => {
    const response = await request.get(`/dashBoard/departmentPrescriptionTop10?date=${date}`);
    if (response) {
      set_departmentPrescriptionTop10(response);
    }
  };

  // 定义定时器的设置函数
  const safeInterval = (
    fn: Function,
    delay: number | undefined,
    defaultDelay: number
  ): number => {
    if (delay && !isNaN(delay) && delay > 0) {
      return setInterval(fn, delay * 1000) as unknown as number; // 强制转换为 number
    } else {
      return setInterval(fn, defaultDelay) as unknown as number; // 强制转换为 number
    }
  };

  useEffect(() => {
    // 获取刷新频率和医院信息，并获取初始日期
    getRefreshRates();
    getHospInfo();
    getDate();

    // 每分钟更新一次当前时间
    const intervalId = setInterval(() => {
      setTime(getCurrentFormattedTime());
    }, 60000); // 每分钟更新一次

    return () => {
      clearInterval(intervalId); // 组件卸载时清除计时器
    };
  }, []);

  // 定时检测日期是否跨天，若跨天则更新 date 状态
  useEffect(() => {
    const dateInterval = setInterval(() => {
      const currentDate = getCurrentFormattedDate();
      if (currentDate !== date) {
        set_date(currentDate);
      }
    }, 60000); // 每60秒检测一次
    return () => clearInterval(dateInterval);
  }, [date]);

  useEffect(() => {
    if(date){
      getDrugsStock(date);
      gettaskTimeDistribution(date);
      getDrugTop10(date);
      getPharmacyOperationStatistics(date);
      getWindowMonitoring(date);
      getPrescriptionTimeCount(date);
      getPharmacistWorkloadStatistics(date);
      getEquipmentDrugExpire(date);
      getDepartmentPrescriptionTop10(date);
    }
    
  }, [date]);

  useEffect(() => {
    // 当refreshRates获取到数据后才开始设置定时器
    if (refreshRates.length > 0 && date) {

      const intervalIds: number[] = [];

      intervalIds.push(
        safeInterval(
          () => getDrugsStock(date),
          Number(refreshRates.find((a: any) => a.code === '10')?.value),
          600000
        ),
        safeInterval(
          () => gettaskTimeDistribution(date),
          Number(refreshRates.find((a: any) => a.code === '13')?.value),
          600000
        ),
        safeInterval(
          () => getDrugTop10(date),
          Number(refreshRates.find((a: any) => a.code === '11')?.value),
          600000
        ),
        safeInterval(
          () => getPharmacyOperationStatistics(date),
          Number(refreshRates.find((a: any) => a.code === '14')?.value),
          600000
        ),
        safeInterval(
          () => getWindowMonitoring(date),
          Number(refreshRates.find((a: any) => a.code === '15')?.value),
          600000
        ),
        safeInterval(
          () => getPrescriptionTimeCount(date),
          Number(refreshRates.find((a: any) => a.code === '12')?.value),
          600000
        ),
        safeInterval(
          () => getPharmacistWorkloadStatistics(date),
          Number(refreshRates.find((a: any) => a.code === '16')?.value),
          600000
        )
      );

      // 清除定时器
      return () => {
        intervalIds.forEach(clearInterval);
      };
    }
  }, [refreshRates, date]);

  return (
    <div className={styles.MediScreen}>
      <div className={styles.topbar}>
        <img src={require('../../images/shouyebiaoti.png')} alt="" />
        <div className={styles.topbarInfo}>
          <div className={styles.hospName}>{hospInfo?.value ?? ''}</div>
          <div className={styles.date}>{time}</div>
        </div>
      </div>
      <div className={styles.content}>
        <div className={styles.left}>
          <div className={styles.blockOne}>
            <div className={styles.blockHeader}>库存状态</div>
            <div className={styles.rowOne}>
              <div className={styles.cycleProgress}>
                <CircularProgressBar
                  percentage={drugStock?.equipmentStockInfo?.percent * 100 ?? 0}
                  strokeWidth={10}
                  color="rgba(127, 190, 255, 1)"
                  trailColor="rgba(229, 238, 255, 1)"
                  animationDuration={1000}
                />
              </div>
              <div className={styles.rowDetail}>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>机内库存</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.equipmentStockInfo?.stock ?? 0} /></div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>临期</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.equipmentStockInfo?.expireNum ?? 0} /></div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>补药</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.equipmentStockInfo?.additionalNum ?? 0} /></div>
                </div>
              </div>
            </div>
            <div className={styles.rowTwo}>
              <div className={styles.cycleProgress}>
                <CircularProgressBar
                  percentage={drugStock?.hisStockInfo?.percent ?? 0}
                  strokeWidth={10}
                  color="rgba(255, 234, 128, 1)"
                  trailColor="rgba(229, 238, 255, 1)"
                  animationDuration={1000}
                />
              </div>
              <div className={styles.rowDetail}>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>机外库存</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.hisStockInfo?.stock ?? 0} /></div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>临期</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.hisStockInfo?.expireNum ?? 0} /></div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>补药</div>
                  <div className={styles.value}><NumberAnimation value={drugStock?.hisStockInfo?.additionalNum ?? 0} /></div>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.blockTwo}>
            <div className={styles.blockHeader}>任务完成时间分时分布</div>
            <div className={styles.barLineChartwrap}>
              <CustomBarLineChart barData={taskTimeDistribution} lineData={taskTimeDistribution} />
            </div>
            <div className={styles.blockHeader}>消耗药品Top</div>
            <div className={styles.listWrap}>
              <div key={'header'} className={styles.list}>
                <div className={styles.sort}></div>
                <div className={styles.name}>药品名称</div>
                <div className={styles.info}>药品规格</div>
                <div className={styles.company}>厂商</div>
              </div>
              {
                ([...drugTop10]).map((_, i) => {
                  return (
                    <div key={i} className={styles.list}>
                      <div className={styles.sort}>{(i + 1) >= 10 ? i + 1 : `0${i + 1}`}</div>
                      <div className={styles.name}>{_.drugName}</div>
                      <div className={styles.info}>{_.drugSpec}</div>
                      <div className={styles.company}>{_.manuFactoryName}</div>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </div>
        <div className={styles.middle}>
          <div className={styles.title}>药房当日运营统计</div>
          <div className={styles.subTitle}>
            <div className={styles.leftSubTitle}>平均品规数<i>{pharmacyOperationStatistics?.avgPrescriptionDrug ?? 0}</i></div>
            <div className={styles.rightSubTitle}>平均盒数<i>{pharmacyOperationStatistics?.avgDrugCount ?? 0}</i></div>
          </div>
          <div className={styles.dataWrap}>
            <div className={styles.dataBox}>
              <div className={styles.innerWrap}>
                <div className={styles.info}>
                  <div className={styles.option}>
                    <span className={styles.label}>患者人次</span>
                    <span className={styles.value}>
                      <NumberAnimation value={Number(pharmacyOperationStatistics?.patientInfo?.totalCount ?? 0)} />
                      <i>人</i>
                    </span>
                  </div>
                  <div className={`${styles.option}`}>
                    <span className={styles.label}>预测值</span>
                    <span className={styles.value}>
                      {Number(pharmacyOperationStatistics?.patientInfo?.forecastCount ?? 0)}<i>人</i>
                    </span>
                  </div>
                </div>
                <div className={styles.cardBottom}>
                  <div className={styles.a}>机发率<span>{pharmacyOperationStatistics?.patientInfo?.machinePercent ?? 0}</span></div>
                  <div className={styles.a}>直发率<span>{pharmacyOperationStatistics?.patientInfo?.straightPercent ?? 0}</span></div>
                </div>
              </div>
              <div className={styles.smoothLineChartWrap}>
                <SmoothLineChart data={pharmacyOperationStatistics?.patientInfo?.graph ?? []} />
              </div>
            </div>
            <div className={styles.dataBox}>
              <div className={styles.innerWrap}>
                <div className={styles.info}>
                  <div className={styles.option}>
                    <span className={styles.label}>当日处方</span>
                    <span className={styles.value}>
                      <NumberAnimation value={Number(pharmacyOperationStatistics?.prescription?.totalCount ?? 0)} />
                      <i>张</i>
                    </span>
                  </div>
                  <div className={`${styles.option} ${styles.yellow}`}>
                    <span className={styles.label}>预测值</span>
                    <span className={styles.value}>
                      {pharmacyOperationStatistics?.prescription?.forecastCount ?? 0}<i>张</i>
                    </span>
                  </div>
                </div>
                <div className={styles.cardBottom}>
                  <div className={styles.a}>机发率<span>{pharmacyOperationStatistics?.prescription?.machinePercent ?? 0}</span></div>
                  <div className={styles.a}>直发率<span>{pharmacyOperationStatistics?.prescription?.straightPercent ?? 0}</span></div>
                </div>
              </div>
              <div className={styles.smoothLineChartWrap}>
                <SmoothLineChart data={pharmacyOperationStatistics?.prescription?.graph ?? []} />
              </div>
            </div>
            <div className={styles.dataBox}>
              <div className={styles.innerWrap}>
                <div className={styles.info}>
                  <div className={styles.option}>
                    <span className={styles.label}>当日发药药盒</span>
                    <span className={styles.value}>
                      <NumberAnimation value={Number(pharmacyOperationStatistics?.drugInfo?.totalCount ?? 0)} />
                      <i>盒</i>
                    </span>
                  </div>
                  <div className={`${styles.option} ${styles.yellow}`}>
                    <span className={styles.label}>预测值</span>
                    <span className={styles.value}>
                      {pharmacyOperationStatistics?.drugInfo?.forecastCount ?? 0}<i>盒</i>
                    </span>
                  </div>
                </div>
                <div className={styles.cardBottom}>
                  <div className={styles.a}>机发率<span>{pharmacyOperationStatistics?.drugInfo?.machinePercent ?? 0}</span></div>
                  <div className={styles.a}>直发率<span>{pharmacyOperationStatistics?.drugInfo?.straightPercent ?? 0}</span></div>
                </div>
              </div>
              <div className={styles.smoothLineChartWrap}>
                <SmoothLineChart data={pharmacyOperationStatistics?.drugInfo?.graph ?? []} />
              </div>
            </div>
          </div>
          <div className={styles.titleSheb}>窗口监控</div>
          <div className={styles.banner}>
            <div className={styles.blockType}>
              <div className={styles.leftBlockType}>待配人数</div>
              <div className={styles.rightBlockType}>待发人数</div>
            </div>
            <BarChartZuhe data={windowMonitoring} />
          </div>
          <div className={styles.titleSheb}>当日处方分时统计</div>
          <div className={styles.shebeiCard}>
            <div className={styles.blockType}>
              <div className={styles.leftBlockType}>已缴费处方量</div>
              <div className={styles.rightBlockType}>已发放处方量</div>
            </div>
            <TimeSeriesChart
              labels={prescriptionTimeCount ? Object.keys(prescriptionTimeCount) : []}
              barData1={prescriptionTimeCount ? Object.keys(prescriptionTimeCount).map(label => prescriptionTimeCount[label].feeCount) : [20,30]}
              barData2={prescriptionTimeCount ? Object.keys(prescriptionTimeCount).map(label => prescriptionTimeCount[label].completeCount) : [10,15]}
            />
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.blockHeader}>药师工作量统计</div>
          <div className={styles.listWrap}>
            <div key={'header'} className={styles.list}>
              <div className={styles.name}>员工编号</div>
              <div className={styles.info}>调配处方量</div>
              <div className={styles.company}>发药处方量</div>
              <div className={styles.company}>工作总量</div>
            </div>
            {
              [...(convertObjectToArray(pharmacistWorkloadStatistics))].map((_, i) => {
                return (
                  <div key={i} className={styles.list}>
                    <div className={styles.name}>{_.label}</div>
                    <div className={styles.info}>{_.prePharmacistCount}</div>
                    <div className={styles.company}>{_.disPharmacistCount}</div>
                    <div className={styles.companyA}>{_.totalCount}</div>
                  </div>
                )
              })
            }
          </div>
          <div className={styles.blockHeader}>设备内药品效期管理</div>
          <div className={styles.SingleBarChartComponentWrap}>
            <SingleBarChartComponent data={convertDataToArray(equipmentDrugExpire)} />
          </div>
          <div className={styles.keshichufangblockHeader}>科室处方量Top</div>
          <div className={styles.barChartWrapper}>
            <BarChartComponent data={departmentPrescriptionTop10 ? (departmentPrescriptionTop10.map((a: any) => ({ label: a.encounterOrganization, value: a.prescriptionCount, unit: '' }))) : []} />
          </div>
        </div>
      </div>
      <div className={styles.bottom}>
        <div className={styles.btnGroup}>
          <Link to="/"><div className={location.pathname === '/' ? `${styles.btn} ${styles.active}` : `${styles.btn}`}>药房首页</div></Link>
          <Link to="/fenfa"><div className={location.pathname === '/fenfa' ? `${styles.btn} ${styles.active}` : `${styles.btn}`}>设备信息</div></Link>
        </div>
      </div>
    </div>
  );
}
