/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-06-25 17:01:46
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-03-14 13:52:36
 * @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, useState } from 'react';
import ProgressBar from '@/components/ProgressBar';
import TimelineComponent from '@/components/TimeLine';
import BarChartComponent from '@/components/BarChartComponent';
import ExpiryStockProgressBar from '@/components/ExpiryStockProgressBar';
import NumberAnimation from '@/components/NumberAnimation';
import { Link, useLocation } from 'umi';
import request from '@/utils/request';

// 获取当前完整时间（格式：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 extractPercentage = (str: string) => {
  const match = str.match(/-?\d+(\.\d+)?/); // 匹配数字（包括小数和负数）
  return match ? parseFloat(match[0]) : 0; // 将匹配到的结果转换为浮点数
};

const useViewport = () => {
  const [viewport, setViewport] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = () => {
      setViewport({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return viewport;
};

const defaultDate = getCurrentFormattedDate();

export default function Index() {
  const [time, setTime] = useState(getCurrentFormattedTime());
  const { width, height } = useViewport();
  const [equipmentDepreciation, set_equipmentDepreciation] = useState<any>(undefined);
  const [equipmentAdvice, set_equipmentAdvice] = useState<any>(undefined);
  const [equipmentPrescriptionInfo, set_equipmentPrescriptionInfo] = useState<any>(undefined);
  const [equipmentMaintenance, set_equipmentMaintenance] = useState<any>(undefined);
  const [equipmentInspection, set_equipmentInspection] = useState<any>(undefined);
  const [equipmentDepartmentCostAllocation, set_equipmentDepartmentCostAllocation] = useState<any>(undefined);
  const [equipmentExpire, set_equipmentExpire] = useState<any>(undefined);
  const [refreshRates, setRefreshRates] = useState<any[]>([]);
  const [hospInfo, set_hospInfo] = useState<any>(undefined);
  const [date, set_date] = useState<string | undefined>(undefined);
  const location = useLocation();

  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);
    }
  };

  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 getEquipmentDepreciation = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentDepreciation?date=${date}`);
    if (response) {
      set_equipmentDepreciation(response);
    }
  };

  const getEquipmentAdvice = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentAdvice?date=${date}`);
    if (response) {
      set_equipmentAdvice(response);
    }
  };

  const getEquipmentPrescriptionInfo = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentPrescriptionInfo?dateTime=${date}`);
    if (response) {
      set_equipmentPrescriptionInfo(response);
    }
  };

  const getEquipmentMaintenance = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentMaintenance?date=${date}`);
    if (response) {
      set_equipmentMaintenance(response);
    }
  };

  const getEquipmentInspection = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentInspection?date=${date}`);
    if (response) {
      set_equipmentInspection(response);
    }
  };

  const getEquipmentDepartmentCostAllocation = async (date: string) => {
    if (date) {
      const [year, month] = date.split('-');
      const _date = `${year}-${month}`;
      const response = await request.get(`/dashBoard/equipmentDepartmentCostAllocation?date=${_date}`);
      if (response) {
        set_equipmentDepartmentCostAllocation(response);
      }
    }
  };

  const getEquipmentExpire = async (date: string) => {
    const response = await request.get(`/dashBoard/equipmentExpire?date=${date}`);
    if (response) {
      set_equipmentExpire(response);
    }
  };

  useEffect(() => {
    // 获取刷新频率配置、医院信息及初始日期
    getRefreshRates();
    getHospInfo();
    getDate();

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

  // 新增：定时检测当前日期是否发生变化，跨天后自动更新 date 状态
  useEffect(() => {
    const dateInterval = setInterval(() => {
      const currentDate = getCurrentFormattedDate();
      if (currentDate !== date) {
        set_date(currentDate);
      }
    }, 60000);
    return () => clearInterval(dateInterval);
  }, [date]);

  useEffect(() => {
    // 初始加载数据
    if (date) {
      getEquipmentDepreciation(date);
      getEquipmentAdvice(date);
      getEquipmentPrescriptionInfo(date);
      getEquipmentMaintenance(date);
      getEquipmentInspection(date);
      getEquipmentDepartmentCostAllocation(date);
      getEquipmentExpire(date);
    }
  }, [date]);

  useEffect(() => {
    // 当 refreshRates 获取到数据后，设置定时刷新
    if (Object.keys(refreshRates).length > 0 && date) {
      const intervalIds: number[] = [];

      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;
        } else {
          return setInterval(fn, defaultDelay) as unknown as number;
        }
      };

      intervalIds.push(
        safeInterval(() => getEquipmentDepreciation(date), Number(refreshRates.find((a: any) => a.code === '10')?.value), 600000),
        safeInterval(() => getEquipmentAdvice(date), Number(refreshRates.find((a: any) => a.code === '13')?.value), 600000),
        safeInterval(() => getEquipmentPrescriptionInfo(date), Number(refreshRates.find((a: any) => a.code === '11')?.value), 600000),
        safeInterval(() => getEquipmentMaintenance(date), Number(refreshRates.find((a: any) => a.code === '14')?.value), 600000),
        safeInterval(() => getEquipmentInspection(date), Number(refreshRates.find((a: any) => a.code === '15')?.value), 600000),
        safeInterval(() => getEquipmentDepartmentCostAllocation(date), Number(refreshRates.find((a: any) => a.code === '12')?.value), 600000),
        safeInterval(() => getEquipmentExpire(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/topImg2x.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.iconWrap}>
                <img src={require('../../images/¥icon.png')} alt="" />
              </div>
              <div className={styles.rowDetail}>
                <div className={styles.name}>
                  设备原值<span>*设备随时间变化会产生折旧</span>
                </div>
                <div className={styles.value}>
                  <NumberAnimation value={equipmentDepreciation?.equipValue ?? 0} />
                </div>
              </div>
            </div>
            <div className={styles.rowTwo}>
              <div className={styles.iconWrap}>
                <img src={require('../../images/¥icon1.png')} alt="" />
              </div>
              <div className={styles.rowDetail}>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>设备净值</div>
                  <div className={styles.value}>
                    <NumberAnimation value={equipmentDepreciation?.netValue ?? 0} />
                  </div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>本月折旧</div>
                  <div className={styles.value}>
                    <NumberAnimation value={equipmentDepreciation?.curentMonthDepr ?? 0} />
                  </div>
                </div>
                <div className={styles.typeBlock}>
                  <div className={styles.label}>累计折旧</div>
                  <div className={styles.value}>
                    <NumberAnimation value={equipmentDepreciation?.accumulatedDepr ?? 0} />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.blockTwo}>
            <div className={styles.blockHeader}>建议补药</div>
            <div className={styles.progressWrap}>
              <div className={styles.infoOne}>
                缺药率<i>{equipmentAdvice?.lackPercentDisplay ?? '0%'}</i>
              </div>
              <div className={styles.infoTwo}>
                补药总数<i>{equipmentAdvice?.addMedCount ?? 0}盒</i>
              </div>
            </div>
            <div className={styles.listWrap}>
              {[
                ...(equipmentAdvice ? equipmentAdvice.list : []),
              ].map((item, i) => (
                <div key={i} className={styles.list}>
                  <div className={styles.number}>{i + 1 >= 10 ? i + 1 : `0${i + 1}`}</div>
                  <div className={styles.title}>
                    <div className={styles.name}>{item.medName}</div>
                    <div className={styles.sub}>{item.manufacturer}</div>
                  </div>
                  <div className={styles.al}>
                    <div className={styles.label}>库存</div>
                    <div className={styles.value}>{item.stock}</div>
                  </div>
                  <div className={styles.al}>
                    <div className={styles.label}>低限</div>
                    <div className={styles.value}>{item.avgDay}</div>
                  </div>
                  <div className={styles.al}>
                    <div className={styles.label}>缺药率</div>
                    <div className={styles.value}>{item.lackPercentDisplay}</div>
                  </div>
                  <div className={styles.al}>
                    <div className={styles.label}>建议领药量</div>
                    <div className={styles.value}>{item.addMedCount}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className={styles.middle}>
          <div className={styles.title}>
            总处方数{' '}
            <NumberAnimation value={equipmentPrescriptionInfo?.totalPrescriptionCount ?? 0} duration={2000} />张
          </div>
          <div className={styles.dataWrap}>
            <div className={styles.dataBox}>
              <div className={styles.info}>
                <div className={styles.option}>
                  <span className={styles.label}>直发率</span>
                  <span className={styles.value}>
                    <NumberAnimation
                      value={extractPercentage(equipmentPrescriptionInfo?.straightPercent?.percent ?? '0%')}
                    />
                    %
                  </span>
                </div>
                <div className={`${styles.option}`}>
                  <span className={styles.label}>较昨日</span>
                  <span className={styles.value}>{equipmentPrescriptionInfo?.straightPercent?.chain ?? '0%'}</span>
                </div>
              </div>
              <div className={styles.cardBottom}>
                <div className={styles.a}>
                  今日<span>{equipmentPrescriptionInfo?.straightPercent?.todayCount ?? 0}</span>
                </div>
                <div className={styles.a}>
                  昨日<span>{equipmentPrescriptionInfo?.straightPercent?.yesterdayCount ?? 0}</span>
                </div>
              </div>
            </div>
            <div className={styles.dataBox}>
              <div className={styles.info}>
                <div className={styles.option}>
                  <span className={styles.label}>混发率</span>
                  <span className={styles.value}>
                    <NumberAnimation
                      value={extractPercentage(equipmentPrescriptionInfo?.mixPercent?.percent ?? '0%')}
                    />
                    %
                  </span>
                </div>
                <div className={`${styles.option} ${styles.yellow}`}>
                  <span className={styles.label}>较昨日</span>
                  <span className={styles.value}>{equipmentPrescriptionInfo?.mixPercent?.chain ?? '0%'}</span>
                </div>
              </div>
              <div className={styles.cardBottom}>
                <div className={styles.a}>
                  今日<span>{equipmentPrescriptionInfo?.mixPercent?.todayCount ?? 0}</span>
                </div>
                <div className={styles.a}>
                  昨日<span>{equipmentPrescriptionInfo?.mixPercent?.yesterdayCount ?? 0}</span>
                </div>
              </div>
            </div>
            <div className={styles.dataBox}>
              <div className={styles.info}>
                <div className={styles.option}>
                  <span className={styles.label}>机发率</span>
                  <span className={styles.value}>
                    <NumberAnimation
                      value={extractPercentage(equipmentPrescriptionInfo?.machinePercent?.percent ?? '0%')}
                    />
                    %
                  </span>
                </div>
                <div className={`${styles.option} ${styles.yellow}`}>
                  <span className={styles.label}>较昨日</span>
                  <span className={styles.value}>{equipmentPrescriptionInfo?.machinePercent?.chain ?? '0%'}</span>
                </div>
              </div>
              <div className={styles.cardBottom}>
                <div className={styles.a}>
                  今日<span>{equipmentPrescriptionInfo?.machinePercent?.todayCount ?? 0}</span>
                </div>
                <div className={styles.a}>
                  昨日<span>{equipmentPrescriptionInfo?.machinePercent?.yesterdayCount ?? 0}</span>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.banner}>
            <img src={require('../../images/banner.png')} alt="" />
          </div>
          <div className={styles.titleSheb}>设备保养</div>
          <div className={styles.shebeiCard}>
            {[
              ...(equipmentMaintenance && equipmentMaintenance.length > 0 ? equipmentMaintenance : [{}]),
            ].map((item, i) => (
              <div key={i} className={item.status ? `${styles.card}` : `${styles.card} ${styles.gray}`}>
                <div className={item.maintainFlag ? `${styles.season} ${styles.completed}` : styles.season}>
                  {item.maintainPlanName}
                </div>
                <div className={styles.name}>{item.maintainFlag ? '保养已完成' : '保养未完成'}</div>
                <div className={styles.date}>{item.maintainPlanDate}</div>
              </div>
            ))}
          </div>
          <div className={styles.titleSheb}>设备巡检</div>
          <div>
            <TimelineComponent
              data={
                equipmentInspection
                  ? equipmentInspection.map((a: any) => ({
                      date: a.inspectDate,
                      status: a.inspectFlag,
                      person: a.inspectUser,
                      inspectPlanName: a.inspectPlanName,
                    }))
                  : []
              }
            />
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.blockHeader}>成本分摊</div>
          <div className={styles.barChartWrapper}>
            <BarChartComponent
              data={
                equipmentDepartmentCostAllocation && equipmentDepartmentCostAllocation.length > 0
                  ? equipmentDepartmentCostAllocation.map((a: any) => ({
                      label: a.deptName,
                      value: a.sum,
                      unit: '元',
                    }))
                  : [{ label: '无', value: 0 }]
              }
            />
          </div>
          <div className={styles.blockHeader}>临近效期</div>
          <div className={styles.progressWrapper}>
            <div className={styles.allexpired}>
              全部临期<i>{equipmentExpire?.expireCount ?? 0}盒</i>
            </div>
            <div className={styles.expiredper}>
              临期占比<i>{equipmentExpire?.expirePercentDisplay ?? '0%'}</i>
            </div>
            <div className={styles.stockCount}>
              当前库存<i>{equipmentExpire?.totalCount ?? 0}盒</i>
            </div>
          </div>
          <div className={styles.listWrap}>
            {[
              ...(equipmentExpire?.expireList ?? []),
            ].map((item, i) => (
              <div key={i} className={styles.list}>
                <div className={styles.number}>{i + 1 >= 10 ? i + 1 : `0${i + 1}`}</div>
                <div className={styles.title}>
                  <div className={styles.name}>{item.drugName}</div>
                  <div className={styles.sub}>最短有效期至{item.nearExpire}</div>
                </div>
                <div className={styles.progress}>
                  <ExpiryStockProgressBar expiryCount={item.expireStock} stockCount={item.totalStock} />
                </div>
              </div>
            ))}
          </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>
  );
}
