import DraggableDialog from "@/components/DraggableDialog";
import ImportExcel from "@/components/ImportExcel";
import InitForm from "@/components/InitForm";
import PremButton from "@/components/PremButton";
import ShopProductLoadingCard from "@/components/ProductCard/loading";
import ShopProductCard from "@/components/ProductCard/sxcard";
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 } from "antd";
import { useMemo, useState } from "react";
import "./index.less";

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

  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: "/busTrain/list", params });
      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
      refreshDeps: [params],
    }
  );

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

  const authorized = (row, ifs) => {
    doFetch({
      url: "/trainStudent/queryRelationStudent",
      params: { trainId: row?.id },
    }).then((res) => {
      if (res.code === "0000") {
        setdialogprops({
          open: true,
          maxWidth: "xl",
          defaultFormValue: { ...row },
          studentIdList: res?.data?.dataList,
          title: "授权",
          disabled: !ifs,
        });
      }
    });
  };

  const tauthorized = (row, ifs) => {
    doFetch({
      url: "/busTrainTeacher/queryRelationTeacher",
      params: { trainId: row?.id },
    }).then((res) => {
      if (res.code === "0000") {
        setdialogprops({
          open: true,
          maxWidth: "xl",
          defaultFormValue: { ...row },
          teacherIdList: res?.data?.dataList,
          title: "协作教师",
          disabled: !ifs,
        });
      }
    });
  };

  const remove = (row) => {
    runAsync({
      url: "/busTrain/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: "/busTrain/updateType",
      params: { id: row.id, ...extra },
    });
  };

  const columns = useMemo(
    () => [
      {
        title: "课程",
        dataIndex: "courseId",
        key: "courseId",
        valueType: "select",
        options: {
          path: "/sysCourse/getLoginTeacherCourseSection",
          params: {},
        },
        colProps: {
          span: 24,
        },
      },
      { title: "实训名称", dataIndex: "trainName", key: "trainName" },
      {
        title: "截止日期",
        dataIndex: "deadline",
        key: "deadline",
        valueType: "date",
      },
      {
        title: "实训封面",
        dataIndex: "pic",
        key: "pic",
        valueType: "uploadImage",
        fieldProps: {
          limit: 1,
        },
        colProps: {
          span: 24,
        },
      },
    ],
    []
  );

  return (
    <Container maxWidth={false}>
      <DraggableDialog
        handleClose={handleClose}
        loading={loading}
        dialogprops={dialogprops}
        maxWidth={dialogprops?.maxWidth ?? "xs"}
      >
        {dialogprops?.title === "编辑" || dialogprops?.title === "新增实训" ? (
          <InitForm
            fields={columns}
            defaultFormValue={dialogprops?.defaultFormValue}
            onValuesChange={async (changedValues, allValues, formRef) => {
              if (Object.keys(changedValues)[0] === "courseId") {
                let id = Object.values(changedValues)?.[0] ?? null;
                let res = await doFetch({
                  url: "/sysCourse/detail",
                  params: { id },
                });
                let pic = res?.data?.data?.pic ?? [];
                formRef?.current?.setFieldsValue({
                  pic,
                });
              }
            }}
            onFinish={(val, extra) => {
              let postdata = { ...val },
                url = "/busTrain/saveOrUpdate";
              switch (dialogprops?.title) {
                case "编辑":
                  postdata = {
                    ...val,
                    id: dialogprops?.defaultFormValue?.id,
                  };
                  break;
                default:
                  break;
              }
              runAsync({
                url,
                params: postdata,
              });
            }}
          ></InitForm>
        ) : dialogprops?.title === "协作教师" ? (
          <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: "schoolId",
                    dataIndex: "schoolName",
                    valueType: "select",
                    search: false,
                    editable: false,
                  },
                  {
                    title: "院系名称",
                    key: "departmentName",
                    dataIndex: "departmentName",
                    editable: false,
                  },
                ],
                path: "/user/getAllTeacherByCurrentTeacherSchool",
                params: {
                  type: "",
                },
              },
            ]}
            onFinish={(val) => {
              const teacherIdList = val?.teacherIdList?.map((it) => it?.id);
              runAsync({
                url: "/busTrainTeacher/relationTrainTeacher",
                params: {
                  teacherIdList,
                  trainId: dialogprops?.defaultFormValue?.id,
                },
              });
            }}
          />
        ) : (
          <InitForm
            defaultFormValue={{
              studentIdList: dialogprops?.studentIdList,
            }}
            fields={[
              {
                rowKey: "id",
                rowName: "name",
                valueType: "FormSelectList",
                dataIndex: "studentIdList",
                colProps: {
                  span: 24,
                },
                columns: [
                  {
                    title: "账号",
                    key: "userAccount",
                    dataIndex: "userAccount",
                    editable: false,
                  },
                  {
                    title: "学生姓名",
                    key: "name",
                    dataIndex: "name",
                    editable: false,
                  },
                  {
                    title: "学校名称",
                    key: "schoolId",
                    dataIndex: "schoolName",
                    valueType: "select",
                    search: false,
                    editable: false,
                  },
                  {
                    title: "院系名称",
                    key: "departmentName",
                    dataIndex: "departmentName",
                    editable: false,
                  },
                  {
                    title: "班级名称",
                    key: "className",
                    dataIndex: "className",
                    editable: false,
                  },
                ],
                path: "/user/getAllStudentByCurrentTeacherSchool",
                params: {
                  type: "3",
                },
              },
            ]}
            onFinish={(val) => {
              const studentIdList = val?.studentIdList?.map((it) => it?.id);
              runAsync({
                url: "/trainStudent/relationTrainStudent",
                params: {
                  studentIdList,
                  trainId: 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">
          <FormControlLabel
            control={
              <Checkbox
                checked={params?.typeList?.length === 5}
                indeterminate={
                  params?.typeList?.length > 0 && params?.typeList?.length < 5
                }
              />
            }
            label="全部"
            onChange={(e) => {
              setparams((s) => {
                let news = [];
                if (e.target.checked) {
                  news = ["1", "2", "3", "4", "5"];
                }
                return {
                  ...s,
                  typeList: news,
                };
              });
            }}
          />
          <FormGroup
            row
            value={params?.typeList ?? []}
            onChange={(e) => {
              let val = e.target.value;
              setparams((s) => {
                let news = [...s?.typeList];
                if (news.includes(val)) {
                  news = news.filter((it) => it !== val);
                } else {
                  news = [...news, val];
                }
                return {
                  ...s,
                  typeList: news,
                };
              });
            }}
          >
            <FormControlLabel
              control={
                <Checkbox
                  checked={params?.typeList?.includes("1")}
                  color={"warning"}
                />
              }
              label="待发布"
              value={1}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={params?.typeList?.includes("2")}
                  color={"info"}
                />
              }
              label="已发布"
              value={2}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={params?.typeList?.includes("3")}
                  color={"default"}
                />
              }
              label="已发布(暂停)"
              value={3}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={params?.typeList?.includes("4")}
                  color={"default"}
                />
              }
              label="已结束"
              value={4}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={params?.typeList?.includes("5")}
                  color={"default"}
                />
              }
              label="已关闭"
              value={5}
            />
          </FormGroup>
          <Input
            placeholder="请输入课程名称"
            style={{ width: 200 }}
            value={params?.trainName}
            onChange={(e) => {
              setparams((s) => ({
                ...s,
                trainName: e.target.value,
              }));
            }}
          ></Input>
          <ImportExcel></ImportExcel>
          <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}
                  remove={remove}
                  publish={publish}
                  authorized={authorized}
                  tauthorized={tauthorized}
                />
              </Grid>
            ))
          )}
        </Grid>
      </Box>
    </Container>
  );
}

export default Lessons;
