import { Button, Stack, Typography } from "@mui/material";
import { useState } from "react";
import DraggableDialog from "../DraggableDialog";
import InitForm from "../InitForm";

function ImportExcel({ importurl, downloadurl, refresh }) {
  const [dialogprops, setdialogprops] = useState();
  const [errorList, seterrorList] = useState([]);

  return (
    <>
      <Stack direction={"row"}>
        <Button
          variant="outlined"
          onClick={() => {
            setdialogprops({
              open: true,
              title: "导入",
              footer: false,
            });
          }}
        >
          导入
        </Button>
        <DraggableDialog
          dialogprops={dialogprops}
          handleClose={() => {
            setdialogprops((s) => ({
              ...s,
              open: false,
            }));
          }}
          formdom={
            <InitForm
              style={{ marginTop: 12, marginBottom: -18 }}
              fields={[
                {
                  title: "",
                  dataIndex: "file",
                  key: "file",
                  valueType: "uploadDragger",
                  url: importurl,
                  colProps: {
                    span: 24,
                  },
                  fieldProps: {
                    showUploadList: false,
                  },
                },
              ]}
              onValuesChange={(vals) => {
                seterrorList([]);
                if (Object.values(vals)?.[0]?.length === 0) {
                  refresh?.();
                  setdialogprops((s) => ({
                    ...s,
                    open: false,
                  }));
                } else {
                  seterrorList(Object.values(vals)?.[0]);
                }
              }}
            ></InitForm>
          }
        >
          <Stack direction={"column"}>
            <Stack
              direction={"row"}
              gap={1}
              alignItems={"center"}
              justifyContent={"space-between"}
            >
              <Typography variant={"b"} color={"#999999"}>
                *请先下载模板文件
              </Typography>
              <Button
                variant="text"
                onClick={() => {
                  window.open(DOWNLOAD_URL + downloadurl);
                }}
              >
                模板文件
              </Button>
            </Stack>
            {errorList?.length > 0 && <b style={{ marginTop: 12 }}>错误信息</b>}

            {errorList?.map?.((it) => {
              return (
                <Stack
                  direction={"row"}
                  style={{ color: "#ff4800", margin: "6px 0" }}
                >
                  <span>{it?.name}</span>
                  <span style={{ flex: 1 }}>{it?.error}</span>
                </Stack>
              );
            })}
          </Stack>
        </DraggableDialog>
      </Stack>
    </>
  );
}

export default ImportExcel;
