import { useEffect, useRef, useState } from "react";
import { Button, Select, Space, Table,Spin } from "antd";
import Echarts from "../../components/Echarts";
import ScreenPage from "@/components/ScreenPage";
import StudentGroup from '@/components/StudentGroup';
import Flex from "@/components/Flex";
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import { getSchoolAnalysis, getSchoolPercentAnalysis,getSchoolParams } from '@/apis/leader';
import { getSubjectList } from '@/apis/subject';
import { buildEchartData, removeEmptyChildren } from '@/utils/table';
import {downloadTableData} from '@/apis/download';
import {downloadExcelFile} from '@/utils/file';

const StatisticsPage = () => {
  const [isShow, setIsShow] = useState(false);
  const [isShow1, setIsShow1] = useState(false);
  const [tableIsShow, setTableIsShow] = useState(false);
  const [tableIsShow1, setTableIsShow1] = useState(false);
  const [expandedKeys1, setExpandedKeys1] = useState([]); // 添加展开行的状态管理

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

  const [params1, setParams1] = useState({});
  const [params2, setParams2] = useState({});


  const [dataSource1, setDataSource1] = useState([]);
  const [columns1, setColumns1] = useState([]);

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

  const [loading1, setLoading1] = useState(false);
  const [loading2, setLoading2] = useState(false);

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

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


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

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

  const [expandedKeys2, setExpandedKeys2] = useState([]);

  const studentGroupRef = useRef();


  const [title, setTitle] = useState('');

  const [studentGroupParams, setStudentGroupParams] = useState({});
  const [responseData1,setResponseData1] = useState({});
  const [responseData2,setResponseData2] = useState({});

  const [subtitle3, setSubtitle3] = useState('');
  const [params3, setParams3] = useState({});
  const [dataSource3, setDataSource3] = useState([]);
  const [columns3, setColumns3] = useState([]);
  const [loading3, setLoading3] = useState(false);
  const [echartData3, setEchartData3] = useState({});
  const [lengButton3, setLengButton3] = useState([]);
  const [responseData3,setResponseData3] = useState({});
  const [expandedKeys3, setExpandedKeys3] = useState([]);
  const [isShow3, setIsShow3] = useState(false);
  const [tableIsShow3, setTableIsShow3] = useState(false);

  const [subjectIds, setSubjectIds] = useState([]);

  const [selectValues, setSelectValues] = useState([]);
  
  const [scoreLine,setScoreLine] = useState({});

  useEffect(() => { 
    getSubjectSelectOptions();
  }, []);

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

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

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

  }, [params2?.examId, params2?.subjectId, params2?.schools]);

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

  }, [params3?.examId, params3?.subjectId, params3?.schools]);


  const init = async () => {
    try {
      setLoading1(true);
      const res = await getSchoolAnalysis({
        ...params1,
        scoreLine,
      });
      if (res?.code === 200) {
        setLoading1(false);
        setResponseData1(res);
        const list = removeEmptyChildren(res.data);
        setDataSource1(list);
        const data = buildEchartData(res?.columnDiagramResult?.num);
        setExpandedKeys1([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
        setEchartData1(data);
        setLengButton1(res?.columnDiagramResult?.num?.map(item => item?.lineName));
        setColumns1(() => {
          return res?.columns?.map(item => {
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width: item?.label === '区县' ? 300 : 260,
              children: item?.children?.map(element => {
                if (element?.label === '人数') {
                  return {
                    title: element?.label,
                    dataIndex: element?.prop,
                    align: "center",
                    width:120,
                    render: (text) => (
                      <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                          setTitle(text?.typeDisc);
                          studentGroupRef.current?.openModal();
                          setStudentGroupParams({
                            examId:params1?.examId,
                            students:text?.data
                          });
                      }}>{text?.value}</Button>
                    ),
                  }
                }
                return {
                  title: element?.label,
                  dataIndex: element?.prop,
                  align: "center",
                  width:120,
                  sorter: (a, b) => a[element?.prop] - b[element?.prop],
                }
              })

            }
          })

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

    }
  };


  const percentInit = async () => {
    try {
      setLoading2(true);
      const res = await getSchoolPercentAnalysis(params2);
      if (res?.code === 200) {
        setLoading2(false);
        setResponseData2(res);
        setExpandedKeys2([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
        const list = removeEmptyChildren(res.data);
        setDataSource2(list);
        const data = buildEchartData(res?.columnDiagramResult?.num);
        
        setEchartData2(data);
        setLengButton2(res?.columnDiagramResult?.num?.map(item => item?.lineName));
        setColumns2(() => {
          return res?.columns?.map(item => {
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width: 300,
              children: item?.children?.map(element => {
                if (element?.label === '人数') {
                  return {
                    title: element?.label,
                    dataIndex: element?.prop,
                    width: 150,
                    align: "center",
                    render: (text) => (
                      <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                        setTitle(text?.typeDisc);
                        studentGroupRef.current?.openModal();
                        setStudentGroupParams({
                          examId:params2?.examId,
                          students:text?.data
                        });
                      }}>{text?.value}</Button>
                    ),
                  }
                }
                return {
                  title: element?.label,
                  dataIndex: element?.prop,
                  align: "center",
                  width: 150,
                  sorter: (a, b) => a[element?.prop] - b[element?.prop],
                }
              })

            }
          })

        });
      }
      setLoading2(false);
    } catch (error) {
      setLoading2(false);
      console.log(error, 'init-error');

    }
  };


  const paramInit = async () => {
    try {
        setLoading3(true);
        const res = await getSchoolParams(params3);
        if(res?.code === 200){
          setLoading3(false);
          setResponseData3(res);

          const data = {
            xAxis: {
              name: "地区",
              type: "category",
              axisTick: { show: false },
              data:res?.columnDiagramResult?.avg?.[0]?.xdata,
            },
            tooltip: {
              show: true,
            },
            yAxis: { name: "" },
            yChartData:Object.entries(res?.columnDiagramResult).map(([_, items]) => ({
              name:items?.[0]?.lineName,
              data: items?.[0].data
            })),
          }
          
          setEchartData3(data);
          setLengButton3(()=>{
            return Object.entries(res?.columnDiagramResult).map(([_, items]) => (items?.[0]?.lineName))
          });
          setExpandedKeys3([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
          setColumns3(()=>{
            return res?.columns?.map(item=>{


              if (item?.label === '考试人数') {
                return {
                  title: item?.label,
                  dataIndex: item?.prop,
                  width: 140,
                  align: "center",
                  render: (text,record) => (
                    <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                      setTitle(record?.num?.typeDisc);
                      studentGroupRef.current?.openModal();
                      setStudentGroupParams({
                        examId:params3?.examId,
                        students:record?.num?.data
                      });
                    }}>{record?.num?.value}</Button>
                  ),
                }
              }
              return {
                title:item?.label,
                dataIndex:item?.prop,
                align:"center",
                width:item?.label === '区县' ? 300 : 140,
                sorter:item?.label !== '区县'?(a,b)=>a[item?.prop] - b[item?.prop] : false
              }
            })
          });
          setDataSource3(res?.data);
          

          return;
        }
      setLoading3(false);
    } catch (error) {
      setLoading3(false);
      console.log(error, 'paramInit-error');
      
    }
  };


  ////////////////////////////
  //展开表格行
  const expandableConfig1 = {
    expandedRowKeys: expandedKeys1,
    defaultExpandedRowKeys: [dataSource1?.[0]?.id,dataSource1?.[0]?.children?.[0]?.id],
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys1([...expandedKeys1, record.id]);
      } else {
        setExpandedKeys1(expandedKeys1.filter((k) => k !== record.id));
      }
    },
  };
  const tableCommonProps = {
    style: { maxHeight: 460},
    rowKey: "id",
    scroll: { x: 1500,y:340 },
    sticky: true,
    pagination: false,
  };


  const expandableConfig2 = {
    expandedRowKeys: expandedKeys2,
    defaultExpandedRowKeys: [dataSource2?.[0]?.id,dataSource2?.[0]?.children?.[0]?.id],
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys2([...expandedKeys2, record.id]);
      } else {
        setExpandedKeys2(expandedKeys2.filter((k) => k !== record.id));
      }
    },
  };

  const expandableConfig3 = {
    expandedRowKeys: expandedKeys3,
    defaultExpandedRowKeys: [dataSource3?.[0]?.id,dataSource3?.[0]?.children?.[0]?.id],
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys3([...expandedKeys3, record.id]);
      } else {
        setExpandedKeys3(expandedKeys3.filter((k) => k !== record.id));
      }
    },
  };

  const handleDownload1 = async () => {
    try {
        const res = await downloadTableData(responseData1);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle1}*学校排名分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };
  const handleDownload2 = async () => {
    try {
        const res = await downloadTableData(responseData2);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle2}*学校排名百分比分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };


  const handleDownload3 = async () => {
    try {
        const res = await downloadTableData(responseData3);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle3}*当前考试参数情况分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };

  const getSubjectSelectOptions = async () => {
      try {
        const res = await getSubjectList({ stages: 3, contain256: false, level: 1, single: true, showFlag: true });
        if (res?.code === 200) {
  
          setSelectValues(() => {
            return res?.data?.map(item => {
              return {
                label: item?.cname,
                value: item?.id
              }
            })
          })
        }
      } catch (error) {
        console.log(error, 'getSubjectSelectOptions-error');
  
      }
    };
  ///////////////////////////////
  return (
    <div style={{ padding: 20 }}>
      {
        <ScreenPage
          isShow={isShow}
          isShowSubject={true}
          onChange={(e) => {
            setSubtitle1([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name, e?.currentDiscipline?.[0]?.name || ''].filter(item => !!item).join("*"));

            setParams1({
              examId: e?.examId,
              schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item=>item?.id),
              subjectId: e?.currentDiscipline?.[0]?.id || '',
            })
          }}
          saveshow={(e) => {
            setIsShow(e);
          }}
        />
      }
      {/* 标题 */}
      <Flex
        style={{
          display: "flex",
          alignItems: "center",
          margin: "20px 0",
          gap: 12,
        }}
        justify="space-betweens"
        alignItems="center"
      >
        <Flex style={{ flex: 1 }} alignItems="center">
          <Flex
            style={{
              display: "flex",
              alignItems: "center",
              color: "#8a8a8a",
            }}
          >
            当前考试排名情况分析 : &nbsp;
            <h3
              style={{
                color: "black",
              }}
            >
              {subtitle1}
            </h3>
          </Flex>
        </Flex>
        <Flex
          style={{
            padding: "4px 8px",
            border: "1px solid #666",
            borderRadius: 5,
            cursor: "pointer",
          }}
          alignItems="center"
          onClick={() => {
            setIsShow(!isShow);
          }}
        >
          选择考试和学校
          <img
            src={isShow ? upSrc : downSrc}
            width={14}
            height={12}
            style={{ marginLeft: 5 }}
          />
        </Flex>
      </Flex>
      {/* 表格 */}
      <section style={{ display: "flex", alignItems: "center",marginBottom:8 }}>
          <span style={{ color: " #8a8a8a" }}>设置选科范围：</span>
          <Space>
          <Select style={{ width: 260 }} maxTagCount={2} value={subjectIds} placeholder='请选择学科'  mode='multiple' allowClear options={selectValues} onChange={(value, options) => {
            if (!value.length) {
              setSubjectIds([]);
              
              return;
            }
            setSubjectIds(value);
      

          }} />
          <Button onClick={()=>{
            const list = selectValues?.filter(item=>subjectIds?.includes(item?.value));
            setScoreLine(()=>{
              return {
                name:list?.map(item=>item?.label)?.join(','),
                combIds:list?.map(item=>item?.value)?.join(',')
              }
            })
            // setCombIds(subjectIds);
          }}>确定</Button>
          </Space>
        </section>
      {!tableIsShow ? (
        <Table
          {...tableCommonProps}
          dataSource={dataSource1}
          columns={columns1}
          loading={loading1}
          rowKey="id"
          expandable={expandableConfig1}
          // pagination={{
          //   position: ["none", "none"],
          // }}
        >
        </Table>
      ) : (
        <Spin spinning={loading1}>
          <Echarts
          data={echartData1}
          type={"bar"}
          text={`${subtitle1}*考试排名情况分析`}
          lengButton={lengButton1}
          onTableClick={(e) => {
            setTableIsShow(false);
          }}
        />
        </Spin>
        
      )}
      {!tableIsShow && (
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10, margintop: 10 }}
            disabled={!dataSource1?.length > 0}
            onClick={handleDownload1}
          >
            导出表格
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              setTableIsShow(true);
            }}
          >
            显示为图表
          </Button>
        </Flex>
      )}
      <ScreenPage
        isShow={isShow1}
        isShowSubject={true}
        onChange={(e) => {
          setSubtitle2([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name, e?.currentDiscipline?.[0]?.name || ''].filter(item => !!item).join("*"));

          setParams2({
            examId: e?.examId,
            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item=>item?.id),
            subjectId: e?.currentDiscipline?.[0]?.id || '',
          })
          // let list = Common.cartesianProduct(
          //   ...[e.currentGrade, e.currentSemester, e.currentExamination]
          // );

          // setExamination1(list[0]);
        }}
        saveshow={(e) => {
          setIsShow1(e);
        }}
      />
      <Flex
        style={{
          display: "flex",
          alignItems: "center",
          margin: "20px 0",
          gap: 12,
        }}
        justify="space-betweens"
        alignItems="center"
      >
        <Flex style={{ flex: 1 }} alignItems="center">
          <Flex
            style={{
              display: "flex",
              alignItems: "center",
              color: "#8a8a8a",
            }}
          >
            当前考试排名情况百分比分析 : &nbsp;
            <h3
              style={{
                color: "black",
              }}
            >
              {subtitle2}
            </h3>
          </Flex>
        </Flex>
        <Flex
          style={{
            padding: "4px 8px",
            border: "1px solid #666",
            borderRadius: 5,
            cursor: "pointer",
          }}
          alignItems="center"
          onClick={() => {
            setIsShow1(!isShow1);
          }}
        >
          选择考试和学校
          <img
            src={isShow1 ? upSrc : downSrc}
            width={14}
            height={12}
            style={{ marginLeft: 5 }}
          />
        </Flex>
      </Flex>
      {/* 表格 */}
      {!tableIsShow1 ? (
        <Table

          {...tableCommonProps}
          // pagination={{
          //   position: ["none", "none"],
          // }}
          rowKey="id"
          loading={loading2}
          columns={columns2}
          dataSource={dataSource2}
          expandable={expandableConfig2}
        >
        </Table>
      ) : (
        <Spin spinning={loading2}>
          <Echarts
          data={echartData2}
          type={"bar"}
          text={`${subtitle2}*当前考试排名情况百分比分析`}
          lengButton={lengButton2}
          onTableClick={(e) => {
            setTableIsShow1(false);
          }}
        />
        </Spin>
      )}
      {!tableIsShow1 && (
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            disabled={!dataSource2.length > 0}
            onClick={handleDownload2}
          >
            导出表格
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              setTableIsShow1(true);
            }}
          >
            显示为图表
          </Button>
        </Flex>
      )}
  {
        <ScreenPage
          isShow={isShow3}
          isShowSubject={true}
          onChange={(e) => {
            setSubtitle3([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name, e?.currentDiscipline?.[0]?.name || ''].filter(item => !!item).join("*"));

            setParams3({
              examId: e?.examId,
              schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item=>item?.id),
              subjectId: e?.currentDiscipline?.[0]?.id || '',
            })
          }}
          saveshow={(e) => {
            setIsShow3(e);
          }}
        />
      }
      {/* 标题 */}
      <Flex
        style={{
          display: "flex",
          alignItems: "center",
          margin: "20px 0",
          gap: 12,
        }}
        justify="space-betweens"
        alignItems="center"
      >
        <Flex style={{ flex: 1 }} alignItems="center">
          <Flex
            style={{
              display: "flex",
              alignItems: "center",
              color: "#8a8a8a",
            }}
          >
            当前考试参数情况分析 : &nbsp;
            <h3
              style={{
                color: "black",
              }}
            >
              {subtitle3}
            </h3>
          </Flex>
        </Flex>
        <Flex
          style={{
            padding: "4px 8px",
            border: "1px solid #666",
            borderRadius: 5,
            cursor: "pointer",
          }}
          alignItems="center"
          onClick={() => {
            setIsShow3(!isShow3);
          }}
        >
          选择考试和学校
          <img
            src={isShow3 ? upSrc : downSrc}
            width={14}
            height={12}
            style={{ marginLeft: 5 }}
          />
        </Flex>
      </Flex>
      {/* 表格 */}
      {!tableIsShow3 ? (
        <Table
          {...tableCommonProps}
          dataSource={dataSource3}
          columns={columns3}
          loading={loading3}
          rowKey="id"
          expandable={expandableConfig3}
          // pagination={{
          //   position: ["none", "none"],
          // }}
        >
        </Table>
      ) : (
        <Spin spinning={loading3}>
          <Echarts
          data={echartData3}
          type={"bar"}
          text={`${subtitle3}*当前情况基本参数分析`}
          lengButton={lengButton3}
          onTableClick={(e) => {
            setTableIsShow3(false);
          }}
        />
        </Spin>
        
      )}
      {!tableIsShow3 && (
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10, margintop: 10 }}
            disabled={!dataSource3?.length > 0}
            onClick={handleDownload3}
          >
            导出表格
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              setTableIsShow3(true);
            }}
          >
            显示为图表
          </Button>
        </Flex>
      )}
      <StudentGroup
        ref={studentGroupRef}
        params={studentGroupParams}
        title={title}
      />


      
    </div>
  );
};

export default StatisticsPage;
