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

function Dolessons() {
  const params = useParams();
  const formRef = useRef(),
    cksyactionRef = useRef(),
    cjwtactionRef = useRef();
  const [lessonDetail, setlessonDetail] = useState(null),
    [courseContent, setCourseContent] = useState({}),
    [drawer, setDrawer] = useState({
      open: false,
    }),
    [active, setactive] = useState("1");

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

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

  const checkCourse = (val) => {
    if (val.length) {
      doFetch({
        url: "/sysCourseTrain/getCourseTrain",
        params: { id: val[0] },
      }).then((res) => {
        setCourseContent(res?.data?.data);
        formRef.current.setFieldValue(
          "trainContent",
          res?.data?.data?.trainContent
        );
      });
    }
  };



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

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

  const questionColumns = useMemo(() => {
    let col = [
      {
        title: "问题内容",
        dataIndex: "question",
        key: "question",
        width: 400,
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "参考答案",
        dataIndex: "answer",
        key: "answer",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
    ];
    return col;
  }, []);

  const experimentColumns = useMemo(() => {
    let col = [
      {
        title: "实验名称",
        dataIndex: "experimentName",
        key: "experimentName",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
        render: (_, row) => {
          return (
            <Link
              underline="hover"
              href={row?.url}
              target="_blank"
              rel="noopener"
            >
              {row?.experimentName}
            </Link>
          );
        },
        search: false,
      },
      {
        title: "模型ID",
        dataIndex: "modelId",
        search: false,
        key: "modelId",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "模型名称",
        dataIndex: "modelName",
        search: false,
        key: "modelName",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "考试时间（分钟）",
        search: false,
        dataIndex: "testTime",
        key: "testTime",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "权重(%)",
        search: false,
        dataIndex: "weight",
        key: "weight",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        search: false,
        title: "创建人",
        dataIndex: "createUserName",
        key: "createUserName",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        search: false,
        key: "createTime",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
    ];
    return col;
  }, []);

  const items = [
    {
      key: "1",
      label: `课程目录`,
      children: (
        <Grid container spacing={2}>
          <Grid item xs={3}>
            <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2} padding={2}>
              <TreeRender
                onselected={checkCourse}
                maxWidth={170}
                courseId={params?.id}
                url="/sysCourseTrain/queryCatalogueTree"
                saveurl="/sysCourseTrain/saveOrUpdateCatalogue"
                deleteurl="/sysCourseTrain/deleteCatalogue"
                submitKey="catalogue"
                params={{
                  courseId: params?.id,
                }}
              />
            </Box>
          </Grid>
          <Grid item xs={9}>
            <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2} padding={2}>
              <InitForm
                formRef={formRef}
                fields={[
                  {
                    key: "trainContent",
                    dataIndex: "trainContent",
                    valueType: "Editor",
                    colProps: {
                      span: 24,
                    },
                  },
                ]}
                onFinish={(val) => {
                  const data = { ...val };
                  if (editorIsNull(data?.trainContent)) {
                    return message.warning("备课内容不能为空!", 2);
                  }
                  doFetch({
                    url: "/sysCourseTrain/saveOrUpdateCourseTrain",
                    params: {
                      id: courseContent?.id,
                      trainContent: data?.trainContent,
                    },
                  }).then((res) => {
                    if (res.code === "0000") {
                      message.success("操作成功！");
                    }
                  });
                }}
              />
            </Box>
          </Grid>
        </Grid>
      ),
    },
    {
      key: "2",
      label: (
        <Badge count={lessonDetail?.experimentNum} size="small" offset={[6, 0]}>
          查看实验
        </Badge>
      ),
      children: (
        <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
          <AutoTable
            rerendered={false}
            actionRef={cksyactionRef}
            columns={[
              ...experimentColumns,
              {
                title: "操作",
                valueType: "option",
                width: 180,
                render: (text, row, _, action) => [
                  edit(text, row, _, action),
                  remove(text, row, _, action),
                ],
              },
            ]}
            path="/courseExperiment/page"
            extraparams={{
              courseId: params?.id,
            }}
          />
        </Box>
      ),
    },
    {
      key: "3",
      label: "常见问题",
      children: (
        <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
          <AutoTable
            rerendered={false}
            actionRef={cjwtactionRef}
            columns={[
              ...questionColumns,
              {
                title: "操作",
                valueType: "option",
                width: 180,
                render: (text, row, _, action) => [
                  edit(text, row, _, action),
                  removeq(text, row, _, action),
                ],
              },
            ]}
            path="/courseQuestion/page"
            extraparams={{
              courseId: params?.id,
            }}
          />
        </Box>
      ),
    },
  ];

  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,
    }));
  };

  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: "experimentName",
                key: "experimentName",
              },
              {
                title: "仿真模型（单选）",
                dataIndex: "modelId",
                key: "modelId",
                valueType: "select",
                options: {
                  path: "/model/selection",
                },
              },
              {
                title: "考试时间（分钟）",
                dataIndex: "testTime",
                key: "testTime",
                valueType: "digit",
              },
              {
                title: "权重",
                dataIndex: "weight",
                key: "weight",
                valueType: "digit",
              },
            ]}
            onFinish={(val, extra) => {
              let postdata;
              switch (drawer?.title) {
                case "添加实验":
                  postdata = {
                    ...val,
                    courseId: params?.id,
                  };
                  break;
                case "编辑":
                  postdata = {
                    ...val,
                    id: drawer?.defaultFormValue?.id,
                    courseId: params?.id,
                  };
                default:
                  break;
              }
              runAsync({
                url: "/courseExperiment/saveOrUpdate",
                params: postdata,
              });
            }}
          ></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,
                    courseId: params?.id,
                  };
                  break;
                case "编辑":
                  postdata = {
                    ...val,
                    id: drawer?.defaultFormValue?.id,
                    courseId: params?.id,
                  };
                default:
                  break;
              }
              runAsync({
                url: "/courseQuestion/saveOrUpdate",
                params: postdata,
              });
            }}
          ></InitForm>
        )}
      </DraggableDialog>

      <Box
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        sx={{ mb: 2.5 }}
        mt={0}
      >
        <Typography variant="h5">
          {lessonDetail?.courseName ?? "暂无名称"}
        </Typography>
        <Stack spacing={2} direction="row">
          <PremButton
            btn={{
              variant: "outlined",
              onClick: (e) => {
                e.stopPropagation();
                history.back();
              },
            }}
          >
            返回
          </PremButton>
          <PremButton
            btn={{
              variant: "contained",
              onClick: addHandel,
            }}
          >
            {active === "1" ? "预览" : active === "2" ? "添加实验" : "添加问题"}
          </PremButton>
        </Stack>
      </Box>
      <Box>
        <Tabs
          activeKey={active}
          onChange={setactive}
          items={items}
          tabPosition="top"
          animated={true}
        />
      </Box>
    </Container>
  );
}

export default Dolessons;
