import Flex from "@/components/Flex";
import less from "./index.less";
import { useEffect, useState } from "react";
import { Modal, Select, ConfigProvider } from "antd";
import { getSubjectList, getSchoolAreaList, getCurrentSelected, getGradeEnum, getSemesterEnum, getExamEnum, getNoSingleSubject,getSort,getExam } from "@/apis/common";
const ScreenPage = ({
  isShow = true,
  isSingle = true, //是否单选
  isTeacher = false,//是否为老师相关的
  onChange = () => { },
  saveshow = () => { },
  isShowSubject = false, //是否显示学科
  isShowSort = false,//是否显示排名 
  isShowSchool = true, //是否显示学校
  onSendSortList = () => { }, //是否发送排名
}) => {
  const [viewIsShow, setViewIsShow] = useState(isShow);
  const [grade, setGrade] = useState([]); //届别
  const [currentGrade, setCurrentGrade] = useState([]); //当前属别
  const [semester, setSemester] = useState([]); //学期
  const [currentSemester, setCurrentSemester] = useState([]); //当前学期
  const [examination, setExamination] = useState([]); //考试
  const [currentExamination, setCurrentExamination] = useState([]); //当前考试
  const [school, setSchool] = useState([]); //学校
  const [currentSchool, setCurrentSchool] = useState([]); //当前学校
  const [currentDiscipline, setCurrentDiscipline] = useState([]); //当前学科
  const [show, setShow] = useState(false);
  const [chooseList, setChooseList] = useState([]); //自选学校列表

  const [sortList, setSortList] = useState([]); //排名列表
  const [currentSort, setCurrentSort] = useState([]); //当前排名

  const [nonSingleSubject, setNonSingleSubject] = useState([]); //非单一学科

  const [singleSubjectOptions, setSingleSubjectOptions] = useState([]);
  const [optionSchoolList, setOptionSchoolList] = useState([]);
  

  // 考试id
  const [examId, setExamId] = useState('');

  useEffect(() => {
    setViewIsShow(isShow);
  }, [isShow]);

  useEffect(() => {
    if (isShowSubject) {
      singleSubjectListInit();
    }
  }, [isShowSubject]);

  // useEffect(() => {
  //   if(isShowSort){
  //     sortInit();
  //   }
  // }, [isShowSort]);

  useEffect(() => {
    optionalSchoolInit();
    getCurrentSelectedInit();
  }, []);


  // //获取排名

  // const sortInit = async () => {
  //   try {
  //       const res = await getSort();
  //       if(res?.code === 200){

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

  // };

  //获取单一学科
  const singleSubjectListInit = async () => {
    try {
      const res = await getSubjectList();
      
      if (res?.code === 200) {
        
        setSingleSubjectOptions(() => {
          return res?.data?.map((item) => {
            return {
              value: item?.id,
              label: item?.cname,
            };
          });
        });
      }
    } catch (error) {
      console.log(error, "get-subject-list-error");
    }
  };

  // 获取自选范围学校
  const optionalSchoolInit = async () => {
    try {
      const res = await getSchoolAreaList({ type: 0 });
      if (res?.code === 200) {
        setOptionSchoolList(res?.data || []);
      }
    } catch (error) {
      console.log(error, "get-option-school-list-error");
    }

  };

  // 获取当前考试
  const getCurrentSelectedInit = async () => {
    try {

      const grade = await getGradeEnum();
      const semester = await getSemesterEnum();
      const exam = await getExamEnum();
      const subject = await getNoSingleSubject();

      const res = await getCurrentSelected();
      const res2 = await getSchoolAreaList({ type: 1 });

      let sort;
      if(isShowSort){
        const res = await getSort();
        if(res?.code === 200){
          sort = res?.data || [];
          setSortList(res?.data || []);
          setCurrentSort([res?.data?.[0]]);
          onSendSortList && onSendSortList(res?.data || []);
          
        }
        
      }
      
      
      setNonSingleSubject(() => {
        let list = subject?.data?.map(item => {
          return {
            id: item.id,
            name: item.cname
          }
        });
        if(isTeacher){
          list = list?.filter(item=>item.name !== '总分');
        }
        return [...list, {
          id: "single",
          name: "单一学科",
          type: "choose",
        },]
      })


      setGrade(() => {
        return grade?.data?.map((item) => {
          return {
            name: item
          }
        })
      });
      setSemester(() => {
        return semester?.data?.map((item) => {
          return {
            name: item
          }
        })
      });

      setExamination(() => {
        return exam?.data?.map((item) => {
          return {
            name: item
          }
        })
      });

      if (res?.code === 200) {
        setCurrentGrade([{ name: res?.data?.term }]);
        setCurrentSemester([{ name: res?.data?.semester }]);
        setCurrentExamination([{ name: res?.data?.examName }]);
        setExamId(res?.data?.id);
        const element = res2?.data?.find(item => item.districtName === '全部学校');
        setCurrentSchool([element]);
        let totalPoints = subject?.data?.map(item=>{
          return {
            ...item,
            name: item.cname
          }
        })?.find(item=>item.cname === '总分');
        if(isTeacher){
          const list = subject?.data?.filter(item=>item.cname !== '总分')?.map(item=>{
            return {
              ...item,
              name: item.cname
            }
          });
          setCurrentDiscipline([list?.[0]]);
        
        }else{
          setCurrentDiscipline([totalPoints])
        }
        setSchool(() => {
          return [
            ...res2.data,
            { id: "area", districtName: "自选学校范围", type: "choose" },
          ];
        });

        const noTotal = subject?.data?.filter(item=>item.cname !== '总分')?.map(item=>{
          return {
            ...item,
            name: item.cname
          }
        })?.[0];
        if(isShowSort){
          onChange &&
          onChange({
            currentGrade: [{ name: res?.data?.term }],
            currentSemester: [{ name: res?.data?.semester }],
            currentExamination: [{ name: res?.data?.examName }],
            currentSchool: [element],
            currentDiscipline:[isTeacher ? noTotal : totalPoints],
            examId: res?.data?.id,
            currentSort:sort?.[0],
          });
          return;
        }
        onChange &&
          onChange({
            currentGrade: [{ name: res?.data?.term }],
            currentSemester: [{ name: res?.data?.semester }],
            currentExamination: [{ name: res?.data?.examName }],
            currentSchool: [element],
            currentDiscipline:[isTeacher ? noTotal : totalPoints],
            examId: res?.data?.id
          });
      }

    } catch (error) {
      console.log(error, 'get-current-selected-error');

    }
  };

  /////////////////////
  /**
   * 自选学校
   * @param record
   */
  const updateModal = (chooseList, schoolList) => {
    let datalist = schoolList || [];
    let colorList = {
      "Ⅰ类": "#722ED1",
      "Ⅱ类": "#FADB14",
    };
    let chooselist = [...chooseList];
    let modal = null;
    const showModal = () => {
      let content = (
        <Flex direction="column" className={less.schoolsList}>
          {datalist.map((item) => {
            return (
              <Flex
                key={item?.id}
                className={less.schoolsitem}
                direction="column"
              >
                <Flex className={less.address}>{item.districtName}</Flex>
                <Flex className={less.children} wrap="wrap">
                  {item?.schoolList?.map((child) => {
                    return (
                      <Flex
                        key={child?.id}
                        className={
                          chooselist?.find((it) => it?.id == child?.id)
                            ? less.childchecked
                            : less.child
                        }
                        alignItems="center"
                        onClick={() => {
                          if (
                            chooselist?.find((it) => it?.id == child?.id)
                          ) {
                            chooselist = chooselist.filter(
                              (it) => it?.id != child?.id
                            );
                            showModal();
                            return;
                          }
                          chooselist = [...chooselist, child];
                          showModal();
                        }}
                      >
                        {child?.cname}
                        <Flex
                          className={less.color}
                          style={{ backgroundColor: colorList[child?.schoolType] }}
                        >
                          {child?.schoolType}
                        </Flex>
                      </Flex>
                    );
                  })}
                </Flex>
              </Flex>
            );
          })}
        </Flex>
      );

      if (modal) {
        modal.update({ content });
      } else {
        modal = Modal.confirm({
          title: "选择学校",
          className: "globalModal",
          okText: "确定",
          cancelText: "取消",
          content,
          width: 900,
          closable: true,
          styles: { content: { height: "60vh", overflow: "auto" } },
          onOk: () => {
            setChooseList(chooselist);
          },
        });
      }
    };
    showModal();
  };
  const titlePage = (name) => {
    return (
      <Flex>
        {name}&nbsp;&nbsp;&nbsp;
        <Flex
          style={{
            color: "#c0c0c0",
            fontWeight: "bold",
          }}
        >
          |
        </Flex>
        &nbsp;&nbsp;
      </Flex>
    );
  };
  return (
    <Flex
      className={less.frame}
      direction="column"
      style={{ display: viewIsShow ? "flex" : "none" }}
    >
      <Flex className={less.chooseCard} direction="column">
        <Flex className={less.chooseItem}>
          {titlePage("届别")}
          <Flex className={less.list}>
            {grade?.map((item) => {
              return (
                <Flex
                  key={item?.name}
                  className={
                    currentGrade?.find((it) => it?.name == item?.name)
                      ? less.itemchecked
                      : less.item
                  }
                  onClick={() => {
                    if (isSingle) {
                      setCurrentGrade([item]);
                      return;
                    }
                    if (currentGrade?.find((it) => it?.name == item?.name)) {
                      setCurrentGrade(
                        currentGrade.filter((it) => it?.name != item?.name)
                      );
                      return;
                    }
                    setCurrentGrade([...currentGrade, item]);
                  }}
                >
                  {item.name}
                </Flex>
              );
            })}
          </Flex>
        </Flex>
        <Flex className={less.chooseItem}>
          {titlePage("学期")}
          <Flex className={less.list}>
            {semester?.map((item,index) => {
              return (
                <Flex
                  key={index}
                  className={
                    currentSemester?.find((it) => it?.name == item?.name)
                      ? less.itemchecked
                      : less.item
                  }
                  onClick={() => {
                    if (isSingle) {
                      setCurrentSemester([item]);
                      return;
                    }
                    if (currentSemester?.find((it) => it?.name == item?.name)) {
                      setCurrentSemester(
                        currentSemester.filter((it) => it?.name != item?.name)
                      );
                      return;
                    }
                    setCurrentSemester([...currentSemester, item]);
                  }}
                >
                  {item.name}
                </Flex>
              );
            })}
          </Flex>
        </Flex>
        <Flex className={less.chooseItem}>
          {titlePage("考试")}
          <Flex className={less.list}>
            {examination?.map((item) => {
              return (
                <Flex
                  key={item?.name}
                  className={
                    currentExamination?.find((it) => it?.name == item?.name)
                      ? less.itemchecked
                      : less.item
                  }
                  onClick={() => {
                    if (isSingle) {
                      setCurrentExamination([item]);
                      return;
                    }
                    if (
                      currentExamination?.find((it) => it?.name == item?.name)
                    ) {
                      setCurrentExamination(
                        currentExamination.filter(
                          (it) => it?.name != item?.name
                        )
                      );
                      return;
                    }
                    setCurrentExamination([...currentExamination, item]);
                  }}
                >
                  {item.name}
                </Flex>
              );
            })}
          </Flex>
        </Flex>
        {isShowSubject ? (
          <Flex className={less.chooseItem}>
            {titlePage("学科")}
            <Flex className={less.list} alignItems="center" style={{ marginTop: -6 }}>
              {nonSingleSubject?.map((item) => {
                if (item.type == "choose") {
                  return (
                    <Flex
                      key={item?.id}
                      className={show ? less.itemchecked1 : less.item1}
                      alignItems="center"
                      justify="center"
                    >
                      <ConfigProvider theme={{
                        components: {
                          Select: {
                            selectorBg: 'transparent',
                            colorTextPlaceholder: "#666",
                            fontSize: 16
                          }
                        }
                      }}>
                        <Select
                          placeholder="单一学科"
                          variant="borderless"
                          onChange={(e,option) => {
                            setShow(true);
                            setCurrentDiscipline([{name:option?.label,id:e}]);
                          }}
                          options={singleSubjectOptions || []}
                        />
                      </ConfigProvider>

                    </Flex>
                  );
                }

                return (
                  <Flex
                    key={item?.id}
                    className={
                      currentDiscipline?.[0]?.name == item?.name
                        ? less.itemchecked
                        : less.item
                    }
                    onClick={() => {
                      setShow(false);
                      setCurrentDiscipline([item]);
                    }}
                  >
                    {item.name}
                  </Flex>
                );
              })}
            </Flex>
          </Flex>
        ) : null}

            {isShowSchool ? ( <Flex className={less.chooseItem}>
          {titlePage("学校")}
          <Flex className={less.list}>
            {school?.map((item) => {
              return (
                <Flex
                  key={item?.id}
                  className={
                    currentSchool?.find((it) => it?.id == item?.id)
                      ? less.itemchecked
                      : less.item
                  }
                  onClick={() => {
                    if (item.type == "choose") {
                      updateModal(chooseList, optionSchoolList);
                      setCurrentSchool([]);
                      return;
                    }

                    if (isSingle) {
                      setCurrentSchool([item]);
                      return;
                    }
                    if (currentSchool?.find((it) => it?.name == item?.name)) {
                      setCurrentSchool(
                        currentSchool.filter((it) => it?.name != item?.name)
                      );
                      return;
                    }
                    setCurrentSchool([...currentSchool, item]);
                  }}
                >
                  {item.districtName}
                </Flex>
              );
            })}
          </Flex>
        </Flex>) : null}
        <Flex className={less.otherSchools}>
          {chooseList?.map((item) => {
            return (
              <Flex key={item?.name} className={less.otheritem}>
                {item?.cname}
              </Flex>
            );
          })}
        </Flex>
        
        {isShowSort ? (
          <Flex className={less.chooseItem}>
            {titlePage("排名")}
            <Flex className={less.list} alignItems="center">
              {sortList?.map((item) => {

                return (
                  <Flex
                    key={item?.value}
                    className={
                      currentSort?.[0]?.label == item?.label
                        ? less.itemchecked
                        : less.item
                    }
                    onClick={() => {
                      setShow(false);
                      console.log(item,'item')
                      setCurrentSort([item]);
                    }}
                  >
                    {item.label}
                  </Flex>
                );
              })}
            </Flex>
          </Flex>
        ) : null}
        <Flex className={less.btns}>
          <Flex
            className={less.btn}
            onClick={async() => {
                try {
                  const res = await getExam({
                    term: [currentGrade?.[0]?.name],
                    semester:[currentSemester?.[0]?.name],
                    examName:[currentExamination?.[0]?.name],
                  });
                  if(res?.code === 200){
                    onChange &&
                    onChange({
                      currentGrade,
                      currentSemester,
                      currentExamination,
                      currentSchool: [...currentSchool, ...chooseList],
                      currentDiscipline,
                      currentSort,
                      examId:res?.data[0]?.id,
                    });
                    setViewIsShow(false);
                    saveshow && saveshow(false);
                  }
                  
                } catch (error) {
                  console.log(error,'get-exam-error');
                  
                }
              
              
            }}
          >
            确定
          </Flex>
          <Flex
            className={less.btn}
            style={{
              color: "#c0c0c0",
              border: "1px solid #c0c0c0",
              backgroundColor: "#fff",
            }}
            onClick={() => {
              setViewIsShow(false);
              // getCurrentSelectedInit();
              setCurrentSchool([]);
              setCurrentDiscipline([]);
              saveshow && saveshow(false);
            }}
          >
            取消
          </Flex>
        </Flex>
      </Flex>
    </Flex>
  );
};

export default ScreenPage;
