import * as React from 'react';

import Service from './Service';
import {useNavigate, useLocation} from "react-router";
//registerAllModules();
import { DataGrid, GridActionsCellItem, zhCN} from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import MuiAppBar from '@mui/material/AppBar';
import { styled, useTheme } from '@mui/material/styles';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import CssBaseline from '@mui/material/CssBaseline';
import AccountCircle from '@mui/icons-material/AccountCircle';
import Fab from '@mui/material/Fab';
import Tooltip from '@mui/material/Tooltip';
import DeleteIcon from '@mui/icons-material/Delete';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import Drawer from '@mui/material/Drawer';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import MenuIcon from '@mui/icons-material/Menu';
import AddIcon from '@mui/icons-material/Add';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import CircularProgress from '@mui/material/CircularProgress';
import Backdrop from '@mui/material/Backdrop';

export default function Home2() {
  const drawerWidth = 240;
  const theme = useTheme();

  const deleteItem = React.useCallback(
    (id) => () => {

      itemRef.current = id;
      /*
      console.log(id);
      Service.deleteFiles(id).then(x=> {
        Service.generateFiles2().then(x=>{
          setDetail(x.map(y=>{return {'id': y[0], 'ID': y[0], '名称': y[1], '创建时间': y[2], '操作': y[0]};}));
        });
      });*/
      setDopen(true);
    },
    [],
  );



  function RenderDate(props) {
    const { hasFocus, value } = props;
    const buttonElement = React.useRef(null);
    const rippleRef = React.useRef(null);
  
    React.useLayoutEffect(() => {
      if (hasFocus) {
        const input = buttonElement.current.querySelector('input');
        input?.focus();
      } else if (rippleRef.current) {
        // Only available in @mui/material v5.4.1 or later
        rippleRef.current.stop({});
      }
    }, [hasFocus]);
  
    return (
      <strong>
        
        <Button
          ref={buttonElement}
          touchRippleRef={rippleRef}
          variant="contained"
          size="small"
          style={{ marginLeft: 4 }}
          
          
          onClick={(event) => {
            console.log(value);
            event.stopPropagation();
            setBopen(true);
            Service.download(value)
                .then(blob => {
                // Create a temporary URL for the Blob
                const url = URL.createObjectURL(blob);
    
                // Create a link and set its href to the temporary URL
                const link = document.createElement('a');
                link.href = url;
    
                 // Set the link attributes for downloading
                link.setAttribute('download', value.concat('.xml'));
    
                 // Programmatically click the link to initiate the download
                link.click();
    
                 // Clean up the temporary URL
                URL.revokeObjectURL(url);
                setBopen(false);
             })
             .catch(error => console.error(error));
          }}
        >
          导出文件
        </Button>
      </strong>
    );
  }
  
 
  const columns = React.useMemo(
    () => [
      { field: 'ID', headerName: 'ID', width: 250 },
      { field: '名称', headerName: '名称', width: 400 },
      { field: '创建时间', headerName: '创建时间', width: 200 },
      { field: '操作', headerName: '操作', width: 100 , sortable: false, renderCell: RenderDate},
      {
        field: 'actions',
        type: 'actions',
        width: 80,
        getActions: (params) => [
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="删除"
            onClick={deleteItem(params.id)}
          />,
       
      
        ],
      },
    ],
    [deleteItem],
  );
  const Style = {
    position: "absolute",
    bottom: 128,
    right: 64,
  };
  const VisuallyHiddenInput = styled('input')({
    display: 'none',
    accept: ".13jz, .13jt, .jszf"
    });

    const hotRef = React.useRef(null);
    const itemRef = React.useRef(null);
    const navigate = useNavigate();
    let location = useLocation();
    const [detail, setDetail] = React.useState([]);
    const [open, setOpen] = React.useState(false);
    const [dopen, setDopen] = React.useState(false);
    const [bopen, setBopen] = React.useState(false);
    const [selectedFiles, setSelectedFiles] = React.useState([]);

    const handleFileChange = (event) => {
         setSelectedFiles(event.target.files);
         console.log(event.target.files);
         const fd = new FormData();
         fd.append('file', event.target.files[0]);
         Service.uploadFile(fd).then(x=>{
            console.log("uploaded");
            Service.generateFiles2().then(x=>{
              setDetail(x.map(y=>{return {'id': y[0], 'ID': y[0], '名称': y[1], '创建时间': y[2], '操作': y[0]};}));
            });

         });


    };

    React.useEffect(
      () => {
         Service.generateFiles2().then(x=>{
           setDetail(x.map(y=>{return {'id': y[0], 'ID': y[0], '名称': y[1], '创建时间': y[2], '操作': y[0]};}));
         });
      }, []
    );


    const handleRowClick = (params) => {
      //setMessage(`Movie "${params.row.title}" clicked`);
      navigate('/editor/qingdan/'.concat(params.row.id));
    };

    const AppBar = styled(MuiAppBar, {
      shouldForwardProp: (prop) => prop !== 'open',
    })(({ theme }) => ({
      transition: theme.transitions.create(['margin', 'width'], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
      }),
      variants: [
        {
          props: ({ open }) => open,
          style: {
            width: `calc(100% - ${drawerWidth}px)`,
            marginLeft: `${drawerWidth}px`,
            transition: theme.transitions.create(['margin', 'width'], {
              easing: theme.transitions.easing.easeOut,
              duration: theme.transitions.duration.enteringScreen,
            }),
          },
        },
      ],
    }));

    const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })(
      ({ theme }) => ({
        flexGrow: 1,
        padding: theme.spacing(3),
        transition: theme.transitions.create('margin', {
          easing: theme.transitions.easing.sharp,
          duration: theme.transitions.duration.leavingScreen,
        }),
        marginLeft: `-${drawerWidth}px`,
        variants: [
          {
            props: ({ open }) => open,
            style: {
              transition: theme.transitions.create('margin', {
                easing: theme.transitions.easing.easeOut,
                duration: theme.transitions.duration.enteringScreen,
              }),
              marginLeft: 0,
            },
          },
        ],
      }),
    );

    const DrawerHeader = styled('div')(({ theme }) => ({
      display: 'flex',
      alignItems: 'center',
      padding: theme.spacing(0, 1),
      // necessary for content to be below app bar
      ...theme.mixins.toolbar,
      justifyContent: 'flex-end',
    }));

    const handleDrawerClose = () => {
      setOpen(false);
    };


  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setDopen(false);
  };
  const handleCloseB = () => {
    setBopen(false);
  };

  const handleDelete = () => {
    Service.deleteFiles(itemRef.current).then(x=> {
      Service.generateFiles2().then(x=>{
        setDetail(x.map(y=>{return {'id': y[0], 'ID': y[0], '名称': y[1], '创建时间': y[2], '操作': y[0]};}));
      });
    });
    setDopen(false);
  };


    return (
      <Box sx={{ display: 'flex' }}>
       
        <CssBaseline />
        <AppBar position="fixed" open={open}>
        <Toolbar>
        
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            sx={[
              {
                mr: 2,
              },
              open && { display: 'none' },
            ]}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap component="div">
            工作台
          </Typography>
          <Box sx={{ flexGrow: 1 }} />
          <Box sx={{ display: { xs: 'none', md: 'flex' } }}>
           
            <IconButton
              size="large"
              edge="end"
              aria-label="account of current user"
              
              aria-haspopup="true"
              
              color="inherit"
            >
              <AccountCircle />
            </IconButton>
          </Box>
          </Toolbar>
        </AppBar>
        <Drawer
        sx={{
          width: drawerWidth,
          flexShrink: 0,
          '& .MuiDrawer-paper': {
            width: drawerWidth,
            boxSizing: 'border-box',
          },
        }}
        variant="persistent"
        anchor="left"
        open={open}
      >
         <DrawerHeader>
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />}
          </IconButton>
        </DrawerHeader>
        <Divider />

      </Drawer>
      <Main open={open}>
      <DrawerHeader />

      <div style={{ height: `calc(100vh - 150px)`, width: '100%' }}>
      <DataGrid onRowClick={handleRowClick}
      rows={detail} columns={columns}
      disableColumnMenu={true}
      localeText={zhCN.components.MuiDataGrid.defaultProps.localeText}
      />

        <Tooltip title="导入">
       <Fab color="primary" aria-label="add" sx={Style} component="label">
        <AddIcon />
        <VisuallyHiddenInput
             type="file"
             accept=".13jz, .13jt, .jszf"
             onChange={handleFileChange}
          />
      </Fab>
      </Tooltip>
    </div>
   
    </Main>
    <Dialog
        open={dopen}
        onClose={handleClose}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">
          {"删除该项目？"}
        </DialogTitle>
        
        <DialogActions>
          <Button onClick={handleClose}>取消</Button>
          <Button onClick={handleDelete} autoFocus>
            确定
          </Button>
        </DialogActions>
      </Dialog>
      <Backdrop
        sx={(theme) => ({ color: '#fff', zIndex: theme.zIndex.drawer + 1 })}
        open={bopen}
        
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    </Box>
    );
  }
