import DraggableDialog from "@/components/DraggableDialog";
import InitForm from "@/components/InitForm";
import PremButton from "@/components/PremButton";
import ShopProductCard from "@/components/ProductCard";
import ShopProductLoadingCard from "@/components/ProductCard/loading";
import { doFetch } from "@/utils/doFetch";
import PRODUCTS from "@/_mock/products";
import { Box, Container, Grid, Stack, Typography } from "@mui/material";
import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormGroup from "@mui/material/FormGroup";
import { useRequest } from "ahooks";
import { Empty, Input, message,Tabs } from "antd";
import { useMemo, useState } from "react";
import "./index.less";



function Lessons() {
  const [dialogprops, setdialogprops] = useState({
    open: false,
  });
  const [params, setparams] = useState({
    courseName: "",
    status: null,
    typeList: ["1", "2", "3"],
  });

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

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

  const datalist = useRequest(
    async () => {
      let res = await doFetch({ url: "/sysCourse/list", params });
      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
      refreshDeps: [params],
    }
  );

  const edit = (row) => {
    setdialogprops({
      open: true,
      defaultFormValue: { ...row },
      title: "编辑",
    });
  };

  const copy = (row) => {
    setdialogprops({
      open: true,
      defaultFormValue: { ...row },
      title: "复制创建",
    });
  };

  const authorized = (row) => {
    doFetch({
      url: "/sysCourseTeacher/queryRelationTeacher",
      params: { courseId: row?.id },
    }).then((res) => {
      if (res.code === "0000") {
        setdialogprops({
          open: true,
          maxWidth: "xl",
          defaultFormValue: { ...row },
          teacherIdList: res?.data?.dataList,
          title: "授权",
        });
      }
    });
  };

  const remove = (row) => {
    runAsync({
      url: "/sysCourse/delete",
      params: { id: row.id },
    });
  };

  const publish = (row, params) => {
    const type = row?.type === 1 ? 2 : row?.type === 2 ? 1 : null;
    const extra = params ?? { type };
    runAsync({
      url: "/sysCourse/pubOrNotPub",
      params: { id: row.id, ...extra },
    });
  };

  const columns = useMemo(
    () => [
      {
        title: "课程封面",
        dataIndex: "pic",
        key: "pic",
        valueType: "uploadImage",
        fieldProps: {
          limit: 1,
        },
      },
      {
        title: "课程名称",
        dataIndex: "courseName",
        key: "courseName",
        formItemProps: {
          rules: [{ required: true, message: "此项为必填项" }],
        },
        colProps: {
          span: 24,
        },
      },
      {
        title: "课程时间",
        dataIndex: "courseTime",
        key: "courseTimeList",
        valueType: "dateRange",
        colProps: {
          span: 24,
        },
      },
    ],
    []
  );

  return (
    <Container maxWidth={false}>
      <DraggableDialog
        handleClose={handleClose}
        loading={loading}
        dialogprops={dialogprops}
        maxWidth={dialogprops?.maxWidth ?? "xs"}
      >
        {dialogprops?.title === "编辑" ||
        dialogprops?.title === "新增课程" ||
        dialogprops?.title === "复制创建" ? (
          <InitForm
            fields={columns}
            defaultFormValue={dialogprops?.defaultFormValue}
            onFinish={(val, extra) => {
              let postdata = { ...val },
                url = "/sysCourse/saveOrUpdate";
              switch (dialogprops?.title) {
                case "编辑":
                  postdata = {
                    ...val,
                    id: dialogprops?.defaultFormValue?.id,
                  };
                  break;
                case "复制创建":
                  url = "/sysCourse/copy";
                  postdata = {
                    ...val,
                    id: dialogprops?.defaultFormValue?.id,
                  };
                  break;
                default:
                  break;
              }
              runAsync({
                url,
                params: postdata,
              });
            }}
          ></InitForm>
        ) : (
          <InitForm
            defaultFormValue={{
              teacherIdList: dialogprops?.teacherIdList,
            }}
            fields={[
              {
                rowKey: "id",
                rowName: "name",
                valueType: "FormSelectList",
                dataIndex: "teacherIdList",
                colProps: {
                  span: 24,
                },
                columns: [
                  {
                    title: "账号",
                    key: "userAccount",
                    dataIndex: "userAccount",
                    editable: false,
                  },
                  {
                    title: "教师姓名",
                    key: "name",
                    dataIndex: "name",
                    editable: false,
                  },
                  {
                    title: "学校名称",
                    key: "schoolName",
                    dataIndex: "schoolName",
                    editable: false,
                  },
                  {
                    title: "院系名称",
                    key: "departmentName",
                    dataIndex: "departmentName",
                    editable: false,
                  },
                ],
                path: "/user/page",
                params: {
                  type: "2",
                },
              },
            ]}
            onFinish={(val) => {
              const teacherIdList = val?.teacherIdList?.map((it) => it?.id);
              runAsync({
                url: "/sysCourseTeacher/relationCourseTeacher",
                params: {
                  teacherIdList,
                  courseId: dialogprops?.defaultFormValue?.id,
                },
              });
            }}
          />
        )}
      </DraggableDialog>
      <Box
        display={"flex"}
        justifyContent={"space-between"}
        alignItems={"center"}
        sx={{ mb: 2.5 }}
        mt={0}
      >
        <Typography variant="h5">课程管理</Typography>
        <Stack spacing={2} direction="row" flex={1} justifyContent={"flex-end"}>

        <Tabs
            items={[
              {
                key: null,
                label: `全部`,
              },
              {
                key: "1",
                label: `待发布`,
              },
              {
                key: "2",
                label: `已发布`,
              },
              {
                key: "3",
                label: `已结束`,
              },
            ]}
            activeKey={params?.type}
            onChange={(val) => {
              setparams((s) => ({
                ...s,
                type: val,
              }));
            }}
          ></Tabs>

          <Input
            placeholder="请输入课程名称"
            style={{ width: 200, marginLeft: 24  }}
            value={params?.courseName}
            onChange={(e) => {
              setparams((s) => ({
                ...s,
                courseName: e.target.value,
              }));
            }}
          ></Input>

          <PremButton
            btn={{
              variant: "contained",
              onClick: (e) => {
                e.stopPropagation();
                setdialogprops({
                  open: true,
                  defaultFormValue: {},
                  title: "新增课程",
                });
              },
            }}
          >
            新增课程
          </PremButton>
        </Stack>
      </Box>

      <Box mt={2.5}>
        <Grid container spacing={3}>
          {datalist?.loading && !datalist?.data ? (
            PRODUCTS?.map((product, i) => {
              return (
                <Grid
                  key={product.id}
                  item
                  xs={12}
                  sm={6}
                  md={4}
                  lg={3}
                  xl={2.4}
                >
                  <ShopProductLoadingCard product={product} />
                </Grid>
              );
            })
          ) : datalist?.data?.length === 0 ? (
            <Grid xs={12} mt={12}>
              <Empty></Empty>
            </Grid>
          ) : (
            datalist?.data?.map?.((product) => (
              <Grid key={product.id} item xs={12} sm={6} md={4} lg={3} xl={2.4}>
                <ShopProductCard
                  product={product}
                  loading={datalist?.loading}
                  edit={edit}
                  copy={copy}
                  remove={remove}
                  publish={publish}
                  authorized={authorized}
                />
              </Grid>
            ))
          )}
        </Grid>
      </Box>
    </Container>
  );
}

export default Lessons;
