import AutoTable from "@/components/AutoTable";
import DraggableDialog from "@/components/DraggableDialog";
import InitForm from "@/components/InitForm";
import OnlineChat from "@/components/OnlineChat";
import PremButton from "@/components/PremButton";
import TreeRender from "@/components/TreeRender/sxtree";
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 { Badge, message, Tabs } 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: "/busTrain/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);
        formRef.current.setFieldValue(
          "trainContent",
          res?.data?.data?.trainContent
        );
      });
    }
  };

  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 removeq = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          disabled: ifs,
          title: "是否删除该实验?",
          okText: "确认",
          cancelText: "取消",
          onConfirm: async () => {
            await runAsync({
              url: "/busTrainQuestion/delete",
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          size: "small",
          color: "error",
          disabled: ifs,
        }}
      >
        删除
      </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: "考试时间（分钟）",
        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: "此项为必填项" }] },
      },
      {
        title: "实验完成率",
        dataIndex: "finishPer",
        search: false,
        key: "finishPer",
        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="/busTrainCatalogue/queryCatalogueTree"
                saveurl="/busTrainCatalogue/saveOrUpdateCatalogue"
                deleteurl="/busTrainCatalogue/deleteCatalogue"
                submitKey="catalogue"
                disabled={ifs}
                params={{
                  trainId: params?.id,
                }}
              />
            </Box>
          </Grid>
          <Grid item flex={1}>
            <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: "/busTrainCatalogue/saveCatalogueContent",
                    params: {
                      id: courseContent?.id,
                      trainContent: data?.trainContent,
                    },
                  }).then((res) => {
                    if (res.code === "0000") {
                      message.success("操作成功！");
                    }
                  });
                }}
                disabled={ifs}
              />
            </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) => [
                  edit(text, row, _, action),
                  remove(text, row, _, action),
                ],
              },
            ]}
            path="/busTrainExperiment/page"
            extraparams={{
              trainId: 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="/busTrainQuestion/page"
            extraparams={{
              trainId: params?.id,
            }}
          />
        </Box>
      ),
    },
    {
      key: "4",
      label: "在线沟通",
      children: <OnlineChat trainId={params?.id}></OnlineChat>,
    },
  ];

  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: "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>
          <PremButton
            btn={{
              disabled: ifs,
              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;
