import { Button, Table, Select, Tag, Input, Tooltip } from "antd";
import { useState, useEffect } from "react";
import { CaretDownOutlined, CaretUpOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import ScreenPage from "@/components/ScreenPage";
import Flex from "@/components/Flex";
import { getSubjectListAll } from '@/apis/common';
import Common from "@/utils/Common";
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import "./index.less";

export const totalScore = [
  {
    label: "总分",
    value: "total",
  },
  {
    label: "语数外",
    value: "chineseThree",
  },
  {
    label: "语数外+物化",
    value: "chineseFive",
  },
  {
    label: "语数",
    value: "chineseTwo",
  },
  {
    label: "语文",
    value: "chinese",
  },
  {
    label: "数学",
    value: "math",
  },
  {
    label: "英语",
    value: "english",
  },
  {
    label: "物理",
    value: "physics",
  },
  {
    label: "化学",
    value: "chemistry",
  },
];

export const Tags = ({ titles = [], onClose }) => {
  if (!titles || !titles.length) {
    return null;
  }
  return (
    <div className="tag-container">
      {titles.map((item, index) => (
        <Tag
          style={{ marginLeft: 8 }}
          key={index}
          closable
          onClose={(e) => {
            e.preventDefault();
            if (titles.length == 1) return;
            onClose?.(index, item);
          }}
        >
          {item.name}
        </Tag>
      ))}
    </div>
  );
};

export const TableTitle = ({
  title,
  // subtitle,
  hasClass = true,
  isTags = false,
  hasAllCity = false,
  hasOnline = false,
  studentTitle = '',
  isShowSubject=true,
  isShowSchool = true,
  criticalScore = '', //临界生分数
  onChangeAllPro = () => { },
  onChange = () => { },
  onSelect = () => { },
  onLimitChange = () => { }, //全是前x名筛选
  onLineChange = () => { }, //包含前x名，上线，未上线筛选
  onChangeTitle = () => { }, //标题变化
}) => {

  const [showSearchAll, setShowSearchAll] = useState(false); //筛选框
  const [tagTitles, setTagTitles] = useState([
    { name: "2027届*高一上*入学考试" },
  ]);
  const [num, setnum] = useState({
    allCity: 50,
    online: studentTitle === '临界生' ? 5 : 610,
    noLine: studentTitle === '临界生' ? 5 : 600,
  });
  const [subtitle, setSubtitle] = useState('');

  useEffect(() => {
    if (studentTitle) {
      onLineChange && onLineChange({
        allCity: 50,
        online: studentTitle === '临界生' ? 5 : 610,
        noLine: studentTitle === '临界生' ? 5 : 600,
      });
      setnum({
        allCity: 50,
        online: studentTitle === '临界生' ? 5 : 610,
        noLine: studentTitle === '临界生' ? 5 : 600,
      })
    }
  }, [studentTitle]);

  // 添加处理删除的函数
  const handleTagClose = (index) => {
    setTagTitles((prevTags) => prevTags.filter((_, i) => i !== index));
  };

  const [subjectList, setSubjectList] = useState([]);


  useEffect(() => {
    getSubjectListInit();
    onLimitChange && onLimitChange(num?.allCity);
  }, []);


  const getSubjectListInit = async () => {
    try {
      const res = await getSubjectListAll();
      if (res.code === 200) {

        const list = res.data.map((item) => {
          return {
            value: item.id,
            label: item.cname
          }
        });
        const element = list.find(item => item.label === '总分');
        // onSelect&&onSelect(element.value);
        setSubjectList(list);
      }
    } catch (error) {
      console.log(error, 'get-subject-list-error');

    }
  };

  return (
    <>
      {/* {showSearchAll && ( */}
      <ScreenPage
        isShow={showSearchAll}
        isSingle={!isTags}
        isShowSubject={isShowSubject}
        isShowSchool={isShowSchool}
        onChange={(e) => {
          setSubtitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name, e?.currentDiscipline?.[0]?.name || ''].filter(item => !!item).join("*"));
          onChangeTitle && onChangeTitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name, e?.currentDiscipline?.[0]?.name || ''].filter(item => !!item).join("*"));

          onChange && onChange({
            examId: e?.examId,
            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
            subjectId: e?.currentDiscipline?.[0]?.id || '',
          })
          // 遍历对象的键值对
          // for (let key in e) {
          //   if (e.hasOwnProperty(key)) {
          //     // 将当前数组添加到结果数组中
          //     result.push(e[key]);
          //   }
          // }
          // console.log(result,'结果');

          // let list = Common.cartesianProduct(...result);
          // if (isTags) {
          //   setTagTitles(list);
          // } else {
          //   setSubtitle(list[0].name);
          // }
          // setShowSearchAll(!showSearchAll);
        }}
      />
      {/* )} */}
      <div className="table-title-wrapper">
        <div className="title-content">
          <span className="title">{title}: </span>
          {isTags ? (
            <Tags titles={tagTitles} onClose={handleTagClose} />
          ) : (
            <h3>{subtitle}</h3>
          )}
          {hasClass && (
            <Select
              placeholder="请选择"
              style={{ marginLeft: 12, width: 120 }}
              options={subjectList}
              defaultValue='总分'
              allowClear
              onChange={(e, option) => {
                onSelect && onSelect(e);

              }}
            />
          )}
        </div>
        <Flex>
          <Flex alignItems="center" style={{ marginRight: 12 }}>
            {hasAllCity && (
              <>
                {studentTitle === '临界生' ? (
                  <Flex alignItems="center" style={{ marginRight: 12 }}>
                    全市前&nbsp;&nbsp;
                    <Input
                      style={{
                        padding: "2px 8px",
                        border: "1px solid #c0c0c0",
                        borderRadius: 5,
                        cursor: "pointer",
                        color: "#c0c0c0",
                        width: 80,
                      }}
                      min={1}
                      placeholder="请输入"
                      value={num.allCity}
                      type="number"
                      onChange={(e) => {
                        setnum((pre) => ({ ...pre, allCity: e.target.value }));
                        // onLimitChange && onLimitChange(e.target.value);
                        // onLineChange && onLineChange({
                        //   ...num,
                        //   allCity: +e.target.value
                        // });

                      }}
                    />{" "}
                    &nbsp;&nbsp;名&nbsp;&nbsp;
                    {!hasOnline && (<Button onClick={()=>{
                        onLimitChange && onLimitChange(num.allCity);
                    }}>确定</Button>)}
                  </Flex>
                ) : null}
              </>
            )}
            {hasOnline && (
              <Flex alignItems="center">
                {studentTitle === '临界生' && (
                  <>
                    {criticalScore ? `分数为${criticalScore}分` : ''}，上限浮动&nbsp;&nbsp;
                    <Input
                      style={{
                        padding: "2px 8px",
                        border: "1px solid #c0c0c0",
                        borderRadius: 5,
                        cursor: "pointer",
                        color: "#c0c0c0",
                        width: 80,
                      }}
                      min={1}
                      placeholder="请输入"
                      value={num.online}
                      type="number"
                      onChange={(e) => {
                        setnum((pre) => ({ ...pre, online: e.target.value }));
                        // onLineChange && onLineChange({
                        //   ...num,
                        //   online: +e.target.value
                        // });
                      }}
                    />
                    &nbsp;&nbsp;分，下限浮动&nbsp;&nbsp;
                    <Input
                      style={{
                        padding: "2px 8px",
                        border: "1px solid #c0c0c0",
                        borderRadius: 5,
                        cursor: "pointer",
                        color: "#c0c0c0",
                        width: 80,
                      }}
                      min={1}
                      placeholder="请输入"
                      value={num.noLine}
                      type="number"
                      onChange={(e) => {
                        setnum((pre) => ({ ...pre, noLine: e.target.value }));
                        // onLineChange && onLineChange({
                        //   ...num,
                        //   noLine: +e.target.value
                        // });
                      }}
                    />
                    &nbsp;&nbsp;分
                    &nbsp;
                    <Button onClick={()=>{
                      onLineChange && onLineChange(num);
                    }}>确定</Button>
                  </>
                )}
                {studentTitle === '优生劣科' && (
                  <>
                    总分分数段区间设置为上限&nbsp;&nbsp;
                    <Input
                      style={{
                        padding: "2px 8px",
                        border: "1px solid #c0c0c0",
                        borderRadius: 5,
                        cursor: "pointer",
                        color: "#c0c0c0",
                        width: 80,
                      }}
                      min={1}
                      max={1000}
                      placeholder="请输入"
                      value={num?.online}
                      type="number"
                      onChange={(e) => {
                        setnum((pre) => ({ ...pre, online: e.target.value }));
                        // onLineChange && onLineChange({
                        //   ...num,
                        //   online: +e.target.value
                        // });
                      }}
                    />
                    &nbsp;&nbsp;分，
                    下限&nbsp;
                    <Input
                      style={{
                        padding: "2px 8px",
                        border: "1px solid #c0c0c0",
                        borderRadius: 5,
                        cursor: "pointer",
                        color: "#c0c0c0",
                        width: 80,
                      }}
                      min={1}
                      max={1000}
                      placeholder="请输入"
                      value={num?.noLine}
                      type="number"
                      onChange={(e) => {
                        setnum((pre) => ({ ...pre, noLine: e.target.value }));
                        // onLineChange && onLineChange({
                        //   ...num,
                        //   noLine: +e.target.value
                        // });
                      }}
                    />
                    &nbsp;&nbsp;分。
                    <Button onClick={()=>{
                      onLineChange && onLineChange(num);
                    }}>确定</Button>
                    &nbsp;
                    &nbsp;
                    <Tooltip title="在该区间的学生群体中，个别学生的学科分数低于区间内学生群体平均分的标记为劣科。">
                      <QuestionCircleOutlined />
                    </Tooltip>
                  </>
                )}
              </Flex>
            )}
          </Flex>

          <Flex
            style={{
              padding: "4px 8px",
              border: "1px solid #666",
              borderRadius: 5,
              cursor: "pointer",
            }}
            alignItems="center"
            onClick={() => {
              setShowSearchAll(!showSearchAll);
            }}
          >
            选择考试
            <img
              src={showSearchAll ? upSrc : downSrc}
              width={14}
              height={12}
              style={{ marginLeft: 5 }}
            />
          </Flex>
        </Flex>
      </div>
    </>
  );
};

// 抽取表格部分为独立组件
export const TableSection = ({
  columns,
  dataSource,
  onExport,
  onShowChart,
  hasCharts = true,
  expandableConfig = {},
  tableCommonProps = {},
}) => {
  return (
    <div style={{ height: 460, marginBottom: 30 }}>
      <Table
        {...tableCommonProps}
        columns={columns}
        dataSource={dataSource}
        expandable={expandableConfig}
        pagination={false}
      />
      <div className="table-footer">
        <Flex style={{ gap: 12 }}>
          <Button
            type="primary"
            onClick={() => {
              Common.uploadFile();
            }}
          >
            导出表格
          </Button>
          {hasCharts && (
            <Button type="primary" onClick={onShowChart}>
              显示为图表
            </Button>
          )}
        </Flex>
      </div>
    </div>
  );
};
