import AutoTable from "@/components/AutoTable";
import DraggableDialog from "@/components/DraggableDialog";
import InitForm from "@/components/InitForm";
import PremButton from "@/components/PremButton";
import SplitDesc from "@/components/SplitDesc";
import { doFetch } from "@/utils/doFetch";
import { ProDescriptions } from "@ant-design/pro-components";
import { Box, Container, Stack, Typography } from "@mui/material";
import { useRequest } from "ahooks";
import { Divider, message, Tabs } from "antd";
import { useMemo, useRef, useState } from "react";
import "./index.less";

function Checkhomework() {
  const actionRef = useRef(),
    formRef = useRef(),
    actionRefs = useRef(),
    formRefs = useRef(),
    formRefc = useRef();
  const [dialogprops, setdialogprops] = useState({
    open: false,
  });
  const [active, setactive] = useState("2");
  const [params, setparams] = useState();

  const handleClose = () => {
    setdialogprops((s) => ({
      ...s,
      open: false,
    }));
  };

  const { runAsync, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, parames) => {
      if (parames?.url === "/studentExperiment/giveScore") return;
      if (res?.code == "0000") {
        message.success("操作成功");
        if (active === "1") {
          actionRef?.current?.reload();
        } else {
          actionRefs?.current?.reload();
        }
      }
    },
  });

  const audit = (text, row, _, action) => {
    return row.reviewType == 1 ? (
      <PremButton
        btn={{
          size: "small",
          variant: "text",
          onClick: () => {
            setdialogprops({
              open: true,
              defaultFormValue: { ...row },
              title: "批阅",
            });
          },
        }}
      >
        批阅
      </PremButton>
    ) : (
      <PremButton
        btn={{
          size: "small",
          variant: "text",
          color: "inherit",
          onClick: () => {
            setdialogprops({
              open: true,
              defaultFormValue: { ...row },
              title: "详情",
              maxWidth: "md",
              footer: false,
            });
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const remove = (text, row, _) => {
    return (
      <PremButton
        pop={{
          disabled: row?.reviewType !== 1,
          title: "是否退回该实训?",
          okText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            await runAsync({
              url: "/studentExperiment/remake",
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          disabled: row?.reviewType !== 1,
          size: "small",
          color: "error",
        }}
      >
        退回
      </PremButton>
    );
  };

  const columns = useMemo(
    () => [
      { title: "学生姓名", dataIndex: "studentName", key: "studentName" },
      { title: "学生账号", dataIndex: "studentAccount", key: "studentAccount" },
      { title: "课程名称", dataIndex: "courseName", key: "courseName" },
      { title: "实训名称", dataIndex: "trainName", key: "trainName" },
      { title: "实验名称", dataIndex: "experimentName", key: "experimentName" },
      { title: "分数", dataIndex: "score", key: "score", hideInSearch: true },
      { title: "权重", dataIndex: "weight", key: "weight", hideInSearch: true },
      {
        title: "分数(权重)",
        dataIndex: "scoreWeight",
        key: "scoreWeight",
        hideInSearch: true,
      },
      {
        title: "提交时间",
        dataIndex: "finishTime",
        key: "finishTimeRange",
        valueType: "dateTimeRange",
      },
      {
        title: "批阅时间",
        dataIndex: "reviewTime",
        key: "reviewTimeRange",
        valueType: "dateTimeRange",
      },
      {
        title: "批阅状态",
        dataIndex: "reviewTypeName",
        key: "reviewType",
        valueType: "select",
        mode: "radio",
        options: [
          { label: "待批阅", value: "1" },
          { label: "已批阅", value: "2" },
        ],
      },
    ],
    []
  );

  const detailcolumns = [
    { title: "学生姓名", dataIndex: "studentName", key: "studentName" },
    { title: "学生账号", dataIndex: "studentAccount", key: "studentAccount" },
    { title: "课程名称", dataIndex: "courseName", key: "courseName" },
    { title: "实训名称", dataIndex: "trainName", key: "trainName" },
    { title: "实验名称", dataIndex: "experimentName", key: "experimentName" },
    { title: "分数", dataIndex: "score", key: "score", hideInSearch: true },
    { title: "权重", dataIndex: "weight", key: "weight", hideInSearch: true },
    { title: "分数", dataIndex: "scoreWeight", key: "scoreWeight" },
    {
      title: "提交时间",
      dataIndex: "finishTime",
      key: "finishTimeRange",
    },
    {
      title: "批阅时间",
      dataIndex: "reviewTime",
      key: "reviewTimeRange",
    },
  ];

  const columes = useMemo(() => {
    return [
      { title: "学生姓名", dataIndex: "studentName", key: "studentName" },
      { title: "学生账号", dataIndex: "studentAccount", key: "studentAccount" },
      { title: "课程名称", dataIndex: "courseName", key: "courseName" },
      { title: "实训名称", dataIndex: "trainName", key: "trainName" },
      { title: "实验名称", dataIndex: "experimentName", key: "experimentName" },
      { title: "分数", dataIndex: "score", key: "score", hideInSearch: true },
      { title: "权重", dataIndex: "weight", key: "weight", hideInSearch: true },
      {
        title: "分数(权重)",
        dataIndex: "scoreWeight",
        key: "scoreWeight",
        hideInSearch: true,
      },
      {
        title: "提交时间",
        dataIndex: "finishTime",
        key: "finishTimeRange",
        valueType: "dateTimeRange",
      },
      {
        title: "批阅时间",
        dataIndex: "reviewTime",
        key: "reviewTimeRange",
        valueType: "dateTimeRange",
      },
      {
        title: "批阅状态",
        dataIndex: "reviewTypeName",
        key: "reviewType",
        valueType: "select",
        mode: "radio",
        options: [
          { label: "待批阅", value: "1" },
          { label: "已批阅", value: "2" },
        ],
      },
    ];
  }, []);

  const [datas, setdatas] = useState({
    tabs: [],
  });

  let blid = useRequest(
    async () => {
      let res = await doFetch({
        url: "/studentExperiment/queryAllByLoginTeacher",
        params: {},
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [],
      onSuccess: (data, params) => {
        setdatas((s) => ({
          ...s,
          tabs: data?.map((it) => ({
            ...it,
            label: it?.studentName,
            key: it?.id,
          })),
        }));
        if (dialogprops?.open) {
          setdialogprops({
            open: true,
            defaultFormValue: { ...data[0] },
            title: "批阅",
          });
        }

        formRefc?.current?.resetFields();
      },
    }
  );

  //全部数量
  let totaldata = useRequest(async () => {
    let res = await doFetch({
      url: "/studentExperiment/queryCountByLoginTeacher",
      params: {},
    });
    return res?.data?.data;
  });

  const items = useMemo(() => {
    return [
      {
        key: "2",
        label: `已提交 ${params?.already ?? totaldata?.data?.submitNum ?? 0}`,
        children: (
          <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
            <AutoTable
              actionRef={actionRefs}
              formRef={formRefs}
              scroll={{ x: 1366 }}
              columns={[
                ...columes,
                {
                  title: "操作",
                  valueType: "option",
                  width: 136,
                  render: (text, row, _, action) => [
                    audit(text, row, _, action),
                    remove(text, row, _, action),
                  ],
                },
              ]}
              path="/studentExperiment/queryPageByLoginTeacher"
              rerendered={false}
              extraparams={{ type: "2" }}
              setparams={(val) => {
                setparams((s) => ({
                  ...s,
                  already: val,
                }));
              }}
            ></AutoTable>
          </Box>
        ),
      },
      {
        key: "1",
        label: `待提交 ${
          params?.unalready ?? totaldata?.data?.notSubmitNum ?? 0
        }`,
        children: (
          <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
            <AutoTable
              actionRef={actionRef}
              formRef={formRef}
              scroll={{ x: 1366 }}
              columns={[...columns]}
              extraparams={{ type: "1" }}
              path="/studentExperiment/queryPageByLoginTeacher"
              rerendered={false}
              setparams={(val) => {
                setparams((s) => ({
                  ...s,
                  unalready: val,
                }));
              }}
            ></AutoTable>
          </Box>
        ),
      },
    ];
  }, [totaldata]);

  return (
    <Container maxWidth={false}>
      <DraggableDialog
        handleClose={() => {
          handleClose();
          actionRef?.current?.reload();
        }}
        loading={loading}
        formRef={formRefc}
        dialogprops={dialogprops}
        maxWidth={dialogprops?.maxWidth ?? "sm"}
        formdom={
          dialogprops?.title === "批阅" && (
            <InitForm
              fields={[
                {
                  title: "批阅信息",
                  dataIndex: "sort",
                  key: "sort",
                  valueType: "split",
                },
                {
                  title: "打分",
                  dataIndex: "score",
                  key: "score",
                  colProps: { span: 24 },
                  valueType: "digit",
                },
                {
                  title: "评语",
                  dataIndex: "comment",
                  key: "comment",
                  valueType: "textarea",
                  colProps: {
                    span: 24,
                  },
                },
              ]}
              defaultFormValue={{ examineResult: "1" }}
              onFinish={async (val, extra) => {
                let postdata = {
                  ...val,
                  id: dialogprops?.defaultFormValue?.id,
                };
                await runAsync({
                  url: "/studentExperiment/giveScore",
                  params: postdata,
                });
                await blid?.runAsync();
              }}
            ></InitForm>
          )
        }
      >
        {dialogprops?.title === "批阅" ? (
          <>
            <Tabs
              items={datas?.tabs}
              activeKey={dialogprops?.defaultFormValue?.id}
              onChange={(key) => {
                let currow = datas?.tabs?.filter((it) => it?.id == key)[0];
                setdialogprops({
                  open: true,
                  defaultFormValue: { ...currow },
                  title: "批阅",
                });
              }}
            ></Tabs>
            <Divider style={{ marginTop: 0 }}></Divider>
            <ProDescriptions
              columns={detailcolumns}
              column={2}
              style={{ marginBottom: 12 }}
              dataSource={dialogprops?.defaultFormValue}
            ></ProDescriptions>
          </>
        ) : dialogprops?.title === "详情" ? (
          <Stack
            direction={"column"}
            alignItems={"center"}
            justifyContent={"center"}
            gap={1}
          >
            <SplitDesc
              columns={[
                detailcolumns,
                {
                  title: "批阅信息",
                  dataIndex: "sort",
                  key: "sort",
                  valueType: "split",
                },
                [
                  {
                    title: "实验时长",
                    dataIndex: "useTime",
                    key: "useTime",
                  },
                  {
                    title: "批阅状态",
                    dataIndex: "reviewTypeName",
                    key: "reviewTypeName",
                  },
                  {
                    title: "批阅时间",
                    dataIndex: "reviewTime",
                    key: "reviewTime",
                  },
                  {
                    title: "批阅人",
                    dataIndex: "reviewUserName",
                    key: "reviewUserName",
                  },
                  {
                    title: "分数",
                    dataIndex: "score",
                    key: "score",
                    span: 2,
                  },
                  {
                    title: "评语",
                    dataIndex: "comment",
                    key: "comment",
                    span: 3,
                  },
                ],
              ]}
              dataSource={dialogprops?.defaultFormValue}
            ></SplitDesc>
          </Stack>
        ) : (
          <InitForm
            fields={columns}
            defaultFormValue={dialogprops?.defaultFormValue}
            onFinish={(val, extra) => {
              let postdata = { ...val, type: "3" };
              switch (dialogprops?.title) {
                case "编辑":
                  postdata = {
                    ...val,
                    id: dialogprops?.defaultFormValue?.id,
                  };
                  break;
                default:
                  break;
              }
              runAsync({
                url: "/user/saveOrUpdate",
                params: postdata,
              });
            }}
          ></InitForm>
        )}
      </DraggableDialog>

      <Box
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        sx={{ mb: 1 }}
        mt={0}
      >
        <Typography variant="h5">作业批阅</Typography>
        <Stack spacing={2} direction="row">
          <PremButton
            btn={{
              variant: "contained",
              onClick: async (e) => {
                e.stopPropagation();
                if (active === "1") {
                  let formval = formRef?.current.getFieldsValue();
                  const params = {
                    ...formval,
                    type: active,
                  };
                  await doFetch({
                    url: "/studentExperiment/exportByLoginTeacher",
                    params,
                  });
                } else {
                  let formval = formRefs?.current.getFieldsValue();
                  const params = {
                    ...formval,
                    type: active,
                  };
                  await doFetch({
                    url: "/studentExperiment/exportByLoginTeacher",
                    params,
                  });
                }
              },
            }}
          >
            导出
          </PremButton>
        </Stack>
      </Box>

      <Tabs
        activeKey={active}
        onChange={(value) => {
          setactive(value);
        }}
        items={items}
        tabPosition="top"
        animated={true}
      />
    </Container>
  );
}

export default Checkhomework;
