import React, { useEffect, useRef, useState } from 'react';
import Title from '@/pages/homepage/compontent/title';
import {
  Row,
  Col,
  Select,
  DatePicker,
  Statistic,
  Card,
  Table,
  Tag,
  Space,
  Form, Button,
} from 'antd';
import * as echarts from 'echarts';
import styles from './Analysis.less';

const { Option } = Select;
const { RangePicker } = DatePicker;
const Title1=(props)=>{
  return(
      <div style={{display:'flex',alignItems:'center',fontSize:20,marginBottom:'20px'}}>
          <span style={{background:'#006665',display:'inline-block',height:'6px',width:'6px',borderRadius:'50%',marginRight:'7px'}}></span>
          <span>{props.title}</span>
      </div>
  )
}

const Analysis = () => {
  const [form] = Form.useForm();
  const numberLineChartRef=useRef(null)
  const numberLineChartRef1=useRef(null)
  const numberLineChartRef2=useRef(null)
  const pieChartRef = useRef(null);
  const barChartRef = useRef(null);
  const lineChartRef = useRef(null);
  const barChartRef1 = useRef(null);
  const barChartRef2 = useRef(null);
  // 初始化图表
  useEffect(() => {
      if (numberLineChartRef.current) {
        const chart = echarts.init(numberLineChartRef.current);
        const numberLineOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            }
          },
          grid: {
            top: '10%',
            left: '0%',
            right: '6%',
            bottom: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: ['5月', '6月', '7月', '8月', '9月', '10月', '11月'],
              axisTick: {
                alignWithLabel: true
              },
              boundaryGap: false
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '月环比增长15%',
            }
          ],
          series: [
            {
              name: '工单数量',
              type: 'line',
              data: [900, 1000, 950, 1050, 900, 850, 800],
              lineStyle: {
                color:'#006665'
              },
              itemStyle:{
                color:'#006665'
              },
              areaStyle:{
                color:'#DFEAE5'
              }
            }
          ]
        };
        chart.setOption(numberLineOption);
        const handleResize = () => {
          chart.resize();
        };
        window.addEventListener('resize', handleResize);
        return () => {
          window.removeEventListener('resize', handleResize);
          chart?.dispose();
        };
      }
  }, []);
  useEffect(() => {
      if (numberLineChartRef1.current) {
        const chart = echarts.init(numberLineChartRef1.current);
        const numberLineOption1 = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            }
          },
          grid: {
            top: '10%',
            left: '0%',
            right: '6%',
            bottom: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: ['5月', '6月', '7月', '8月', '9月', '10月', '11月'],
              axisTick: {
                alignWithLabel: true
              },
              boundaryGap: false
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '月环比增长15%',
            }
          ],
          series: [
            {
              name: '工单数量',
              type: 'line',
              data: [900, 1000, 950, 1050, 900, 850, 800],
              lineStyle: {
                color:'#FF826D'
              },
              itemStyle:{
                color:'#FF826D'
              },
              areaStyle:{
                color:'#F4EDED'
              }
            }
          ]
        };
        chart.setOption(numberLineOption1);
        const handleResize = () => {
          chart.resize();
        };
        window.addEventListener('resize', handleResize);
        return () => {
          window.removeEventListener('resize', handleResize);
          chart?.dispose();
        };
      }
  }, []);
  useEffect(() => {
      if (numberLineChartRef2.current) {
        const chart = echarts.init(numberLineChartRef2.current);
        const numberLineOption1 = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            }
          },
          grid: {
            top: '10%',
            left: '0%',
            right: '6%',
            bottom: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: ['5月', '6月', '7月', '8月', '9月', '10月', '11月'],
              axisTick: {
                alignWithLabel: true
              },
              boundaryGap: false
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '月环比增长15%',
            }
          ],
          series: [
            {
              name: '工单数量',
              type: 'line',
              data: [2.5, 3, 5, 2.5, 4, 4.5, 3.5],
              lineStyle: {
                color:'#006665'
              },
              itemStyle:{
                color:'#006665'
              },
              areaStyle:{
                color:'#E2EFEA'
              }
            }
          ]
        };
        chart.setOption(numberLineOption1);
        const handleResize = () => {
          chart.resize();
        };
        window.addEventListener('resize', handleResize);
        return () => {
          window.removeEventListener('resize', handleResize);
          chart?.dispose();
        };
      }
  }, []);

  useEffect(()=>{
    // 饼图 - 工单分类统计
    if (pieChartRef.current) {
      const chart = echarts.init(pieChartRef.current);
      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          textStyle: {
            fontSize: 16
          },
          itemGap:30,
          itemWidth:0,
          formatter:'{name}'

        },
        series: [
          {
            name: '工单类型',
            type: 'pie',
            radius: '70%',
            center: ['75%', '40%'],
            data: [
              {value: 85, name: '设备维修', itemStyle: {color: '#C1D3D1'}},
              {value: 60, name: '故障报修', itemStyle: {color: '#045F5E80'}},
              {value: 45, name: '软件升级', itemStyle: {color: '#FFBC00'}},
              {value: 30, name: '巡检任务', itemStyle: {color: '#FF826D'}}
            ],
            labelLine:{
              show:false
            },
            label:{
              show:false
            }
          }
        ]
      };
      chart.setOption(pieOption);
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
      };
    }

  },[])
  useEffect(()=>{
    // 柱状图 - 工单状态统计
    if (barChartRef.current) {
      const chart = echarts.init(barChartRef.current);
      const barOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          textStyle: {
            fontSize: 16
          },
          itemGap:30,
          itemWidth:0,
          formatter:'{name}'

        },
        series: [
          {
            name: '工单类型',
            type: 'pie',
            radius: '70%',
            center: ['75%', '40%'],
            data: [
              {value: 85, name: '设备维修', itemStyle: {color: '#C1D3D1'}},
              {value: 60, name: '故障报修', itemStyle: {color: '#045F5E80'}},
              {value: 45, name: '软件升级', itemStyle: {color: '#FFBC00'}},
              {value: 30, name: '巡检任务', itemStyle: {color: '#FF826D'}}
            ],
            labelLine:{
              show:false
            },
            label:{
              show:false
            }
          }
        ]
      };
      chart.setOption(barOption);
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
      };
    }

  },[])
  useEffect(()=>{
    // 柱状图 - 工单状态统计
    if (barChartRef1.current) {
      const chart = echarts.init(barChartRef1 .current);
      const barOption = {
        // 提示框（鼠标悬浮显示数据）
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        // 图例（多系列时开启）
        // legend: {
        //   top: 0,
        //   right: 10
        // },
        // 网格（调整图表内边距，适配容器）
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        // X轴（替换为你的实际标签）
        xAxis: {
          type: 'category',
          data: ['传感器', '服务器', '网络设备', '安全设备', '网关','摄像头','执行器','机房环境类','其他'],
          axisLabel: { fontSize: 12 }
        },
        // Y轴
        yAxis: {
          type: 'value',
          axisLabel: { fontSize: 12 }
        },
        // 系列数据（替换为你的实际数值）
        series: [
          {
            name: '数据1',
            type: 'bar',
            data: [{value: 85, itemStyle: {color: '#C1D3D1'}}, {value: 95, itemStyle: {color: '#045F5E80'}}, {value: 96, itemStyle: {color: '#FFBC00'}}, {value: 65, itemStyle: {color: '#FF826D'}}, {value: 47, itemStyle: {color: '#045F5E80'}}, {value: 61, itemStyle: {color: '#FFBC00'}}, {value: 71, itemStyle: {color: '#FF826D'}}, {value: 45, itemStyle: {color: '#045F5E80'}}, {value: 92, itemStyle: {color: '#FFBC00'}}], // 匹配X轴的数值
            // 柱子样式（可选）
            // itemStyle: {
            //   color: '#1890ff', // 阿里云蓝（可自定义）
            //   borderRadius: 4 // 圆角
            // },
            label:{
              position:'top',
              color:'#333333',
              show: true
            },
            // 柱子宽度
            barWidth: '20%'
          },
          // 如需多系列，新增对象即可
          // {
          //   name: '数据2',
          //   type: 'bar',
          //   data: [18, 35, 25, 48, 30],
          //   itemStyle: { color: '#52c41a' }
          // }
        ]
      };
      chart.setOption(barOption);
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
      };
    }

  },[])
  useEffect(()=>{
    // 折线图 - 工单趋势
    if (lineChartRef.current) {
      const chart = echarts.init(lineChartRef.current);
      const lineOption = {
        tooltip: {
          trigger: 'axis'
        },
        // legend: {
        //   data: ['申请工单', '完成工单'],
        //   textStyle: {
        //     fontSize: 12
        //   }
        // },
        grid: {
          top:'10%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value'
        },
        series: [

          {
            name: '完成工单',
            type: 'line',
            stack: '总量',
            data: [25, 27, 27, 29, 22, 26, 21],
            lineStyle: {
              color: '#52c41a'
            },

            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: 'rgba(82, 196, 26, 0.3)'},
                {offset: 1, color: 'rgba(82, 196, 26, 0.1)'}
              ])
            }
          }
        ]
      };
      chart.setOption(lineOption);
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
      };
    }

  },[])
  useEffect(()=>{
    // 柱状图 - 工单状态统计
    if (barChartRef2.current) {
      const chart = echarts.init(barChartRef2 .current);
      const barOption = {
        // 提示框（鼠标悬浮显示数据）
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        // 图例（多系列时开启）
        // legend: {
        //   top: 0,
        //   right: 10
        // },
        // 网格（调整图表内边距，适配容器）
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        // X轴（替换为你的实际标签）
        xAxis: {
          type: 'category',
          data: ['生产部', '研发部', '运维部', '财务部', '人事部'],
          axisLabel: { fontSize: 12 }
        },
        // Y轴
        yAxis: {
          type: 'value',
          axisLabel: { fontSize: 12 }
        },
        // 系列数据（替换为你的实际数值）
        series: [
          {
            name: '数据1',
            type: 'bar',
            data: [{value: 74, itemStyle: {color: '#C1D3D1'}}, {value: 95, itemStyle: {color: '#045F5E80'}}, {value: 96, itemStyle: {color: '#FFBC00'}}, {value: 65, itemStyle: {color: '#FF826D'}}, {value: 47, itemStyle: {color: '#045F5E80'}}], // 匹配X轴的数值
            // 柱子样式（可选）
            itemStyle: {
              // color: '#1890ff', // 阿里云蓝（可自定义）
              borderRadius: 4 // 圆角
            },
            label:{
              position:'top',
              color:'#333333',
              show: true
            },
            // 柱子宽度
            barWidth: '20%'
          },

        ]
      };
      chart.setOption(barOption);
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
      };
    }

  },[])
  // 表格数据
  const tableColumns = [
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department'
    },
    {
      title: '申请工单',
      dataIndex: 'applied',
      key: 'applied'
    },
    {
      title: '完成工单',
      dataIndex: 'completed',
      key: 'completed'
    },
    {
      title: '完成率',
      dataIndex: 'completionRate',
      key: 'completionRate',
      render: (rate) => <Tag color="#52c41a">{rate}</Tag>
    },
    {
      title: '平均处理时长',
      dataIndex: 'avgDuration',
      key: 'avgDuration'
    }
  ];

  const tableData = [
    { key: '1', department: '生产部', applied: 120, completed: 108, completionRate: '90%', avgDuration: '2.5天' },
    { key: '2', department: '技术部', applied: 85, completed: 82, completionRate: '96.5%', avgDuration: '1.8天' },
    { key: '3', department: '运维部', applied: 156, completed: 148, completionRate: '94.9%', avgDuration: '2.2天' },
    { key: '4', department: '财务部', applied: 45, completed: 45, completionRate: '100%', avgDuration: '1.2天' },
    { key: '5', department: '行政部', applied: 68, completed: 62, completionRate: '91.2%', avgDuration: '1.9天' }
  ];
  const pieColumns = [
    {
      title: '工单类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '数量',
      dataIndex: 'count',
      key: 'count',
    },
    {
      title: '占比',
      dataIndex: 'proportion',
      key: 'proportion',
    },
    {
      title: '平均处理时长',
      dataIndex: 'avgTime',
      key: 'avgTime',
    },
  ];
  const pieData = [
    {
      key: '1',
      type: '设备维修',
      count: 540,
      proportion: '45%',
      avgTime: '5.0小时',
    },
    {
      key: '2',
      type: '软件升级',
      count: 300,
      proportion: '25%',
      avgTime: '3.5小时',
    },
    {
      key: '3',
      type: '故障报修',
      count: 240,
      proportion: '20%',
      avgTime: '6.0小时',
    },
    {
      key: '4',
      type: '巡检任务',
      count: 120,
      proportion: '10%',
      avgTime: '2.0小时',
    },
  ];

  const pieColumns1=[
    {
      title: '排名',
      dataIndex: 'order',
      key: 'order',
    },
    {
      title: '故障原因',
      dataIndex: 'faultReason',
      key: 'faultReason',
    },
  ]
  const pieData1=[
    {
      key: '1',
      order: 'NO.1',
      faultReason: '传感器硬件损坏',
    },
    {
      key: '2',
      order: 'NO.2',
      faultReason: '网关软件版本不兼容',
    },
    {
      key: '3',
      order: 'NO.3',
      faultReason: '摄像头网络波动',
    },

  ]
  return (
    <div className={styles.container}>
      {/* 统计卡片 */}
      <Row gutter={[20, 20]} className={styles.statsSection}>
        <Col xs={24} sm={12} md={6}>
          <div className={styles.statCard}>
            <Row style={{width:'100%'}}>
                <Col span={8}>
                  <div style={{height: '100%',margin:'15px 0'}}>
                      <div className={styles.statValue}>1200</div>
                      <div className={styles.statTitle}>工单总数</div>
                  </div>
                </Col>
                <Col span={16}>
                  <div style={{color:'#666666'}}>月环比增长 <span>15</span>%</div>
                  <div ref={numberLineChartRef} style={{width:'100%',height:'100%',marginBottom:'-15px'}}></div>
                </Col>
            </Row>
          </div>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <div className={styles.statCard}>
            <Row style={{width: '100%'}}>
              <Col span={8}>
                <div style={{height: '100%', margin: '15px 0'}}>
                  <div className={styles.statValue}>85</div>
                  <div className={styles.statTitle}>故障设备数</div>
                </div>
              </Col>
              <Col span={16}>
                <div style={{color: '#666666'}}>月环比下降 <span>15</span>%</div>
                <div ref={numberLineChartRef1} style={{width: '100%', height: '100%', marginBottom: '-15px'}}></div>
              </Col>
            </Row>
            </div>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <div className={styles.statCard}>
            <Row style={{width: '100%'}}>
              <Col span={8}>
                <div style={{height: '100%', margin: '15px 0'}}>
                  <div className={styles.statValue}>92%</div>
                  <div className={styles.statTitle}>工单处理完成率</div>
                </div>
              </Col>
              <Col span={16} >
                <div style={{color: '#666666',lineHeight:'65px'}}>目标 95%，差距 3%</div>
                <progress value={92} max={100} style={{height:'28px',padding:0}}>70%</progress>
              </Col>
            </Row>
          </div>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <div className={styles.statCard}>
            <Row style={{width: '100%'}}>
              <Col span={8}>
                <div style={{height: '100%', margin: '15px 0'}}>
                  <div className={styles.statValue}>4.2小时</div>
                  <div className={styles.statTitle}>平均处理时长</div>
                </div>
              </Col>
              <Col span={16}>
                <div style={{color: '#666666'}}>月环比缩短 <span>0.5</span>小时</div>
                <div ref={numberLineChartRef2} style={{width: '100%', height: '100%', marginBottom: '-15px'}}></div>
              </Col>
            </Row>
          </div>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[20, 20]} className={styles.chartsSection}>
        {/* 饼图 */}
        <Col xs={24} lg={6}>
          <div className={styles.chartContainer}>
            <Title1 title={'工单类型统计'}></Title1>
            <div ref={pieChartRef} style={{height:'200px',width:'100%'}} />
            <div>
              <Table columns={pieColumns} dataSource={pieData} style={{width:'100%'}} pagination={false}></Table>
            </div>
          </div>
        </Col>
        {/* 柱状图 */}
        <Col xs={24} lg={6}>
          <div className={styles.chartContainer}>
            <Title1 title={'故障类型统计'}></Title1>
            <div ref={barChartRef} className={styles.chart}/>
            <div>
              <Table columns={pieColumns1} dataSource={pieData1} style={{width: '100%'}} pagination={false}></Table>
            </div>
          </div>
        </Col>
        {/* 折线图 */}
        <Col xs={24} lg={12}>
          <Row gutter={[20, 20]} style={{display:'flex',flexDirection:'column'}}>
            <Col xs={24} lg={24}>
              <div className={styles.chartContainer}>
                <Title1 title={'设备类型统计'}></Title1>
                <div ref={barChartRef1} className={styles.chart}/>
              </div>
            </Col>
            <Col xs={24} lg={24}>
              <div className={styles.chartContainer}>
                <Title1 title={'时间趋势统计'}></Title1>
                <div ref={lineChartRef} className={styles.chart}/>
              </div>
            </Col>
          </Row>
        </Col>
      </Row>

      {/* 部门统计表格 */}
      <Row gutter={20}>
        <Col span={6}>
          <div className={styles.chartContainer}>
            <Title1 title={'部门分布统计'}></Title1>
            <div ref={barChartRef2} className={styles.chart}/>
          </div>
        </Col>
        <Col span={18}>
          <div className={styles.chartContainer}>
            <Title1 title={'筛选导出'}></Title1>
            <Form layout={"vertical"}>
              <Row gutter={50} align={'middle'}>
                <Col span={8}>
                  <Form.Item label="工单类型" >
                    <Select>
                      <Option value="1">故障工单</Option>
                      <Option value="2">维护工单</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="设备类型" >
                    <Select>
                      <Option value="1">故障工单</Option>
                      <Option value="2">维护工单</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="故障类型" >
                    <Select>
                      <Option value="1">故障工单</Option>
                      <Option value="2">维护工单</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="时间范围" >
                    <DatePicker style={{width:'100%'}}></DatePicker>
                  </Form.Item>
                </Col>
                <Col span={8} offset={8} style={{textAlign:'right'}}>
                  <Button className={styles['search-button']} style={{marginRight:30}}>导出图表</Button>
                  <Button className={styles['reset-button']}>导出数据</Button>
                </Col>
              </Row>

            </Form>
          </div>
        </Col>
      </Row>

    </div>
  );
};

export default Analysis;
