import React, { useState, useEffect, useRef, useCallback } from 'react';
import styled from 'styled-components';
import { apiGet } from '../../utils/request';
import { getDefaultDate } from '../../App';
import useGlobalRefresh from '../../hooks/useGlobalRefresh';

// 组件容器样式
const Container = styled.div`
  width: 92%;
  margin: 0 auto;
  position: relative;
  margin-bottom: 2vh;
  height: auto;
  overflow: visible;
`;

// 标题样式
const Title = styled.div`
  color: #CCE6FF;
  font-size: 1vw;
  text-align: center;
  margin-bottom: 0.5vw;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('/zhongjianbiaotizhuangshi_bg.png') no-repeat;
  background-size: contain;
  background-position: center;
  height: 1.8vw;
  font-family: 'DingTalk JinBuTi', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  
  &::before,
  &::after {
    display: none;
  }
`;

// 内容背景容器
const ContentBox = styled.div`
  width: 100%;
  background: url('/shebeixunjian_bg.png') no-repeat;
  background-size: 100% 100%;
  padding: 1vw 1.5vw 1vw 1.5vw;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
`;

// 巡检状态行
const StatusRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.2vw;
`;

// 巡检状态文本
const StatusText = styled.div<{ status: 'completed' | 'pending' }>`
  color: ${props => props.status === 'completed' ? '#fff' : '#6B8299'};
  font-size: 0.7vw;
  text-align: center;
  width: 8.33%;
  font-weight:bold;
`;

// 巡检时间轴
const TimelineContainer = styled.div<{ completedPercentage: number }>`
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 0.25vw;
    transform: translateY(-50%);
    background: linear-gradient(
      to right,
      #66CCFF 0%,
      #66CCFF ${props => props.completedPercentage}%,
      #233A59 ${props => props.completedPercentage}%,
      #233A59 100%
    );
    border-radius: 0.125vw;
    z-index: 0;
  }
`;

// 巡检记录项
const InspectionItem = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;
  width: 8.33%;
`;

// 巡检状态点
const StatusDot = styled.div<{ status: 'completed' | 'pending' }>`
  width: 1.5vw;
  height: 1.5vw;
  border-radius: 0.5vw;
  background: ${props => props.status === 'completed' 
    ? 'linear-gradient(180deg, #66CCFF 0%, #B3E6FF 100%)'
    : '#233A59'};
  border: 0.3vw solid #051833;
  position: relative;
`;

// 日期容器
const DateContainer = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5vw;
  margin-bottom: 0.3vw;
`;

// 巡检日期
const DateText = styled.div<{ status: 'completed' | 'pending' }>`
  color: ${props => props.status === 'completed' ? '#CCE6FF' : '#6B8299'};
  font-size: 0.5vw;
  text-align: center;
  width: 8.33%;
`;

// 巡检人员容器
const InspectorContainer = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

// 巡检人员
const InspectorText = styled.div<{ status: 'completed' | 'pending' }>`
  color: ${props => props.status === 'completed' ? '#CCE6FF' : '#6B8299'};
  font-size: 0.6vw;
  text-align: center;
  width: 8.33%;
