import { useEffect,useState,useRef } from "react";
import { Button, Spin, Table } from "antd";
import Echarts from "./components/Echarts";
import  StudentModal from '@/components/StudentModal';
import { TableTitle } from "./components/TableTitle";
import Flex from "@/components/Flex";
import Common from "@/utils/Common";
import { getCriticalStudentAnalysis,getTopStudentAnalysis,getBadSubjectStudentAnalysis,getRashStudentAnalysis } from '@/apis/leader';
import {buildBarAndPieOption} from '@/utils/table';
import {downloadTableData} from '@/apis/download';
import {downloadExcelFile} from '@/utils/file';
import "./index.less";

const buttonData = ["临界生", "优生劣科"];
const StatisticsPage = () => {
  const [selectButton, setSelectButton] = useState(buttonData);
  const [activeButtons, setActiveButtons] = useState(buttonData[0]); // 添加新的状态来跟踪选中的按钮
  const [showSearch, setShowSearch] = useState(false); //筛选框
  const [changeTable, setChangeTable] = useState(true);
  const [changeTableTwo, setChangeTableTwo] = useState(true);
  const [title, setTitle] = useState({
    point: "2027届*高一上*入学考试",
    other: "2027届*高一上*入学考试",
  }); // 图表筛选标题
  const [changeTitle, setChangeTitle] = useState(1); // 判断需要更改哪个图表 1是尖子生 2是临界生
  const [params1,setParams1] = useState({});
  const [dataSource1,setDataSource1] = useState([]);
  const [columns1,setColumns1] = useState([]);
  const [loading1,setLoading1] = useState(false);

  const [echartData1,setEchartData1] = useState({});

  const [lengButton1,setLengButton1] = useState([]);

  const [params2,setParams2] = useState({});
  const [loading2,setLoading2] = useState(false);

  const [dataSource2,setDataSource2] = useState([]);
  const [columns2,setColumns2] = useState([]);

  const [echartData2,setEchartData2] = useState({});

  const [lengButton2,setLengButton2] = useState([]);


  const [selected,setSelected] = useState('critical');


  const [topLimit,setTopLimit] = useState(0);

  const [otherParams,setOtherParams] = useState({});

  const [subtitle1,setSubtitle1] = useState('');
  const [subtitle2,setSubTitle2 ] = useState('');



  const studentRef = useRef();

  const [studentParams,setStudentParams] = useState({});

  const [criticalScore,setCriticalScore] = useState();

  const timer = useRef(null);

  const [responseData,setResponseData] = useState({});
  const [responseData1,setResponseData1] = useState({});

  useEffect(()=>{
    return () => {
      clearTimeout(timer.current);

    };
  },[])
  


  useEffect(() => {
    if(!Object.values(params1).length > 0){
      return;
    }
    init();

  }, [params1?.examId,params1?.subjectId,params1?.schools,topLimit]);


  useEffect(() => {
    if(!Object.values(params2).length > 0){
      return;
    }
    init2();

  }, [params2?.examId,params2?.subjectId,params2?.schools,selected,otherParams?.limit,otherParams?.rateOn,otherParams?.rateUnder]);


  const init = async () => {

    try {
        setLoading1(true);
        const res = await getTopStudentAnalysis({
          ...params1,
          limit:topLimit
        });
        if(res.code === 200){
          setLoading1(false);
          setResponseData(res);
          setLengButton1([res?.columnDiagramResult?.rate?.[0]?.lineName,res?.columnDiagramResult?.num?.[0]?.lineName]);
          const option = buildBarAndPieOption(res?.columnDiagramResult);
          setEchartData1(option);
          setDataSource1(res?.data|| []);
          setColumns1(()=>{
            return res?.columns?.map(item=>{

              if(item?.label === '学生姓名'){
                return {
                  title:item?.label,
                  dataIndex:item?.prop,
                  align:"center",
                  width:120,
                  render:(value,record)=>{

                    
                    return <Button type="link" onClick={()=>{
                      setStudentParams({
                        studentName:record?.name,
                        studentId:record?.studentId,
                        examId:params1?.examId,
                        school:record?.school
                      });
                      timer.current = setTimeout(() => {
                        studentRef?.current?.openModal();
                      }, 0);


                    }} style={{color:'#4ABB6A'}}>{value}</Button>
                  }
                }
              }
              return{
                title:item?.label,
                dataIndex:item?.prop,
                align:"center",
                width:160,
                children:item?.children?.map(element=>{
                    return{
                      title:element?.label,
                      dataIndex:element?.prop,
                      align:"center",
                      width:80,
                      sorter: (a, b) => a[element?.prop] - b[element?.prop],
                    }
                })
              }
            })
          })
          
        }
        setLoading1(false);

    } catch (error) {
        setLoading1(false);
        console.log(error,'student-error');
    }
  };


  const init2 = async() => {
    const API = {
      critical: getCriticalStudentAnalysis,
      badSubject:getBadSubjectStudentAnalysis,
      rash:getRashStudentAnalysis,
    };

    try {
      setLoading2(true);
      const res = await API?.[selected]({
        ...params2,
        ...otherParams
      });
      if(res.code === 200){
        if(selected === "critical"){
          setCriticalScore(res?.name);
        }
        setResponseData1(res);
        setLoading2(false);
        setLengButton2([res?.columnDiagramResult?.rate?.[0]?.lineName,res?.columnDiagramResult?.num?.[0]?.lineName])
        const option = buildBarAndPieOption(res?.columnDiagramResult);
        setEchartData2(option);
        setDataSource2(res?.data|| []);
        setColumns2(()=>{
          return res?.columns?.map(item=>{
            if(item?.label === '学生姓名'){
              return {
                title:item?.label,
                dataIndex:item?.prop,
                align:"center",
                width:100,
                render:(value,record)=>{

                  
                  return <Button type="link" onClick={()=>{
                    setStudentParams({
                      studentName:record?.name,
                      studentId:record?.studentId,
                      examId:params2?.examId,
                      school:record?.school
                    });
                    timer.current = setTimeout(() => {
                      studentRef?.current?.openModal();
                    }, 0);


                  }} style={{color:'#4ABB6A'}}>{value}</Button>
                }
              }
            }
            return{
              title:item?.label,
              dataIndex:item?.prop,
              align:"center",
              width:160,
              children:item?.children?.map(element=>{
                  return{
                    title:element?.label,
                    dataIndex:element?.prop,
                    align:"center",
                    width: 100,
                    sorter: element?.label !== "标签" ? (a, b) => a[element?.prop] - b[element?.prop] : false,
                  }
              })
            }
          })
        })
        
      }
      setLoading2(false);

  } catch (error) {
      console.log(error,'student-error');
  }
  };

  const tableCommonProps = {
    style: { maxHeight: 460},
    rowKey: "id",
    scroll: { x: 1500 ,y:340},
    sticky: true,
    pagination: false,
  };


  const handleDownload = async () => {
    try {
        const res = await downloadTableData(responseData);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle1}*尖子生情况分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };

  const handleDownload1 = async () => {
    try {
        const res = await downloadTableData(responseData1);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle2}*${activeButtons}情况分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };

  return (
    <div style={{ padding: "20px 20px" }}>
      {/* 表格1 */}
      <div>
        {/* 标题 */}
        <TableTitle
          title={" 尖子生情况分析"}
          subtitle={title.point}
          studentTitle="临界生"
          hasClass={false}
          hasAllCity={true}
          onChange={(value)=>{
            setParams1(value);
          }}
          onSearchClick={() => {
            setChangeTitle(1);
            setShowSearch(!showSearch);
          }}
          onLimitChange={(value)=>{
            setTopLimit(+value);
          }}
          onChangeTitle={(value)=>{
            setSubtitle1(value);
          }}
        />

        {/* 表格 */}
        {changeTable ? (
          <div style={{ height: 500 }}>
            <Table 
              {...tableCommonProps}
              dataSource={dataSource1}
              columns={columns1}
              loading={loading1}
              rowKey="studentId"
            >
              
            </Table>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                marginTop: 8,
              }}
            >
              <Flex>
                <Button
                  type="primary"
                  style={{ marginRight: 20 }}
                  disabled={!dataSource1.length > 0}
                  onClick={handleDownload}
                >
                  导出表格
                </Button>
                <Button
                  type="primary"
                  style={{ marginRight: 20 }}
                  onClick={() => {
                    setChangeTable(false);
                  }}
                >
                  显示为图表
                </Button>
              </Flex>
            </div>
          </div>
        ) : (
          <Spin spinning={loading1}>
            <Echarts
            data={echartData1}
            lengButton={lengButton1}
            needTab={true}
            text={`尖子生*${subtitle1}`}
            onTableClick={(val) => {
              setChangeTable(true);
            }}
          />
          </Spin>
          
        )}
      </div>

      {/* 表格2 */}
      <div style={{ marginTop: 20 }}>
        {/*  不同学生类型 */}
        {Array.isArray(selectButton) &&
          selectButton.length &&
          selectButton.map((but, index) => {
            return (
              <Button
                size={"small"}
                key={index}
                style={{
                  marginRight: 10,
                  backgroundColor: activeButtons == but ? "#e9f7ee" : "",
                  color: activeButtons == but ? "#3eb463" : "",
                  borderColor: activeButtons == but ? "#e9f7ee" : "",
                }}
                onClick={() => {
                  setActiveButtons(but);
                  if(but === '临界生'){
                    setSelected('critical');
                    return;
                  }
                  if(but === '优生劣科'){
                    setSelected('badSubject');
                    return;
                  }
                  if(but === '冒进生'){
                    setSelected('rash');
                    return;
                  }
                }}
              >
                {but}
              </Button>
            );
          })}

        {/* 标题 */}
        <TableTitle
          title={`${activeButtons}参数分析`}
          hasClass={false}
          subtitle={title.other}
          hasAllCity={true}
          studentTitle={activeButtons}
          criticalScore={criticalScore}
          hasOnline={true}
          onChange={(value)=>{
            setParams2(value);
          }}
          onSearchClick={() => {
            setChangeTitle(1);
            setShowSearch(!showSearch);
          }}
          onLineChange={(value)=>{
            console.log(value,'student-value');
            
            setOtherParams({
              limit: +value?.allCity,
              rateOn: +value?.online,
              rateUnder: +value?.noLine
            })
          }}
          onChangeTitle={(value)=>{
            setSubTitle2(value);
          }}
        />
        {/* 表格 */}
        {changeTableTwo ? (
          <div style={{ height: 500 }}>
            <Table
              {...tableCommonProps}
              dataSource={dataSource2}
              columns={columns2}
              loading={loading2}
              rowKey="studentId"
            >
            </Table>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                marginTop: 8,
              }}
            >
              <Flex>
                <Button
                  type="primary"
                  style={{ marginRight: 20 }}
                  disabled={!dataSource2.length > 0}
                  onClick={handleDownload1}
                >
                  导出表格
                </Button>
                <Button
                  type="primary"
                  style={{ marginRight: 20 }}
                  onClick={() => {
                    setChangeTableTwo(false);
                  }}
                >
                  显示为图表
                </Button>
              </Flex>
            </div>
          </div>
        ) : (
          <Spin spinning={loading2}>
            <Echarts
            data={echartData2}
            lengButton={lengButton2}
            needTab={true}
            text={`${activeButtons}*${subtitle2}`}
            onTableClick={(val) => {
              setChangeTableTwo(true);
            }}
          />
          </Spin>
          
        )}
      </div>
      <StudentModal ref={studentRef} params={studentParams}/>
    </div>
  );
};

export default StatisticsPage;
