import { useEffect, useRef, useState } from "react";
import { Button, Modal, Image, Select, Space, Table, Tag, Input } from "antd";
import ScreenPage from "@/components/ScreenPage";
import TeacherGroup from '@/components/TeacherGroup';
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 { getTeacherAnalysis, getTeacherZScoreAnalysis, getTeacherTrace, getTeacherGrade, getTeacherSort, getTeacherAvg,getSingleTeacherZ } from '@/apis/leader';
import { getSort, getSubjectList, getExam } from "@/apis/common";
import {downloadTableData} from '@/apis/download';
import {downloadExcelFile} from '@/utils/file';

const StatisticsPage = () => {
  const [isShow, setIsShow] = useState(false);
  const [isShow1, setIsShow1] = useState(false);
  const [isShow2, setIsShow2] = useState(false);
  const [tableIsShow, setTableIsShow] = useState(false);
  const [examinationList, setExaminationList] = useState([]); //筛选列表排列组合出的考试
  const [examinationList1, setExaminationList1] = useState([]); //筛选列表排列组合出的考试
  const [examinationList2, setExaminationList2] = useState([]); //筛选列表排列组合出的考试
  const [isDx, setisDx] = useState(true); //是否单选
  const [num, setnum] = useState(50);
  const [num1, setnum1] = useState(50);
  const [open, setOpen] = useState(2); //


  const [subtitle1, setSubtitle1] = useState('');
  const [params1, setParams1] = useState({});
  const [dataSource1, setDataSource1] = useState([]);
  const [columns1, setColumns1] = useState([]);
  const [loading1, setLoading1] = useState(false);


  const [subtitle2, setSubtitle2] = useState('');
  const [params2, setParams2] = useState({});
  const [loading2, setLoading2] = useState(false);
  const [dataSource2, setDataSource2] = useState([]);
  const [columns2, setColumns2] = useState([]);

  const [examList, setExamList] = useState([]);
  const [sortList, setSortList] = useState([]);
  const [selectSort, setSelectSort] = useState();


  const [isShow3, setIsShow3] = useState(false);
  const [subtitle3, setSubtitle3] = useState('');
  const [params3, setParams3] = useState({});
  const [loading3, setLoading3] = useState(false);
  const [dataSource3, setDataSource3] = useState([]);
  const [columns3, setColumns3] = useState([]);

  const [num3, setNum3] = useState(50);

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

  const [subjectId1, setSubjectId1] = useState('');
  const [subjectId2, setSubjectId2] = useState('');
  const [subjectId3, setSubjectId3] = useState('');

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

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

  const teacherGroupRef = useRef();

  const [teacherGroupParams, setTeacherGroupParams] = useState({});

  const [record,setRecord] = useState({});

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


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

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


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

  }, [params2?.examId, params2?.schools, num1, examList, subjectId3]);

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

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

  const init = async () => {
    setLoading1(true);
    try {
      const res = await getTeacherSort({
        ...params1,
        limit: num,
        limitStudent: selectSort,
        subjectId: subjectId1
      });
      if (res.code === 200) {
        setResponseData(res);
        setLoading1(false);
        setDataSource1(res?.data || []);
        setColumns1(() => {
          return res?.columns?.map(item => {
            if (item?.label === '教师姓名') {
              return {
                title: item?.label,
                dataIndex: item?.prop,
                align: "center",
                width: 80,
                render: (_, record) => {
                  return (<Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                    setTeacherGroupParams({
                      ...params1,
                      subjectId: subjectId1
                    });
                    setRecord(record);
                    teacherGroupRef.current?.openModal();
                    

                  }}>{record?.name}</Button>)
                }
              }
            }
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width:80,
              sorter: item.label !== '所属学校' ?(a, b) => a[item?.prop] - b[item?.prop] : false,
              
            }
          })
        })
      }
      setLoading1(false);
    } catch (error) {
      setLoading1(false);
      console.log(error, 'teacher-error');

    }

  };



  const initZ = async () => {
    setLoading2(true);
    
    try {
      const res = await getTeacherZScoreAnalysis({
        ...params2,
        limit: num1,
        examIds: examList?.map(item => item?.id).filter(item=>item !== params2?.examId),
        subjectId: subjectId3
      });
      if (res.code === 200) {
        setLoading2(false);
        setResponseData2(res);
        setDataSource2(res?.data || []);
        setColumns2(() => {
          return res?.columns?.map(item => {
            if (item?.label === '教师姓名') {
              return {
                title: item?.label,
                dataIndex: item?.prop,
                align: "center",
                width: 140,
                render: (_, record) => {
                  return (<Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                    setTeacherGroupParams({
                      ...params2,
                      subjectId: subjectId3
                    });
                    setRecord(record);
                    teacherGroupRef.current?.openModal();

                  }}>{record?.name}</Button>)
                }
              }
            }
            if (['对比考试均分', 'z值', '修正后z值'].includes(item?.label)) {
              return {
                title: item?.label,
                dataIndex: item?.prop,
                align: "center",
                sorter: (a, b) => a[item?.prop] - b[item?.prop],
              }
            }
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
            }
          })
        })

        return;
      }
      setLoading2(false);


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

    }

  };



  const getSortInit = async () => {
    try {
      const res = await getSort({start:10});
      if (res?.code === 200) {
        setSortList(res?.data || []);
        setSelectSort(res?.data?.[0]?.value);

      }

    } catch (error) {
      console.log(error, 'get-sort-init-error');

    }
  };

  const teacherAvgInit = async () => {
    try {
      setLoading3(true);
      const res = await getTeacherAvg({
        ...params3,
        limit: num3,
        subjectId: subjectId2
      });
      if (res.code === 200) {
        setResponseData1(res);
        setLoading3(false);
        setDataSource3(res?.data || []);
        setColumns3(() => {
          return res?.columns?.map(item => {
            if (item?.label === '教师姓名') {
              return {
                title: item?.label,
                dataIndex: item?.prop,
                align: "center",
                width:80,
                render: (_, record) => {
                  return (<Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                    setTeacherGroupParams({
                      ...params3,
                      subjectId: subjectId2
                    });
                    setRecord(record);
                    teacherGroupRef.current?.openModal();

                  }}>{record?.name}</Button>)
                }
              }
            }
            return {
              title: item?.label,
              dataIndex: item?.prop,
              align: "center",
              width:80,
              sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false,
            }
          })
        })

      }
      setLoading3(false);
    } catch (error) {
      setLoading3(false);
      console.log(error, 'get-teacher-avg-init-error');

    }
  };


  const singleSubjectInit = async () => {
    try {
      const res = await getSubjectList();
      if (res?.code === 200) {
        setSubjectId1(res?.data?.[0]?.id || '');
        setSubjectId2(res?.data?.[0]?.id || '');
        setSubjectId3(res?.data?.[0]?.id || '');
        setSubjectName1(res?.data?.[0]?.cname || null);
        setSubjectName2(res?.data?.[0]?.cname || null);
        setSubjectName3(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 handleSortClick = (item) => {
    setSelectSort(item?.value);


  };
  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}*${subjectName1}*教师群体排名分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };


  const handleDownload1 = async () => {
    try {
        const res = await downloadTableData(responseData1);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle3}*${subjectName2}*教师群体均分分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };

  const handleDownload2 = async () => {
    try {
        const res = await downloadTableData(responseData2);
        if(res?.status === 200){
          downloadExcelFile(res, `${subtitle2}*${subjectName3}*教师绩效Z值情况分析`);
        }
        
    } catch (error) {
      console.log(error,'download-error');
      
    }
  };


  ///////////////////////////////////////////////////////////
  return (
    <div style={{ padding: 20 }}>
      <ScreenPage
        isShow={isShow}
        isTeacher={true}
        isShowSubject={false}
        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),
            subjectId: e?.currentDiscipline?.[0]?.id || '',
          });
        }}
        saveshow={(e) => {
          setIsShow(e);
        }}
      />
      {/* 教师群体排名分析 */}
      <Flex direction="column" style={{ width: "100%" }}>
        <Flex
          style={{
            display: "flex",
            alignItems: "center",
            margin: "10px 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>
              <Select
                placeholder="请选择学科"
                options={singleSubjectList}
                value={subjectName1}
                style={{ marginLeft: 20, width: "120px" }}
                onChange={(value,options) => {
                  if(!value){
                    return;
                  }
                  setSubjectName1(options?.label);
                  setSubjectId1(value);
                }}
              />
            </Flex>
          </Flex>
          {/* <Flex
            alignItems="center"
            onClick={() => {
              //   setIsShow(!isShow);
            }}
          >
            全市前&nbsp;&nbsp;
            <Input
              style={{
                padding: "2px 8px",
                border: "1px solid #c0c0c0",
                borderRadius: 5,
                cursor: "pointer",
                color: "#c0c0c0",
                width: 80,
              }}
              min={1}
              placeholder="请输入"
              value={num}
              type="number"
              onChange={(e) => {
                setnum(+e.target.value);
              }}
            />
            &nbsp;&nbsp;名
          </Flex> */}
          <Flex
            style={{
              padding: "4px 8px",
              border: "1px solid #666",
              borderRadius: 5,
              cursor: "pointer",
              marginLeft: 10,
            }}
            alignItems="center"
            onClick={() => {
              setIsShow(!isShow);
            }}
          >
            选择考试和学校
            <img
              src={isShow ? upSrc : downSrc}
              width={14}
              height={12}
              style={{ marginLeft: 5 }}
            />
          </Flex>
        </Flex>

        <Space style={{ marginBottom: 8 }}>
          {sortList.length > 0 ? (
            sortList.map((item, index) => {
              const isSelected = item?.value === selectSort;
              return (
                <Tag
                  onClick={() => handleSortClick(item)}
                  color={isSelected ? 'green' : 'default'}
                  key={index}
                  style={{
                    cursor: 'pointer',
                  }}
                >
                  {item?.label}
                </Tag>
              );
            })
          ) : null}
        </Space>
        {/* 表格 */}
        {
          <Table
            {...tableCommonProps}
            dataSource={dataSource1}
            columns={columns1}
            loading={loading1}
            rowKey="teacherId"
          >
          </Table>
        }
        {!tableIsShow && (
          <Flex style={{ marginTop: 8 }}>
            <Button
              type="primary"
              disabled={!dataSource1.length > 0}
              onClick={handleDownload}
            >
              导出表格
            </Button>
          </Flex>
        )}
      </Flex>
      <ScreenPage
        isShow={isShow3}
        isTeacher={true}
        isShowSubject={false}
        onChange={(e) => {
          setSubtitle3([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[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 direction="column" style={{ width: "100%" }}>
        <Flex
          style={{
            display: "flex",
            alignItems: "center",
            margin: "10px 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>
              <Select
                placeholder="请选择学科"
                options={singleSubjectList}
                value={subjectName2}
                style={{ marginLeft: 20, width: "120px" }}
                onChange={(value,options) => {
                  if(!value){
                    return;
                  }
                  setSubjectName2(options?.label);
                  setSubjectId2(value);
                }}
              />
            </Flex>
          </Flex>
          <Flex
            alignItems="center"
            onClick={() => {
              //   setIsShow(!isShow);
            }}
          >
            全市前&nbsp;&nbsp;
            <Input
              style={{
                padding: "2px 8px",
                border: "1px solid #c0c0c0",
                borderRadius: 5,
                cursor: "pointer",
                color: "#c0c0c0",
                width: 80,
              }}
              min={1}
              placeholder="请输入"
              value={num3}
              type="number"
              onChange={(e) => {
                setNum3(+e.target.value);
              }}
            />
            &nbsp;&nbsp;名
          </Flex>
          <Flex
            style={{
              padding: "4px 8px",
              border: "1px solid #666",
              borderRadius: 5,
              cursor: "pointer",
              marginLeft: 10,
            }}
            alignItems="center"
            onClick={() => {
              setIsShow3(!isShow3);
            }}
          >
            选择考试和学校
            <img
              src={isShow3 ? upSrc : downSrc}
              width={14}
              height={12}
              style={{ marginLeft: 5 }}
            />
          </Flex>
        </Flex>
        {/* 表格 */}
        {
          <Table
            {...tableCommonProps}
            dataSource={dataSource3}
            columns={columns3}
            loading={loading3}
            rowKey="teacherId"
          >
          </Table>
        }
        {!tableIsShow && (
          <Flex style={{ marginTop: 8 }}>
            <Button
              type="primary"
              disabled={!dataSource3.length > 0}
              onClick={handleDownload1}
            >
              导出表格
            </Button>
          </Flex>
        )}
      </Flex>

      {/* 教师绩效Z值情况分析 */}
      <div style={{display:(isShow1 && !isShow2)? 'block':'none'}}>
      <ScreenPage
          isShow={isShow1}
          isTeacher={true}
          isSingle={true}
          isShowSubject={false}
          isShowSchool={true}
          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),
              subjectId: e?.currentDiscipline?.[0]?.id || '',
            });
          }}
          saveshow={(e) => {
            console.log(e,'isShow1');
            
            setIsShow1(e);
          }}
        />
      </div>
      <div style={{display:(isShow2 && !isShow1) ? 'block' : 'none'}}>
            <ScreenPage
          isShow={isShow2}
          isSingle={false}
          isShowSubject={false}
          isShowSchool={false}
          isTeacher={true}
          onChange={(e) => {
            const term = e?.currentGrade?.map(item => item?.name);
            const semester = e?.currentSemester?.map(item => item?.name);
            const examName = e?.currentExamination?.map(item => item?.name);
            getExam({
              term,
              semester,
              examName,
            }).then(res => {
              console.log(res.data);
              if (res.code === 200) {
                setExamList(res.data || []);
              }

            }).catch(error => {
              console.log(error, 'get-exam-error');

            })
          }}

          saveshow={(e) => {
            setIsShow2(e);
          }}
        />
        </div>
      <Flex direction="column" style={{ width: "100%", marginTop: 10 }}>
        <Flex
          style={{
            display: "flex",
            alignItems: "center",
            margin: "5px 0",
            gap: 12,
          }}
          justify="space-betweens"
          alignItems="center"
        >
          <Flex style={{ flex: 1 }} alignItems="center">
            <Flex
              style={{
                display: "flex",
                alignItems: "center",
                color: "#8a8a8a",
              }}
            >
              <h3
                style={{
                  color: "black",
                }}
                onClick={() => { }}
              >
                教师绩效Z值情况分析
              </h3>
              <Select
                placeholder="请选择学科"
                options={singleSubjectList}
                value={subjectName3}
                style={{ marginLeft: 20, width: "120px" }}
                onChange={(value,options) => {
                  if(!value){
                    return;
                  }
                  setSubjectName3(options?.label);
                  setSubjectId3(value);
                }}
              />
            </Flex>
          </Flex>
          <Flex
            alignItems="center"
            onClick={() => {
              // setIsShow(!isShow);
            }}
          >
            全市前&nbsp;&nbsp;
            <Input
              style={{
                padding: "2px 8px",
                border: "1px solid #c0c0c0",
                borderRadius: 5,
                cursor: "pointer",
                color: "#c0c0c0",
                width: 80,
              }}
              min={1}
              placeholder="请输入"
              value={num1}
              type="number"
              onChange={(e) => {
                setnum1(+e.target.value);
              }}
            />
            &nbsp;&nbsp;名
          </Flex>
        </Flex>
        <Flex
          style={{
            display: "flex",
            alignItems: "center",
            margin: "5px 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",
              marginLeft: 10,
            }}
            alignItems="center"
            onClick={() => {
              setIsShow1(!isShow1);
              setIsShow2(false);
            }}
          >
            选择考试和学校
            <img
              src={isShow1 ? upSrc : downSrc}
              width={14}
              height={12}
              style={{ marginLeft: 5 }}
            />
          </Flex>
        </Flex>
        <Flex
          style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
            margin: "5px 0",
            // gap: 12,
          }}
          justify="space-between"
          alignItems="center"
        >
          <Flex style={{ flex: 1 }} alignItems="center">
            <Flex
              alignItems="center"
              style={{
                width: "100%",
                display: "flex",
                alignItems: "center",
                color: "#8a8a8a",
              }}
            >
              对比考试 : &nbsp;
              <Flex style={{ width: "92%" }} wrap="wrap">
                {examList?.filter((item)=>item?.id !== params2?.examId)?.map((item) => {
                  return (
                    <h3
                      style={{ color: "#000", marginRight: 8 }}
                      key={item?.id}
                      closable
                      onClose={(e) => {
                        e.preventDefault();
                        setExamList((prev) => {
                          return prev.filter((i) => i?.id !== item?.id)
                        })
                      }}
                    >
                      {`${item?.term}*${item?.semester}*${item?.examName};`}
                    </h3>
                  );
                })}
              </Flex>
            </Flex>
          </Flex>

          <Flex
            style={{
              padding: "4px 8px",
              border: "1px solid #666",
              borderRadius: 5,
              cursor: "pointer",
              marginLeft: 10,
            }}
            alignItems="center"
            onClick={() => {
              setIsShow2(!isShow2);
              setIsShow1(false);
            }}
          >
            选择考试
            <img
              src={isShow2 ? upSrc : downSrc}
              width={14}
              height={12}
              style={{ marginLeft: 5 }}
            />
          </Flex>
        </Flex>
        {/* 表格 */}
        {
          <Table
            {...tableCommonProps}
            dataSource={dataSource2}
            columns={columns2}
            loading={loading2}
            rowKey="teacherId"
            // pagination={{
            //   position: ["none", "none"],
            // }}
          >
          </Table>
        }
        {!tableIsShow && (
          <Flex style={{ marginTop: 8 }}>
            <Button
              type="primary"
              disabled={!dataSource3.length > 0}
              onClick={handleDownload2}
            >
              导出表格
            </Button>
          </Flex>
        )}
      </Flex>



      <TeacherGroup ref={teacherGroupRef} params={teacherGroupParams} record={record}/>
    </div>
  );
};

export default StatisticsPage;
