import { useEffect, useRef, useState } from "react";
import { Button, Modal, Image, Select, Space, Table, Tag, Spin } from "antd";
import Echarts from "../../components/Echarts";
import { getKnowledgePoint } from '@/apis/leader';
import { getSubjectList } from '@/apis/common';
import ScreenPage from "@/components/ScreenPage";
import Flex from "@/components/Flex";
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import Common from "@/utils/Common";
import StudentModal from "./components/StudentModal";
import { studentData, studentCol } from "../mock/tableData";
import { totalScore } from "./components/TableTitle";
import {downloadTableData} from '@/apis/download';
import {downloadExcelFile} from '@/utils/file';

const StatisticsPage = () => {

  const [isShow, setIsShow] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);



  const [subtitle, setSubtitle] = useState('');
  const [dataSource, setDataSource] = useState([]);
  const [params, setParams] = useState({});
  const [columns, setColumns] = useState([]);
  const [loading, setLoading] = useState(false);
  const [echartData, setEchartData] = useState({});
  const [lengButton, setLengButton] = useState([]);



  const [singleSubjectList, setSingleSubjectList] = useState([]);

  const [subjectId, setSubjectId] = useState('');

  const [subjectName, setSubjectName] = useState(null);

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



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

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


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



  const singleSubjectInit = async () => {
    try {
      const res = await getSubjectList();
      if (res?.code === 200) {
        setSubjectId(res?.data?.[0]?.id || '');
        setSubjectName(res?.data?.[0]?.cname || null);
        setSingleSubjectList(() => {
          return res?.data?.map(item => {
            return {
              label: item?.cname,
              value: item?.id
            }
          })
        })
      }

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

    }
  };

  const init = async () => {

    setLoading(true);
    try {
      const res = await getKnowledgePoint({
        ...params,
        subjectId,
      });
      if (res?.code === 200) {
        setResponseData(res);
        setLoading(false);
        setDataSource(res?.data || []);
        setColumns(() => {
          return res?.columns?.map(item => {
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width: 300,
              sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false
            }
          })
        });

        if (!res?.columnDiagramResult?.difficult?.[0]?.data?.length || !res?.columnDiagramResult?.difficult?.[0]?.xdata?.length) {
          return;
        }
        console.log(res?.columnDiagramResult?.difficult?.[0]?.lineName, '小题图表数据');

        setLengButton(res?.columnDiagramResult?.difficult?.map(item => item?.lineName));
        console.log(res?.columnDiagramResult?.difficult?.map(item => item?.lineName), '筛选标签');

        setEchartData(() => {
          return {
            xAxis: {
              name: "",
              type: "category",
              axisTick: { show: false },
              data: res?.columnDiagramResult?.difficult?.[0]?.xdata,
            },
            yAxis: {
              name: '',
            },
            tooltip: {
              show: true,
            },
            yChartData: res?.columnDiagramResult?.difficult?.map(item => {
              return {
                name: item?.lineName,
                data: item?.data
              }
            }),
            radarText: {
              indicator: res?.columnDiagramResult?.difficult?.[0]?.xdata?.map(item => {
                return {
                  name: item,
                }
              }),
              yChartData: res?.columnDiagramResult?.difficult?.map(item => {
                return {
                  name: item?.lineName,
                  data: item?.data
                }
              })
            },
          }
        });
      }
    } catch (error) {
      console.log(error, 'knowledge-error');

    }
  }


  ////////////////////////////
  //展开表格行
  const expandableConfig = {
    expandedRowKeys: expandedKeys,
    defaultExpandedRowKeys: [dataSource[0]?.id],
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys([...expandedKeys, record.id]);
      } else {
        setExpandedKeys(expandedKeys.filter((k) => k !== record.id));
      }
    },
  };

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


  const handleDownload = async () => {
    try {
        const res = await downloadTableData(responseData);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle}*${subjectName}*考试知识点分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };

  ///////////////////////////////
  return (
    <div style={{ padding: 20 }}>
      {
        <ScreenPage
          isTeacher={true}
          isShowSubject={false}
          isShow={isShow}
          onChange={(e) => {

            setSubtitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
            setParams({
              examId: e?.examId,
              schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.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",
              }}
            >
              {subtitle}
            </h3>
            <Select
              placeholder="请选择学科"
              options={singleSubjectList}
              value={subjectName}
              style={{ marginLeft: 20, width: "120px" }}
              onChange={(value, option) => {
                if (!value) {
                  return;
                }
                setSubjectName(option?.label || null);
                setSubjectId(value || '');
              }}
            />
          </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>
      {/* 表格 */}

      <Table
        {...tableCommonProps}
        dataSource={dataSource}
        rowKey="id"
        sticky={true}
        expandable={expandableConfig}
        pagination={false}
        columns={columns}
        loading={loading}
      >
      </Table>

      {
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10, margintop: 10 }}
            onClick={handleDownload}
          >
            导出表格
          </Button>
        </Flex>
      }

      {/* 表格 */}
      {
        <section style={{ marginTop: 16 }}>
          <Spin spinning={loading}>
            <Echarts
              data={echartData}
              type={"line"}
              text={`考试知识点分析${subtitle}*${subjectName}*折线图`}
              hasTable={false}
              isShow={true}
              lengButton={lengButton}
              onTableClick={(e) => { }}
            />
          </Spin>
        </section>
      }

      {/* 表格 */}
      {
        <Spin spinning={loading}>
          <Echarts
            data={echartData}
            type={"radar"}
            hasTable={false}
            isShow={true}
            text={`考试知识点分析${subtitle}*${subjectName}*雷达图`}
            lengButton={lengButton}
            onTableClick={(e) => { }}
          />
        </Spin>

      }
    </div>
  );
};

export default StatisticsPage;
