import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { apiGet } from '../utils/request';
import { getDefaultDate } from '../App'; // 导入getDefaultDate函数

// 按钮容器
const ButtonsContainer = styled.div`
  position: fixed;
  right: 1vw;
  bottom: 8vh;
  display: flex;
  flex-direction: column;
  z-index: 1000;
`;

// 单个按钮
const Button = styled.div<{ isActive: boolean; buttonIndex: number }>`
  width: 1.5vw;
  height: 9.5vh;
  background-image: ${props => 
    props.isActive 
      ? `url('/side_nav_${props.buttonIndex}_active.png')` 
      : `url('/side_nav_${props.buttonIndex}.png')`};
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: ${props => props.isActive ? '#0A1433' : '#CCDDFF'};
  font-size: 0.6vw;
  cursor: pointer;
  position: relative;
  padding: 0;
  writing-mode: vertical-lr;
  text-orientation: upright;
  letter-spacing: 0.1vw;
  margin-bottom: -1vh; /* 使用vh单位实现自适应的负边距 */
`;

// 抽屉容器
const Drawer = styled.div<{ isOpen: boolean }>`
  position: fixed;
  right: ${props => props.isOpen ? '3vw' : '-50vw'};
  top: 12vh;
  width: 46.5vw;
  height: 80vh;
  background: url('/choutibeijingtu_bg.png') no-repeat;
  background-size: 100% 100%;
  background-position: center;
  transition: right 0.3s;
  z-index: 999;
  display: flex;
  flex-direction: column;
  padding: 0;
  padding-top: 1.5%;
  overflow: hidden;
  background-color: #051833;
  &::after {
    content: '';
    position: absolute;
    bottom: 3vh;
    left: 15%;
    right: 10%;
    height: 2px;
    background: url('/bottom_decoration.png') no-repeat;
    background-size: contain;
    background-position: center;
  }
`;

// 模块标题
const ModuleTitle = styled.div`
  position: relative;
  width: 65%;
  height: 1.6vw;
  padding-left: 4%;
  text-align: left;
  line-height: 1.6vw;
  font-size: 0.8vw;
  color:#E6F2FF;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  background: url('/component_header_bg.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  &::before {
    content: '';
    display: none;
  }
  
  &::after {
    content: '';
    display: none;
  }
`;

// 关闭按钮
const CloseButton = styled.div`
  position: absolute;
  z-index: 99;
  right: 2.5vw;
  bottom: 0.5vw;
  width: 2vw;
  height: 2vw;
  display: flex;
  justify-content: center;
  align-items: center;
  color: transparent;
  cursor: pointer;
  font-size: 1.5vw;
  background: url('/drawer_close_btn.png') no-repeat;
  background-size: contain;
  background-position: center;
`;

// 抽屉内容
const DrawerContent = styled.div`
  flex: 1;
  overflow-y: auto;
  color: #CCE6FF;
  padding: 1vh 1.5vw;
  
  &::-webkit-scrollbar {
    width: 0.5vw;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(10, 20, 51, 0.2);
    border-radius: 10px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(78, 128, 229, 0.5);
    border-radius: 10px;
  }
`;

// 药品列表容器
const MedicineList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1vh;
  width: 100%;
  padding-top: 1vw;
  padding-right: 1vw;
`;

// 药品项目
const MedicineItem = styled.div`
  display: flex;
  align-items: center;
  width: 100%;
  height: 4.5vh;
  background: url('/paihangkapian.png') no-repeat;
  background-size: 100% 100%;
  background-position: center;
  /* border-radius: 0.5vw; */
  padding: 0;
  position: relative;
  /* overflow: hidden; */
  border: none;
  box-shadow: none;
`;

// 序号样式
const SerialNumber = styled.div`
  width: 2.5vw;
  height: 100%;
  font-size: 1vw;
  font-weight: bold;
  color: #CCE6FF;
  text-align: center;
  z-index: 1;
  /* background: linear-gradient(90deg, rgba(78, 128, 229, 0.2) 0%, rgba(31, 50, 80, 0) 100%); */
  display: flex;
  justify-content: center;
  align-items: center;
