import { useEffect, useRef, useState } from "react";
import { Button, Modal, Image, Select, Space, Table, Tag, Spin } from "antd";
import Echarts from "../../components/Echarts";
import { getAnswerRate, getQuestionParams, getLittleQuestion } 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, data } from "../mock/tableData";
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const StatisticsPage = () => {

  const [isShow1, setIsShow1] = useState(false);
  const [isShow2, setIsShow2] = useState(false);
  const [tableIsShow1, setTableIsShow1] = useState(false);
  const [tableIsShow2, setTableIsShow2] = useState(false);


  const [subtitle1, setSubtitle1] = useState('');
  const [dataSource1, setDataSource1] = useState([]);
  const [params1, setParams1] = useState({});
  const [columns1, setColumns1] = useState([]);
  const [loading1, setLoading1] = useState(false);
  const [echartData1, setEchartData1] = useState({});
  const [lengButton1, setLengButton1] = useState([]);
  const [expandedKeys1, setExpandedKeys1] = useState([]);
  const [subjectId1, setSubjectId1] = useState('');

  const [subtitle2, setSubtitle2] = useState('');
  const [dataSource2, setDataSource2] = useState([]);
  const [params2, setParams2] = useState({});
  const [columns2, setColumns2] = useState([]);
  const [loading2, setLoading2] = useState(false);
  const [echartData2, setEchartData2] = useState({});
  const [lengButton2, setLengButton2] = useState([]);
  const [expandedKeys2, setExpandedKeys2] = useState([]);
  const [subjectId2, setSubjectId2] = useState('');

  

  const [subjectName1, setSubjectName1] = useState(null);
  const [subjectName2, setSubjectName2] = useState(null);

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

  const [responseData2, setResponseData2] = useState({});
  const [responseData3, setResponseData3] = useState({});

  const [echartData3, setEchartData3] = useState({});

  const [echartData4, setEchartData4] = useState({});




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

  }, [params1?.examId, subjectId1, params1?.schools]);


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

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



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


  const singleSubjectInit = async () => {
    try {
      const res = await getSubjectList();
      if (res?.code === 200) {
        const element = res?.data?.find(item => item?.cname === "数学");
        setSubjectId1(res?.data?.[0]?.id || '');
        setSubjectId2(element?.id || '');
        setSubjectName1(res?.data?.[0]?.cname || '');
        setSubjectName2(element?.cname || '');
        setSingleSubjectList(() => {
          return res?.data?.map(item => {
            return {
              label: item?.cname,
              value: item?.id
            }
          })
        })
      }

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

    }
  };



  const answerRateInit = async () => {

    setLoading1(true);
    try {
      const res = await getAnswerRate({
        ...params1,
        subjectId: subjectId1
      });
      if (res?.code === 200) {
        setLoading1(false);
        setResponseData2(res);
        // setExpandedKeys1([res?.data?.[0]?.id || '']);
        setDataSource1(res?.data || []);
        setColumns1(() => {
          return res?.columns?.map(item => {
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false
            }
          })
        });
        if (!res?.columnDiagramResult?.rate?.[0]?.data?.length || !res?.columnDiagramResult?.rate?.[0]?.xdata?.length) {
          return;
        }
        setLengButton1([res?.columnDiagramResult?.rate?.[0]?.lineName]);
        setEchartData1(() => {
          return {
            xAxis: {
              name: "",
              type: "category",
              axisTick: { show: false },
              data: res?.columnDiagramResult?.rate?.[0]?.xdata,
            },
            yAxis: {
              name: '',
            },
            tooltip: {
              show: true,
            },
            yChartData: [
              {
                name: res?.columnDiagramResult?.rate?.[0]?.lineName,
                data: res?.columnDiagramResult?.rate?.[0]?.data
              }
            ],
          }
        });
        
        setEchartData3(()=>{
          return {
            radarText: {
              indicator: res?.columnDiagramResult?.rate?.[0]?.xdata?.map(item => {
                return {
                  name: item,
                  max: 100
                }
              }),
              yChartData: [
                {
                  name: res?.columnDiagramResult?.rate?.[0]?.lineName,
                  data: res?.columnDiagramResult?.rate?.[0]?.data,
                },
              ],
            },
          }
        })

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

    }

  };

  const littleQuestionInit = async () => {
    setLoading2(true);
    try {
      const res = await getLittleQuestion({
        ...params2,
        subjectId: subjectId2
      });
      if (res?.code === 200) {
        setResponseData3(res);
        setLoading2(false);
        setDataSource2(res?.data || []);
        setColumns2(() => {
          return res?.columns?.map(item => {
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width: item?.label === '区县' && 240,
              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;
        }
        setLengButton2([res?.columnDiagramResult?.difficult?.[0]?.lineName]);

        console.log({
          radarText: {
            indicator: res?.columnDiagramResult?.difficult?.[0]?.xdata?.map(item => {
              return {
                name: item,
                max: 1
              }
            }),
            yChartData: [
              {
                name: res?.columnDiagramResult?.difficult?.[0]?.lineName,
                data: res?.columnDiagramResult?.difficult?.[0]?.data,
              },
            ],
          },
        },'西湖666');
        
        setEchartData2(() => {
          return {
            radarText: {
              indicator: res?.columnDiagramResult?.difficult?.[0]?.xdata?.map(item => {
                return {
                  name: item,
                  max: 1
                }
              }),
              yChartData: [
                {
                  name: res?.columnDiagramResult?.difficult?.[0]?.lineName,
                  data: res?.columnDiagramResult?.difficult?.[0]?.data,
                },
              ],
            },
          }
        });

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

    }
  };

  const expandableConfig1 = {
    expandedRowKeys: expandedKeys1,
    defaultExpandedRowKeys: [dataSource1[0]?.id],
    expandIconColumnIndex: 2,
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys1([...expandedKeys1, record.id]);
      } else {
        setExpandedKeys1(expandedKeys1.filter((k) => k !== record.id));
      }
    },
  };

  const expandableConfig2 = {
    expandedRowKeys: expandedKeys2,
    expandIconColumnIndex: 2,
    onExpand: (expanded, record) => {
      if (expanded) {
        setExpandedKeys2([...expandedKeys2, record.id]);
      } else {
        setExpandedKeys2(expandedKeys2.filter((k) => k !== record.id));
      }
    },
  };

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

  const handleDownload2 = async () => {
    try {
      const res = await downloadTableData(responseData2);
      if (res?.status === 200) {
        downloadExcelFile(res, `${subtitle1}*${subjectName1}*考试选择题答题率分析`);
      }

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

    }
  };
  const handleDownload3 = async () => {
    try {
      const res = await downloadTableData(responseData3);
      if (res?.status === 200) {
        downloadExcelFile(res, `${subtitle2}*${subjectName2}*考试各小题分析`);
      }

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

    }
  };

  ///////////////////////////////
  return (
    <div style={{ padding: 20 }}>
      {/* 第一个表格 */}
      <ScreenPage
        isTeacher={true}
        isShowSubject={false}
        isShow={isShow1}
        onChange={(e) => {
          setSubtitle1([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[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),
          })
        }}
        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",
              }}
            >
              {subtitle1}
            </h3>
          </Flex>
          <Select
            placeholder="请选择学科"
            options={singleSubjectList}
            style={{ marginLeft: 20, width: "120px" }}
            value={subjectName1}
            onChange={(value, option) => {
              if (!value) {
                return;
              }
              setSubjectName1(option?.label);
              setSubjectId1(value);
            }}
          />
        </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}
          dataSource={dataSource1}
          columns={columns1}
          loading={loading1}
          rowKey="id"
          expandable={expandableConfig1}
        >
        </Table>
      ) : (
        <Spin spinning={loading1} tip='图表加载中'>
          <Echarts
            data={echartData1}
            isShow={false}
            type={"line"}
            text={`考试选择题答题率*${subtitle1}*${subjectName1}*折线图`}
            lengButton={lengButton1}
            onTableClick={(e) => {
              setTableIsShow1(false);
            }}
          />
          <section style={{ marginTop: 16 }}>
          <Echarts
            data={echartData3}
            type={"radar"}
            //   type={"line"}
            // type={"pie"}
            //   type={"bar"}
            isShow={false}
            text={`考试各小题分析*${subtitle1}*${subjectName1}*雷达图`}
            lengButton={lengButton1}
            onTableClick={(e) => {
              setTableIsShow1(false);
            }}
          />
          </section>
        </Spin>

      )}
      {!tableIsShow1 && (
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={handleDownload2}
          >
            导出表格
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              setTableIsShow1(true);
            }}
          >
            显示为图表
          </Button>
        </Flex>
      )}
      {/* 第二个表格 */}
      <ScreenPage
        isTeacher={true}
        isShowSubject={false}
        isShow={isShow2}
        onChange={(e) => {
          setSubtitle2([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[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),
          })
        }}
        saveshow={(e) => {
          setIsShow2(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>
            <Select
              placeholder="请选择学科"
              options={singleSubjectList}
              value={subjectName2}
              style={{ marginLeft: 20, width: "120px" }}
              onChange={(value, option) => {
                if (!value) {
                  return;
                }
                setSubjectName2(option?.label);
                setSubjectId2(value);
              }}
            />
          </Flex>
        </Flex>
        <Flex
          style={{
            padding: "4px 8px",
            border: "1px solid #666",
            borderRadius: 5,
            cursor: "pointer",
          }}
          alignItems="center"
          onClick={() => {
            setIsShow2(!isShow2);
          }}
        >
          选择考试和学校
          <img
            src={isShow2 ? upSrc : downSrc}
            width={14}
            height={12}
            style={{ marginLeft: 5 }}
          />
        </Flex>
      </Flex>
      {/* 表格 */}
      {!tableIsShow2 ? (
        <Table

          {...tableCommonProps}
          dataSource={dataSource2}
          rowKey="id"
          expandable={expandableConfig2}
          columns={columns2}
          loading={loading2}
        >
        </Table>
      ) : (
        <Spin spinning={loading2} tip='图表加载中'>
          <Echarts
            data={echartData4}
            // type={"radar"}
              type={"line"}
            // type={"pie"}
            //   type={"bar"}
            isShow={false}
            text={`考试各小题分析*${subtitle2}*${subjectName2}*折线图`}
            lengButton={lengButton2}
            onTableClick={(e) => {
              setTableIsShow2(false);
            }}
          />
          <section style={{marginTop: 16}}>
          <Echarts
            data={echartData2}
            type={"radar"}
            //   type={"line"}
            // type={"pie"}
            //   type={"bar"}
            isShow={false}
            text={`考试各小题分析*${subtitle2}*${subjectName2}*雷达图`}
            lengButton={lengButton2}
            onTableClick={(e) => {
              setTableIsShow2(false);
            }}
          />
          </section>
        </Spin>
      )}
      {!tableIsShow2 && (
        <Flex style={{ marginTop: 8 }}>
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={handleDownload3}
          >
            导出表格
          </Button>
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              setTableIsShow2(true);
            }}
          >
            显示为图表
          </Button>
        </Flex>
      )}
    </div>
  );
};

export default StatisticsPage;