`;

interface InspectionRecord {
  equipCode: string;
  equipName: string;
  inspectPlanDate: string;
  inspectPlanName: string;
  seqNo: number;
  inspectFlag: boolean;
  inspectDate: string | null;
  inspectUser: string | null;
  remark: string | null;
}

interface DeviceInspectionChartProps {
  selectedEquipCode: string;
}

const DeviceInspectionChart: React.FC<DeviceInspectionChartProps> = ({ selectedEquipCode }) => {
  const [records, setRecords] = useState<InspectionRecord[]>([]);
  
  const fetchData = useCallback(async () => {
    try {
      // 获取默认日期
      const defaultDate = getDefaultDate();
      
      // 直接使用选中的设备代码
      const equipCode = selectedEquipCode;
      
      // 调用新的设备巡检接口
      const response = await apiGet('/equipMana/equipmentInspection', {
        params: { 
          dateTime: defaultDate,
          equipCode: equipCode
        }
      });
      
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        setRecords(response.data.data);
      }
    } catch (error) {
      console.error('获取设备巡检数据失败:', error);
      // 使用模拟数据
      setRecords([
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-02-01", inspectPlanName: "2月", seqNo: 2, inspectFlag: true, inspectDate: "2024-02-01", inspectUser: "张晓静", remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-03-01", inspectPlanName: "3月", seqNo: 3, inspectFlag: true, inspectDate: "2024-03-01", inspectUser: "张晓静", remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-04-01", inspectPlanName: "4月", seqNo: 4, inspectFlag: true, inspectDate: "2024-04-01", inspectUser: "张晓静", remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-05-01", inspectPlanName: "5月", seqNo: 5, inspectFlag: true, inspectDate: "2024-05-01", inspectUser: "张晓静", remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-06-01", inspectPlanName: "6月", seqNo: 6, inspectFlag: true, inspectDate: "2024-06-01", inspectUser: "张晓静", remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-07-01", inspectPlanName: "7月", seqNo: 7, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-08-01", inspectPlanName: "8月", seqNo: 8, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-09-01", inspectPlanName: "9月", seqNo: 9, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-10-01", inspectPlanName: "10月", seqNo: 10, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-11-01", inspectPlanName: "11月", seqNo: 11, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null },
        { equipCode: "2", equipName: "Rowa", inspectPlanDate: "2025-12-01", inspectPlanName: "12月", seqNo: 12, inspectFlag: false, inspectDate: null, inspectUser: null, remark: null }
      ]);
    }
  }, [selectedEquipCode]);

  // 组件挂载时获取数据
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 使用全局刷新钩子，指定模块代码'29'
  useGlobalRefresh(fetchData, '29');

  // 当选中的设备代码变化时重新获取数据
  useEffect(() => {
    fetchData();
  }, [selectedEquipCode]);

  return (
    <Container>
      <Title>设备巡检</Title>
      <ContentBox>
        <div>
          <StatusRow>
            {records.map(record => (
              <StatusText key={`status-${record.seqNo}`} status={record.inspectFlag ? 'completed' : 'pending'}>
                {record.inspectFlag ? '已巡检' : '未开始'}
              </StatusText>
            ))}
          </StatusRow>
          
          <TimelineContainer completedPercentage={
            (() => {
              const completedCount = records.filter(r => r.inspectFlag).length;
              const totalCount = records.length;
              if (totalCount === 0) return 0;
              // 计算到最后一个已完成项目的中心位置的百分比
              // 每个项目占据 100/totalCount 的宽度，中心位置是宽度的一半
              return completedCount > 0 ? ((completedCount - 0.5) * 100) / totalCount : 0;
            })()
          }>
            {records.map(record => (
              <InspectionItem key={`dot-${record.seqNo}`}>
                <StatusDot status={record.inspectFlag ? 'completed' : 'pending'} />
              </InspectionItem>
            ))}
          </TimelineContainer>
        </div>
        
        <div>
          <DateContainer>
            {records.map(record => (
              <DateText key={`date-${record.seqNo}`} status={record.inspectFlag ? 'completed' : 'pending'}>
                {record.inspectFlag ? (record.inspectDate ? record.inspectDate.replace(/-/g, '/') : '') : (record.inspectPlanDate ? record.inspectPlanDate.replace(/-/g, '/') : '')}
              </DateText>
            ))}
          </DateContainer>
          
          <InspectorContainer>
            {records.map(record => (
              <InspectorText key={`inspector-${record.seqNo}`} status={record.inspectFlag ? 'completed' : 'pending'}>
                {record.inspectFlag ? record.inspectUser : '预计'}
              </InspectorText>
            ))}
          </InspectorContainer>
        </div>
      </ContentBox>
    </Container>
  );
};

export default DeviceInspectionChart; 