import AutoTable from "@/components/AutoTable";
import DraggableDialog from "@/components/DraggableDialog";
import InitForm from "@/components/InitForm";
import PremButton from "@/components/PremButton";
import { doFetch } from "@/utils/doFetch";
import { Box, Container, Stack, Typography } from "@mui/material";
import { useParams } from "@umijs/max";
import { useAsyncEffect, useRequest } from "ahooks";
import { message, Segmented, Tabs } from "antd";
import { useEffect, useMemo, useState } from "react";
import { history } from "umi";
import "./index.less";

function Dolessons() {
  const params = useParams();
  const [lessonDetail, setlessonDetail] = useState(null),
    [drawer, setDrawer] = useState({
      open: false,
    }),
    [type, settype] = useState("1"),
    [active, setactive] = useState();

  const { runAsync, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, parames) => {
      if (res?.code == "0000") {
        handleClose();
        message.success("操作成功");
      }
    },
  });

  useEffect(() => {
    doFetch({ url: "/busTrain/detail", params: { id: params?.id } }).then(
      (res) => {
        if (res.code === "0000") {
          setlessonDetail(res?.data?.data);
        }
      }
    );
  }, []);

  

  const list = useRequest(
    async () => {
      let res = await doFetch({
        url: "/busTrainExperiment/list",
        params: { trainId: params?.id },
      });
      setactive(res?.data?.dataList?.[0]?.id ?? null);

      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
    }
  );

  const ifs = useMemo(() => {
    let { type } = lessonDetail ?? {};
    return !(type === 1 || type === 3);
  }, [lessonDetail]);

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: "small",
          disabled: ifs,
          variant: "text",
          onClick: () => {
            setDrawer((v) => ({
              open: true,
              defaultFormValue: { ...row },
              title: "编辑",
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          disabled: ifs,
          title: "是否删除该实验?",
          okText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            await runAsync({
              url: "/busTrainExperiment/remove",
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          disabled: ifs,
          size: "small",
          color: "error",
        }}
      >
        删除
      </PremButton>
    );
  };

  const experimentColumns = useMemo(() => {
    let col = [
      { title: "学生姓名", dataIndex: "studentName", key: "studentName" },
      { title: "学生账号", dataIndex: "studentAccount", key: "studentAccount" },
      { title: "分数", dataIndex: "score", key: "score", hideInSearch: true },
      {
        title: "提交时间",
        dataIndex: "finishTime",
        key: "finishTime",
        hideInSearch: true,
      },
      {
        title: "批阅时间",
        dataIndex: "reviewTime",
        key: "reviewTime",
        hideInSearch: true,
      },
      {
        title: "批阅状态",
        dataIndex: "reviewTypeName",
        key: "reviewType",
        valueType: "select",
        options: [
          {
            label: "待批阅",
            value: "1",
          },
          {
            label: "已批阅",
            value: "2",
          },
        ],
      },
    ];
    return col;
  }, []);

  const items = useMemo(() => {
    return list?.data?.map((it, i) => ({
      key: it?.id,
      label: it?.experimentName,
      children: (
        <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
          <AutoTable
            rerendered={it?.id === active}
            columns={[
              ...experimentColumns,
              {
                title: "操作",
                valueType: "option",
                width: 180,
                render: (text, row, _, action) => [
                  edit(text, row, _, action),
                  remove(text, row, _, action),
                ],
              },
            ]}
            path="/studentExperiment/queryPageByExperiment"
            extraparams={{
              experimentId: it?.id,
              type,
            }}
          />
        </Box>
      ),
    }));
  }, [list]);

  const addHandel = (val) => {
    if (active === "1") {
      // 预览
    } else if (active === "2") {
      // 添加实验
      setDrawer({ open: true, title: "添加实验" });
    } else {
      // 添加问题
      setDrawer({ open: true, title: "添加问题" });
    }
  };

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

  const [semlist, setsemlist] = useState();
  useAsyncEffect(async () => {
    if (!active) return;
    let res = await doFetch({
      url: "/studentExperiment/queryScoreStatistics",
      params: { experimentId: active },
    });
    let resdata = res?.data?.data;
    setsemlist([
      {
        value: "1",
        label: `待提交(${resdata?.submitNum})`,
      },
      {
        value: "2",
        label: `已提交(${resdata?.notSubmitNum})`,
      },
    ]);
  }, [active]);



  return (
    <Container maxWidth={false}>
      <DraggableDialog
        handleClose={handleClose}
        dialogprops={drawer}
        loading={loading}
        maxWidth={drawer?.maxWidth ?? "sm"}
      >
        {active === "2" ? (
          <InitForm
            defaultFormValue={drawer?.defaultFormValue ?? null}
            fields={[
              {
                title: "实验",
                dataIndex: "id",
                key: "id",
                valueType: "select",
                options: {
                  path: "/busTrainExperiment/selection",
                  params: { trainId: params?.id },
                },
                formItemProps: {
                  rules: [
                    {
                      required: true,
                      message: "此项为必填项",
                    },
                  ],
                },
              },
              {
                title: "权重(%)",
                dataIndex: "weight",
                key: "weight",
                valueType: "digit",
                formItemProps: {
                  rules: [
                    {
                      required: true,
                      message: "此项为必填项",
                    },
                  ],
                },
              },
              {
                title: "考试时间(分钟)",
                dataIndex: "testTime",
                key: "testTime",
                valueType: "digit",
                formItemProps: {
                  rules: [
                    {
                      required: true,
                      message: "此项为必填项",
                    },
                  ],
                },
              },
              {
                title: "截止时间",
                dataIndex: "deadline",
                key: "deadline",
                valueType: "date",
                formItemProps: {
                  rules: [
                    {
                      required: true,
                      message: "此项为必填项",
                    },
                  ],
                },
              },
            ]}
            onFinish={(val, extra) => {
              let postdata;
              switch (drawer?.title) {
                case "添加实验":
                  postdata = {
                    ...val,
                    trainId: params?.id,
                  };
                  break;
                case "编辑":
                  postdata = {
                    ...val,
                    id: drawer?.defaultFormValue?.id,
                    trainId: params?.id,
                  };
                default:
                  break;
              }
              runAsync({
                url: "/busTrainExperiment/update",
                params: postdata,
              });
            }}
            onValuesChange={(curval, vals, formRef) => {
              if (Object.keys(curval)[0] === "id") {
                doFetch({
                  url: "/busTrainExperiment/detail",
                  params: { id: Object.values(curval)[0] },
                }).then((res) => {
                  formRef?.current?.setFieldsValue({
                    weight: res?.data?.data?.weight,
                  });
                });
              }
            }}
          ></InitForm>
        ) : (
          <InitForm
            defaultFormValue={drawer?.defaultFormValue ?? null}
            fields={[
              {
                title: "问题内容",
                dataIndex: "question",
                key: "question",
                valueType: "textarea",
              },
              {
                title: "参考答案",
                dataIndex: "answer",
                key: "answer",
                valueType: "textarea",
              },
            ]}
            onFinish={(val, extra) => {
              let postdata;
              switch (drawer?.title) {
                case "添加问题":
                  postdata = {
                    ...val,
                    trainId: params?.id,
                  };
                  break;
                case "编辑":
                  postdata = {
                    ...val,
                    id: drawer?.defaultFormValue?.id,
                    trainId: params?.id,
                  };
                default:
                  break;
              }
              runAsync({
                url: "/busTrainQuestion/saveOrUpdate",
                params: postdata,
              });
            }}
          ></InitForm>
        )}
      </DraggableDialog>

      <Box
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        sx={{ mb: 2.5 }}
        mt={0}
      >
        <Typography variant="h5">
          {lessonDetail?.trainName ?? "暂无名称"}
        </Typography>
        <Stack spacing={2} direction="row">
          <PremButton
            btn={{
              variant: "outlined",
              onClick: (e) => {
                e.stopPropagation();
                history.back();
              },
            }}
          >
            返回
          </PremButton>
        </Stack>
      </Box>
      <Box>
        <Tabs
          activeKey={active}
          onChange={setactive}
          items={items}
          tabPosition="top"
          tabBarExtraContent={
            <Segmented
              value={type}
              onChange={(val) => {
                settype(val);
              }}
              options={semlist}
            />
          }
        />
      </Box>
    </Container>
  );
}

export default Dolessons;
