import AutoTable from "@/components/AutoTable";
import DraggableDialog from "@/components/DraggableDialog";
import InitForm from "@/components/InitForm";
import PointViewer from "@/components/PointViewer";
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 { useParams } from "@umijs/max";
import { useAsyncEffect, useRequest } from "ahooks";
import {
  Divider,
  Drawer,
  message,
  Segmented,
  Table,
  Tabs,
  Tag,
  Tooltip,
} from "antd";
import { useEffect, useMemo, useRef, useState } from "react";
import { history } from "umi";
import "./index.less";

function removeFirstAndLastChar(str) {
  return str.substring(1, str.length - 1);
}

function Dolessons() {
  const params = useParams();
  const formRefc = useRef();
  const [lessonDetail, setlessonDetail] = useState(null),
    [dialogprops, setdialogprops] = useState({
      open: false,
    }),
    [type, settype] = useState("2"),
    [active, setactive] = useState();
  const [datas, setdatas] = useState({
    tabs: [],
  });

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

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

  const { runAsync, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res) => {
      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 audit = (text, row, _, action) => {
    return row.reviewType == 1 ? (
      <PremButton
        btn={{
          size: "small",
          variant: "text",
          onClick: async () => {
            let res = await doFetch({
              url: "/studentExperiment/queryResultForPc",
              params: {
                id: row.id,
              },
            });
            setdialogprops({
              open: true,
              defaultFormValue: { ...row },
              title: "批阅",
              tabdata: res?.data?.data,
            });
          },
        }}
      >
        批阅
      </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 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) => ({
      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) => [
                  audit(text, row, _, action),
                  remove(text, row, _, action),
                ],
              },
            ]}
            path="/studentExperiment/queryPageByExperiment"
            extraparams={{
              experimentId: it?.id,
              type,
            }}
          />
        </Box>
      ),
    }));
  }, [list]);

  const handleClose = () => {
    setdialogprops((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: "2",
        label: `已提交(${resdata?.notSubmitNum})`,
      },
      {
        value: "1",
        label: `待提交(${resdata?.submitNum})`,
      },
    ]);
  }, [active]);

  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 [drawer, setDrawer] = useState({
    open: false,
    onClose: () => {
      setDrawer((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  return (
    <Container maxWidth={false}>
      <DraggableDialog
        handleClose={() => {
          handleClose();
        }}
        loading={loading}
        formRef={formRefc}
        dialogprops={dialogprops}
        maxWidth={dialogprops?.maxWidth ?? "md"}
        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={async (key) => {
                let currow = datas?.tabs?.filter((it) => it?.id == key)[0];
                let res = await doFetch({
                  url: "/studentExperiment/queryResultForPc",
                  params: {
                    id: currow.id,
                  },
                });
                setdialogprops({
                  open: true,
                  defaultFormValue: { ...currow },
                  title: "批阅",
                  tabdata: res?.data?.data,
                });
              }}
            ></Tabs>
            <Divider style={{ marginTop: 0 }}></Divider>
            <ProDescriptions
              columns={detailcolumns}
              column={2}
              style={{ marginBottom: 12 }}
              dataSource={dialogprops?.defaultFormValue}
            ></ProDescriptions>
            <Divider></Divider>

            <b style={{ fontSize: 14, paddingBottom: 10, display: "block" }}>
              实验素养
            </b>
            <Table
              size="small"
              pagination={{
                pageSize: 6,
              }}
              columns={[
                {
                  title: "操作名称",
                  dataIndex: "config",
                  key: "config",
                  render: (text, row) => {
                    return row?.config?.name;
                  },
                },
                {
                  title: "是否操作",
                  dataIndex: "isComplete",
                  key: "isComplete",
                  width: 200,
                  render: (text, row) => {
                    return row?.isComplete ? (
                      "完成"
                    ) : (
                      <span style={{ color: "red" }}>未完成</span>
                    );
                  },
                },
              ]}
              dataSource={
                dialogprops?.tabdata?.recordDataDic
                  ? Object.values(dialogprops?.tabdata?.recordDataDic)
                  : []
              }
            ></Table>

            <Divider></Divider>

            <div style={{ position: "relative", minHeight: 360 }}>
              <Drawer
                {...drawer}
                width={"100vh"} //fixer
                title={false}
                closable={false}
                destroyOnClose
              >
                <Button
                  variant="contained"
                  style={{
                    position: "absolute",
                    right: 18,
                    top: 18,
                    zIndex: 9999,
                  }}
                  color="error"
                  onClick={() => {
                    setDrawer((s) => {
                      return {
                        ...s,
                        open: false,
                      };
                    });
                  }}
                >
                  ESC
                </Button>
                <PointViewer
                  position={drawer?.position}
                  CurGongjianData={dialogprops?.tabdata?.CurGongjianData}
                  CoordinatePoint={dialogprops?.tabdata?.CoordinatePoint}
                  CurGongjianPoint={dialogprops?.tabdata?.CurGongjianPoint}
                ></PointViewer>
              </Drawer>
              <b style={{ fontSize: 14, paddingBottom: 10, display: "block" }}>
                实验报告
              </b>
              <Table
                size="small"
                pagination={{
                  pageSize: 6,
                }}
                columns={[
                  {
                    title: "名称",
                    dataIndex: "Name",
                    key: "Name",
                  },
                  {
                    title: "测量值",
                    dataIndex: "actualValue",
                    key: "actualValue",
                    render: (text, row) => {
                      return row?.actualValue?.toFixed(4) ?? "";
                    },
                  },
                  {
                    title: "名义值",
                    dataIndex: "normal",
                    key: "normal",
                    render: (text, row) => {
                      return row?.normal?.toFixed(4) ?? "";
                    },
                  },
                  {
                    title: "上公差",
                    dataIndex: "Upper",
                    key: "Upper",
                  },
                  {
                    title: "下公差",
                    dataIndex: "Down",
                    key: "Down",
                  },
                ]}
                rowKey={"id"}
                dataSource={
                  dialogprops?.tabdata?.PeculiarityInfosDict
                    ? Object.values(dialogprops?.tabdata?.PeculiarityInfosDict)
                        ?.map((it, i) => {
                          return it?.map((item, index) => {
                            return {
                              ...item,
                              id: i + "," + index,
                            };
                          });
                        })
                        ?.flat()
                    : []
                }
                expandable={{
                  expandedRowRender: ({ ElementInfoList, PointList }) => {
                    return (
                      <div style={{ display: "flex", gap: 6 }}>
                        {ElementInfoList?.map((it) => {
                          return (
                            <div
                              style={{
                                padding: 12,
                                backgroundColor: "#f0f0f0",
                                display: "inline-block",
                                borderRadius: 4,
                                marginBottom: 6,
                              }}
                            >
                              <span style={{ paddingRight: 12 }}>
                                {it?.Name}
                              </span>
                              {it?.PointList?.map((its) => (
                                <Tooltip
                                  key={its?.id}
                                  title={
                                    <div
                                      dangerouslySetInnerHTML={{
                                        __html: removeFirstAndLastChar(
                                          JSON.stringify(its.Position)
                                        ).replace(/,/g, "<br/>"),
                                      }}
                                    ></div>
                                  }
                                >
                                  <Tag
                                    onClick={() => {
                                      setDrawer((s) => ({
                                        ...s,
                                        position: its.Position,
                                        open: true,
                                      }));
                                    }}
                                    style={{ cursor: "pointer" }}
                                    color="#13c2c2"
                                  >
                                    {its.Name}
                                  </Tag>
                                </Tooltip>
                              ))}
                            </div>
                          );
                        })}

                        <div
                          style={{
                            padding: 12,
                            backgroundColor: "#f0f0f0",
                            display: "inline-block",
                            borderRadius: 4,
                            marginBottom: 6,
                          }}
                        >
                          <span style={{ paddingRight: 12 }}>点集合</span>
                          {PointList?.map((its) => (
                            <Tooltip
                              key={its?.id}
                              title={
                                <div
                                  dangerouslySetInnerHTML={{
                                    __html: removeFirstAndLastChar(
                                      JSON.stringify(its.Position)
                                    ).replace(/,/g, "<br/>"),
                                  }}
                                ></div>
                              }
                            >
                              <Tag
                                onClick={() => {
                                  setDrawer((s) => ({
                                    ...s,
                                    position: its.Position,
                                    open: true,
                                  }));
                                }}
                                style={{ cursor: "pointer" }}
                                color="#13c2c2"
                              >
                                {its.Name}
                              </Tag>
                            </Tooltip>
                          ))}
                        </div>
                      </div>
                    );
                  },
                }}
              ></Table>
            </div>
          </>
        ) : dialogprops?.title === "详情" ? (
          <Stack
            direction={"column"}
            alignItems={"center"}
            justifyContent={"center"}
            gap={1}
          >
            <SplitDesc
              columns={[
                detailcolumns,
                {
                  title: "批阅信息",
                  dataIndex: "sort",
                  key: "sort",
                  valueType: "split",
                },
                [
                  {
                    title: "实验时长",
                    dataIndex: "testTime",
                    key: "testTime",
                    render: (text, record) => {
                      return record.testTime + "分";
                    },
                  },
                  {
                    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>
        ) : null}
      </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;
