import { useEffect, useState, useRef } from "react";
import { Button, Table, Spin, Space, Tag, InputNumber, Select, message } from "antd";
import StudentGroup from '@/components/StudentGroup';
import ScoreLineSelect from '@/components/ScoreLineSelect';
import SchoolChoice from '@/components/SchoolChoice';
import Echarts from "../../components/Echarts";
import { TableTitle } from "./components/TableTitle";
import { getOnlineAnalysis } from '@/apis/leader';
import { getScoreLineList } from '@/apis/data';
import { getSubjectList } from '@/apis/subject';
import { buildEchartData, removeEmptyChildren } from '@/utils/table'
import "./index.less";
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const StatisticsPage = () => {
  const [showSearch, setShowSearch] = useState(false);

  const [expandedKeys, setExpandedKeys] = 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 studentGroupRef = useRef();


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

  const [studentGroupParams, setStudentGroupParams] = useState({});

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

  const [scoreList, setScoreList] = useState([]);


  const [rankingList, setRankingList] = useState([]);
  const [selectRaking, setSelectRaking] = useState('');


  const [tagList, setTagList] = useState([]);
  const [selectTag, setSelectTag] = useState('');
  const [allEchartData, setAllEchartData] = useState({});

  const [selectValues, setSelectValues] = useState([]);

  const [schoolIds, setSchoolIds] = useState([]);


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

  const [subjectOptions, setSubjectOptions] = useState([]);
  const [scoreLine, setScoreLine] = useState([]);

  const [score, setScore] = useState(null);


  const [scoreLineList, setScoreLineList] = useState([]);
  const [loading2, setLoading2] = useState(false);

  const [scoreLine2, setScoreLine2] = useState([]);

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

  useEffect(() => {
    if (params?.examId) {
      getSortInit();
    }
  }, [params?.examId]);

  useEffect(() => {

    if (!params?.examId) {
      return;
    }
    init();

  }, [params?.examId, schoolIds, scoreLine]);

  useEffect(() => {

    if (!params?.examId) {
      return;
    }

    chartInit();

  }, [params?.examId, schoolIds, scoreLine, scoreLine2]);

  useEffect(() => {
    
    if (selectTag === "上线人数") {
      
      const data = buildEchartData(allEchartData?.num);
      setEchartData(data);
      setLengButton(allEchartData?.num?.map(item => item?.lineName));

    }
    if (selectTag === "上线率") {
      const data = buildEchartData(allEchartData?.incr);
      setEchartData(data);
      setLengButton(allEchartData?.incr?.map(item => item?.lineName));
    }

  }, [selectTag])

  const init = async () => {
    try {
      setLoading(true);
      const res = await getOnlineAnalysis({
        ...params,
        scoreLines: scoreLine,
        lineId: '',
        schools: schoolIds,
      });
      if (res?.code === 200) {
        setResponseData(res);
        setLoading(false);
        const list = removeEmptyChildren(res.data);
        setDataSource(list);

        setExpandedKeys([res?.data?.[0]?.id, res?.data?.[0]?.children?.[0]?.id]);
        setColumns(() => {
          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,
                    align: "center",
                    width: 120,
                    render: (text) => (
                      <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                        setTitle(text?.typeDisc);
                        studentGroupRef.current?.openModal();
                        setStudentGroupParams({
                          examId: params?.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],
                }
              })

            }
          })

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

    }
  };


  const chartInit = async () => {
    try {
      setLoading2(true);
      const res = await getOnlineAnalysis({
        ...params,
        scoreLines: scoreLine?.length > 0 ? scoreLine : scoreLine2,
        lineId: selectRaking,
        schools: schoolIds,
      });
      
      if (res?.code === 200) {
        setLoading2(false);
        setTagList(['上线人数', '上线率']);
        setSelectTag('上线人数');
        const data = buildEchartData(res?.columnDiagramResult?.num);
        
        setEchartData(data);
        setLengButton(res?.columnDiagramResult?.num?.map(item => item?.lineName));
        setAllEchartData(res?.columnDiagramResult);
      }
      setLoading2(false);
    } catch (error) {
      setLoading2(false);
      console.log(error, 'init-error');

    }
  };

  const getSortInit = async () => {
    try {
      const res = await getScoreLineList({ stage: 3, examId: params?.examId });
      if (res?.code === 200) {
        const list = res?.data?.map(item => ({
          id: item?.id,
          score: item?.score,
          name: item?.name,
          combIds: item?.combIds,
        }));
        setRankingList(list);
        setScoreLine2([list?.[0]]);
      }

    } catch (error) {
      console.log(error, 'get-sort-init-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');

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

  const handleDownload = async () => {
    try {
      const res = await downloadTableData(responseData);
      if (res?.status === 200) {
        downloadExcelFile(res, `${subTitle}*${scoreLineList?.length > 0 ? scoreLine?.map(item => item?.name)?.join(',') : scoreLine2?.map(item => item?.name)?.join(',')}`);
      }

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

    }
  };

  return (
    <div style={{ padding: 20 }}>
      {/* 标题 */}
      <TableTitle
        title={" 当前考试排名情况分析"}
        hasClass={false}
        isShowSchool={false}
        isShowSubject={false}
        onChange={(value) => {
          setParams(value);
        }}
        onSearchClick={() => {
          setShowSearch(!showSearch);
        }}
        onChangeTitle={(title) => {
          const str = title?.split('*')?.splice(0,3)?.join('*');
          setSubTitle(str);

        }}
      />
      {/* 表格 */}
      <div style={{ marginBottom: 16 }}>
        <section style={{ display: "flex", alignItems: "center" }}>
          <span style={{ color: " #8a8a8a" }}>学校选择：</span>
          <SchoolChoice onChange={(value) => {
            setSchoolIds(value);
          }} />
        </section>
        <section style={{ display: "flex", alignItems: "center" }}>
          <span style={{ color: " #8a8a8a" }}>设置选科范围：</span>
          <Select style={{ width: 260 }} maxTagCount={2} placeholder='请选择学科' value={subjectIds} mode='multiple' allowClear options={selectValues} onChange={(value, options) => {
            if (!value.length) {
              setSubjectIds([]);
              setSubjectOptions([]);
              return;
            }
            setSubjectIds(value);
            setSubjectOptions(options);

          }} />
        </section>
        <section style={{ display: "flex", alignItems: "center", marginTop: 16 }}>
          <span style={{ color: " #8a8a8a" }}>设置分数线：</span>
          <InputNumber
            min={1}
            value={score}
            onChange={(value) => setScore(value)}
            style={{ width: 120 }}
          />
          &nbsp;&nbsp;分以上&nbsp;&nbsp;
          <Button onClick={() => {
            if (typeof score !== 'number') {
              message.error('请输入数字');
              return;
            }

            const item = {
              score,
              name: !!subjectOptions?.length ? `总分${score}以上，选${subjectOptions?.map(item => item?.label).join('，')}` : `总分${score}以上`,
              combIds: subjectIds?.join(',')
            };
            if (scoreLineList?.map(item => item?.name).includes(item.name)) {
              message.error('该分数线已存在，勿重新添加');
              return;
            }
            // if (scoreLine?.map(element => element?.name)?.includes(item?.name)) {
            //   // 如果 Tag 已经选中，则移除
            //   setScoreLine((prev) => {
            //     if (prev.length === 1) {
            //       return prev;
            //     }
            //     return scoreLine.filter((element) => element?.name !== item?.name)
            //   });


            // } else {
            //   // 如果 Tag 未选中，则添加
            //   setScoreLine([...scoreLine, item]);
            // }
            setScoreLine((prev) => {
              return [...prev, item]
            })
            setScoreLineList((prev) => {
              return [...prev, item];
            })
            setScore(null);
          }}>
            确定
          </Button>
        </section>
        {/* <section style={{ marginTop: 16 }}>
          {scoreLineList?.length ? (
            <Space>
              {scoreLineList?.map((item, index) => {
                const isSelected = scoreLine?.map(i => i?.name)?.includes(item?.name);
                return (<Tag
                  key={index}
                  color={isSelected ? "green" : "default"}
                  closable
                  style={{ cursor: 'pointer' }}
                  onClick={() => {

                    if (scoreLine?.map(element => element?.name)?.includes(item?.name)) {
                      // 如果 Tag 已经选中，则移除
                      setScoreLine((prev) => {
                        if (prev.length === 1) {
                          return prev;
                        }
                        return scoreLine.filter((element) => element?.name !== item?.name)
                      });


                    } else {
                      // 如果 Tag 未选中，则添加
                      setScoreLine([...scoreLine, item]);
                    }

                  }}
                  onClose={() => {
                    setScoreLineList(scoreLineList.filter(i => i?.name !== item?.name))
                  }}
                >
                  {item?.name}
                </Tag>);
              })}
            </Space>

          ) : null}
        </section> */}
        {/* {!scoreLineList?.length ? (<Space style={{ marginTop: 16 }}>
          {rankingList.length > 0 ? (
            rankingList.map((item, index) => {
              const isSelected = selectRaking === item?.value;
              return (
                <Tag
                  onClick={() => setSelectRaking(item?.value)}
                  color={isSelected ? 'green' : 'default'}
                  key={index}
                  style={{
                    cursor: 'pointer',
                  }}
                >
                  {item?.label}
                </Tag>
              );
            })
          ) : null}
        </Space>) : null} */}
        <Table
          style={{ maxHeight: 460, marginTop: 16 }}
          dataSource={dataSource}
          scroll={{ x: 1500, y: 340 }}
          rowKey="id"
          sticky={true}
          expandable={expandableConfig}
          pagination={false}
          columns={columns}
          loading={loading}
        >
        </Table>
        <Button
          type="primary"
          style={{ marginTop: 20 }}
          disabled={!dataSource?.length > 0}
          onClick={handleDownload}
        >
          导出表格
        </Button>
      </div>
      <section style={{ marginTop: 16 }}>
        {scoreLineList?.length ? (
          <Space>
            {scoreLineList?.map((item, index) => {
              const isSelected = scoreLine?.map(i => i?.name)?.includes(item?.name);
              return (<Tag
                key={index}
                color={isSelected ? "green" : "default"}
                closable
                style={{ cursor: 'pointer' }}
                onClick={() => {

                  if (scoreLine?.map(element => element?.name)?.includes(item?.name)) {
                    // 如果 Tag 已经选中，则移除
                    setScoreLine((prev) => {
                      if (prev.length === 1) {
                        return prev;
                      }
                      return scoreLine.filter((element) => element?.name !== item?.name)
                    });


                  } else {
                    // 如果 Tag 未选中，则添加
                    setScoreLine([...scoreLine, item]);
                  }

                }}
                onClose={() => {
                  setScoreLine(scoreLine.filter((element) => element?.combIds !== item?.combIds));
                  setScoreLineList(scoreLineList.filter(i => i?.name !== item?.name))
                }}
              >
                {item?.name}
              </Tag>);
            })}
          </Space>

        ) : null}
      </section>
      {!scoreLineList?.length ? (
        <Space style={{ marginBottom: 16 }} wrap>
          {rankingList.length > 0 ? (
            rankingList.map((item, index) => {
              const isSelected = scoreLine2?.map(i => i?.id)?.includes(item?.id);
              return (
                <Tag
                  onClick={() => {


                    if (scoreLine2?.map(element => element?.id)?.includes(item?.id)) {
                      // 如果 Tag 已经选中，则移除
                      setScoreLine2((prev) => {
                        if (prev.length === 1) {
                          return prev;
                        }
                        return scoreLine2.filter((element) => element?.id !== item?.id)
                      });


                    } else {
                      // 如果 Tag 未选中，则添加
                      setScoreLine2([...scoreLine2, item]);
                    }
                  }}
                  color={isSelected ? 'green' : 'default'}
                  key={index}
                  style={{
                    cursor: 'pointer',
                  }}
                >
                  {item?.name}
                </Tag>
              );
            })
          ) : null}
        </Space>
      ) : null}
      <section style={{ marginTop: 8 }}>
        {tagList?.length ? (
          <Space wrap>
            {tagList.length > 0 ? (
              tagList.map((item, index) => {
                const isSelected = selectTag === item;
                return (
                  <Tag
                    onClick={() => setSelectTag(item)}
                    color={isSelected ? 'green' : 'default'}
                    key={index}
                    style={{
                      cursor: 'pointer',
                    }}
                  >
                    {item}
                  </Tag>
                );
              })
            ) : null}
          </Space>
        ) : null}
      </section>
      <section style={{ marginTop: 8 }}>
        <Spin spinning={loading2}>
          <Echarts
            data={echartData}
            hasTable={false}
            type={"bar"}
            text={`${subTitle}*${scoreLineList?.length > 0 ? scoreLine?.map(item => item?.name)?.join(',') : scoreLine2?.map(item => item?.name)?.join(',')}`}
            isNoneTag={true}
            isShowTag={false}
            lengButton={lengButton}
          />
        </Spin>
      </section>

      <StudentGroup
        ref={studentGroupRef}
        params={studentGroupParams}
        title={title}
      />
    </div>
  );
};

export default StatisticsPage;