`;

// 药品信息区域
const MedicineInfo = styled.div`
  display: flex;
  flex-direction: column;
  margin-left: 0.5vw;
  flex: 1;
  justify-content: center;
`;

// 药品名称
const MedicineName = styled.div`
  font-size: 0.7vw;
  color: #fff;
  display: flex;
  font-weight:bold; 
  flex-direction: row;
  align-items: flex-start;
  gap: 0.5vw;
  margin-bottom: 0.1vw;
  white-space: nowrap;
  
  span {
    color: #CCE6FF;
    font-size: 0.8vw;
  }
`;

// 药品厂家
const MedicineManufacturer = styled.div`
  font-size: 0.6vw;
  color: #A3B8CC;
  text-align: left;
`;

// 数据指标容器
const DataSection = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 60%;
  /* gap: 1.2vw; */
`;

// 单个指标
const DataItem = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  flex: 0.15s;
  min-width: 0;
`;

// 指标标题
const DataTitle = styled.div`
  font-size: 0.55vw;
  color: #CCE6FF;
  text-align: left;
  margin-bottom: 0.1vw;
`;

// 指标数值
const DataValue = styled.div<{ color?: string }>`
  font-size: 0.8vw;
  color: ${props => props.color || '#CCE6FF'};
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  text-align: left;
`;

// 按钮类型
type ButtonType = '补药清单' | '效期清单' | '滞销清单' | null;

interface DrawerButtonsProps {
  currentScreen: number;
  equipCode: string;
  dateTime: string;
}

const DrawerButtons: React.FC<DrawerButtonsProps> = ({ currentScreen, equipCode, dateTime }) => {
  // 所有Hooks必须在组件体最顶层调用，不能放在if语句后面
  const [activeDrawer, setActiveDrawer] = useState<ButtonType>(null);
  const [supplementData, setSupplementData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [expiryList, setExpiryList] = useState<any[]>([]);
  const [slowList, setSlowList] = useState<any[]>([]);
  
  // 打开指定抽屉
  const openDrawer = (type: ButtonType) => {
    setActiveDrawer(type);
  };
  
  // 关闭抽屉
  const closeDrawer = () => {
    setActiveDrawer(null);
  };
  
  // 补药清单接口请求
  useEffect(() => {
    if (activeDrawer === '补药清单') {
      setLoading(true);
      setError(null);
      // 使用getDefaultDate()函数获取日期，而不是直接使用传入的dateTime
      const defaultDate = getDefaultDate();
      apiGet('/equipMana/drugReplenishedList', {
        params: {
          dateTime: defaultDate,
          equipCode: equipCode === 'total' ? '0' : equipCode
        }
      })
        .then((res: any) => {
          if (res.data && res.data.data && Array.isArray(res.data.data)) {
            setSupplementData(res.data.data);
          } else {
            setSupplementData([]);
            setError('无数据');
          }
        })
        .catch(() => {
          setSupplementData([]);
          setError('接口请求失败');
        })
        .finally(() => setLoading(false));
    }
    if (activeDrawer === '效期清单') {
      setLoading(true);
      setError(null);
      // 使用getDefaultDate()函数获取日期，而不是直接使用传入的dateTime
      const defaultDate = getDefaultDate();
      apiGet('/equipMana/drugExpiryDateList', {
        params: {
          dateTime: defaultDate,
          equipCode: equipCode === 'total' ? '0' : equipCode
        }
      })
        .then((res: any) => {
          if (res.data && res.data.data && Array.isArray(res.data.data)) {
            setExpiryList(res.data.data);
          } else {
            setExpiryList([]);
            setError('无数据');
          }
        })
        .catch(() => {
          setExpiryList([]);
          setError('接口请求失败');
        })
        .finally(() => setLoading(false));
    }
    if (activeDrawer === '滞销清单') {
      setLoading(true);
      setError(null);
      // 使用getDefaultDate()函数获取日期，而不是直接使用传入的dateTime
      const defaultDate = getDefaultDate();
      apiGet('/equipMana/drugSlowMovingList', {
        params: {
          dateTime: defaultDate,
          equipCode: equipCode === 'total' ? '0' : equipCode
        }
      })
        .then((res: any) => {
          if (res.data && res.data.data && Array.isArray(res.data.data)) {
            setSlowList(res.data.data);
          } else {
            setSlowList([]);
            setError('无数据');
          }
        })
        .catch(() => {
          setSlowList([]);
          setError('接口请求失败');
        })
        .finally(() => setLoading(false));
    }
  }, [activeDrawer, equipCode]); // 移除dateTime依赖，因为现在使用getDefaultDate()
  
  // 效期清单数据结构调整
  const expiryData = [
    { id: 1, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 2, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 3, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 4, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 5, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 6, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
    { id: 7, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', expiry: '2024/6/31', quantity: 210, overdueStock: 26 },
  ];

  // 滞销清单数据结构调整
  const slowMovingData = [
    { id: 1, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 2, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 3, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 4, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 5, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 6, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 7, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 8, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 9, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 10, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 11, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
    { id: 12, name: '阿魏酸哌嗪片', spec: '[50mgx180.00]', manufacturer: '四川成都亨达制药厂', batchNo: '250305w082', inPackCount: 2930, inPieceCount: 2930, inDate: '2024/6/1', expiry: '2024/6/31', slowDays: 26 },
  ];

  // 格式化编号为两位数
  const formatId = (id: number): string => {
    return id < 10 ? `0${id}` : `${id}`;
  };

  return (
    <>
      {currentScreen === 2 && (
        <>
          <ButtonsContainer>
            <Button 
              isActive={activeDrawer === '补药清单'} 
              onClick={() => openDrawer('补药清单')}
              buttonIndex={1}
            >
              补药清单
            </Button>
            <Button 
              isActive={activeDrawer === '效期清单'} 
              onClick={() => openDrawer('效期清单')}
              buttonIndex={2}
            >
              效期清单
            </Button>
            <Button 
              isActive={activeDrawer === '滞销清单'} 
              onClick={() => openDrawer('滞销清单')}
              buttonIndex={3}
            >
              滞销清单
            </Button>
          </ButtonsContainer>
          
          <Drawer isOpen={activeDrawer === '补药清单'}>
            <CloseButton onClick={closeDrawer}>×</CloseButton>
            <ModuleTitle>补药清单</ModuleTitle>
            <DrawerContent>
              {loading ? (
                <div style={{color:'#7E9BCC',textAlign:'center',padding:'2vw'}}>数据加载中...</div>
              ) : error ? (
                <div style={{color:'#F7B500',textAlign:'center',padding:'2vw'}}>{error}</div>
              ) : (
                <MedicineList>
                  {supplementData.map((item, idx) => (
                    <MedicineItem key={`suppl-${idx}`}>
                      <SerialNumber>{formatId(idx+1)}</SerialNumber>
                      <MedicineInfo style={{marginLeft:0}} >
                        <MedicineName>
                          {item.medicationname}
                        </MedicineName>
                        <MedicineManufacturer>
                          {item.brandname}
                        </MedicineManufacturer>
                      </MedicineInfo>
                      <DataSection style={{width: '40%',gap: '0.3vw'}}>
                        <DataItem style={{flex: 0.4}}>
                          <DataTitle>包装量</DataTitle>
                          <DataValue color="#B3D9FF">{item.specificationquantity}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.4}}>
                          <DataTitle>补药包装数</DataTitle>
                          <DataValue color="#B3D9FF">{item.needbox}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.4}}>
                          <DataTitle>缺药率</DataTitle>
                          <DataValue color="#B3D9FF">{item.needper}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.4}}>
                          <DataTitle >合理库存</DataTitle>
                          <DataValue color="#B3D9FF">{item.total}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.4}}>
                          <DataTitle>库存</DataTitle>
                          <DataValue color="#FFEA80">{item.quantity}</DataValue>
                        </DataItem>
                      </DataSection>
                    </MedicineItem>
                  ))}
                </MedicineList>
              )}
            </DrawerContent>
          </Drawer>
          
          <Drawer isOpen={activeDrawer === '效期清单'}>
            <CloseButton onClick={closeDrawer}>×</CloseButton>
            <ModuleTitle>效期清单</ModuleTitle>
            <DrawerContent>
              {loading ? (
                <div style={{color:'#7E9BCC',textAlign:'center',padding:'2vw'}}>数据加载中...</div>
              ) : error ? (
                <div style={{color:'#F7B500',textAlign:'center',padding:'2vw'}}>{error}</div>
              ) : (
                <MedicineList>
                  {expiryList.map((item, idx) => (
                    <MedicineItem key={`expiry-${idx}`}>
                      <SerialNumber>{formatId(idx+1)}</SerialNumber>
                      <MedicineInfo style={{marginLeft:0,width:'30%'}}>
                        <MedicineName>
                          {item.medicationName}
                        </MedicineName>
                        <MedicineManufacturer>
                          {item.manufacturer}
                        </MedicineManufacturer>
                      </MedicineInfo>
                      <DataSection style={{width: '60%'}}>
                        <DataItem style={{flex: 0.25,marginRight:'0.8vw'}}>
                          <DataTitle>效期</DataTitle>
                          <DataValue color="#80EAFF">{item.expiryDate}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.15}}>
                          <DataTitle>库存</DataTitle>
                          <DataValue color="#80EAFF">{item.stock}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.15}}>
                          <DataTitle>到期天数</DataTitle>
                          <DataValue color="#FFEA80">{item.daysToExpire}</DataValue>
                        </DataItem>
                      </DataSection>
                    </MedicineItem>
                  ))}
                </MedicineList>
              )}
            </DrawerContent>
          </Drawer>
          
          <Drawer isOpen={activeDrawer === '滞销清单'}>
            <CloseButton onClick={closeDrawer}>×</CloseButton>
            <ModuleTitle>滞销清单</ModuleTitle>
            <DrawerContent>
              {loading ? (
                <div style={{color:'#7E9BCC',textAlign:'center',padding:'2vw'}}>数据加载中...</div>
              ) : error ? (
                <div style={{color:'#F7B500',textAlign:'center',padding:'2vw'}}>{error}</div>
              ) : (
                <MedicineList>
                  {slowList.map((item, idx) => (
                    <MedicineItem key={`slow-${idx}`}>
                      <SerialNumber>{formatId(idx+1)}</SerialNumber>
                      <MedicineInfo style={{width: '40%',overflow: 'hidden',marginLeft:0}}>
                        <MedicineName style={{width: '100%', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>
                          {item.medicationname}
                        </MedicineName>
                        <MedicineManufacturer style={{width: '100%'}}>
                          {item.brandname}
                        </MedicineManufacturer>
                      </MedicineInfo>
                      <DataSection style={{width: '60%'}}>
                        
                        <DataItem style={{flex: 0.2}}>
                          <DataTitle>批号</DataTitle>
                          <DataValue style={{color: '#80FFEA'}}>{item.batchnumber?item.batchnumber:'-'}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.2}}>
                          <DataTitle>入库包装数</DataTitle>
                          <DataValue style={{color: '#80FFEA'}}>{item.inputPackageNum}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.2}}>
                          <DataTitle>入库日期</DataTitle>
                          <DataValue style={{color: '#80FFEA'}}>{item.inputdate ? item.inputdate.replace(/-/g, '/') : ''}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.2}}>
                          <DataTitle>效期</DataTitle>
                          <DataValue style={{color: '#80FFEA'}}>{item.expirydate}</DataValue>
                        </DataItem>
                        <DataItem style={{flex: 0.15}}>
                          <DataTitle>滞销天数</DataTitle>
                          <DataValue style={{color: '#FFEA80'}}>{item.unsoldDays}</DataValue>
                        </DataItem>
                      </DataSection>
                    </MedicineItem>
                  ))}
                </MedicineList>
              )}
            </DrawerContent>
          </Drawer>
        </>
      )}
    </>
  );
};

export default DrawerButtons;