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

function Dolessons() {
  const params = useParams();
  const 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) => {
      if (res?.code == "0000") {
        handleClose();
        message.success("操作成功");
        if (active === "2") {
          cksyactionRef?.current?.reload();
        } else if (active === "3") {
          cjwtactionRef?.current?.reload();
        }
      }
    },
  });

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

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

  const checkCourse = (val) => {
    if (val.length) {
      doFetch({
        url: "/busTrainCatalogue/getCatalogueContent",
        params: { id: val[0] },
      }).then((res) => {
        setCourseContent(res?.data?.data);
      });
    }
  };

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

  const remove = (text, row, _) => {
    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 openActive = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: "确认开始该实验?",
          okText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            let res = await runAsync({
              url: "/studentExperiment/startExperiment",
              params: { id: row?.id },
            });
            // add Jump
            if (res.code === "0000") {
              const token = localStorage.getItem("TOKENES");
              window.open(
                `http://frp-dev.nangaoyun.com:2309/sample/?params=${token}:${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 row?.experimentName;
        },
        search: false,
      },
      {
        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: "updateUserName",
        key: "updateUserName",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "创建时间",
        dataIndex: "updateTime",
        search: false,
        key: "updateTime",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
      {
        title: "截止时间",
        dataIndex: "deadline",
        search: false,
        key: "deadline",
        formItemProps: { rules: [{ required: true, message: "此项为必填项" }] },
      },
    ];
    return col;
  }, []);

  
  const items = [
    {
      key: "1",
      label: `课程目录`,
      children: (
        <Grid container spacing={2}>
          <Grid item width={340}>
            <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2} padding={2}>
              <TreeRender
                onselected={checkCourse}
                maxWidth={170}
                url="/studentTrain/queryCatalogueTree"
                submitKey="catalogue"
                hidden={true}
                params={{
                  id: params?.id,
                }}
              />
            </Box>
          </Grid>
          <Grid item flex={1}>
            <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2} padding={2}>
              <Limit
                content={
                  courseContent?.parentId !== "0"
                    ? courseContent?.trainContent
                    : '<span style="font-weight:bloder;color:#1890ff">-- 请选择左侧小节 </span>'
                }
              ></Limit>
            </Box>
          </Grid>
        </Grid>
      ),
    },
    {
      key: "2",
      label: "查看实验",
      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) => [
                  openActive(text, row, _, action),
                ],
              },
            ]}
            path="/studentTrain/experimentPage"
            extraparams={{
              id: params?.id,
            }}
          />
        </Box>
      ),
    },
    {
      key: "3",
      label: "常见问题",
      children: (
        <Box boxShadow={"0 0 18px #f0f0f0"} borderRadius={2}>
          <AutoTable
            rerendered={false}
            actionRef={cjwtactionRef}
            columns={[...questionColumns]}
            path="/studentTrain/questionPage"
            extraparams={{
              id: params?.id,
            }}
          />
        </Box>
      ),
    },
    {
      key: "4",
      label: "在线沟通",
      children: active == "4" && <OnlineChat trainId={params?.id}></OnlineChat>,
    },
  ];

  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: "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) => {
              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) => {
              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"
          animated={true}
        />
      </Box>
    </Container>
  );
}

export default Dolessons;
