import { useContext, useEffect, useState } from "react"

import { DataGrid, GridRowId, GridRowModel, useGridApiRef } from "@mui/x-data-grid"
import { Box, SpeedDial } from "@mui/material"
import { EditorProperties } from "@iplusplus/y-model"

import DeleteForeverOutlinedIcon from "@mui/icons-material/DeleteForeverOutlined"

import {
  GridToolbarContainer,
  GridToolbarColumnsButton,
  GridToolbarFilterButton,
  GridToolbarDensitySelector,
} from "@mui/x-data-grid"
import { EditorContext } from "../editor-context"
import { checkCanEdit } from "../convention"

function translateNumberValue(properties: EditorProperties, newRow: GridRowModel, oldRow: GridRowModel) {
  const result = { ...newRow }
  properties.forEach(p => {
    if (p.valueType.dataTypeName === "number" && typeof result[p.name] !== "number") {
      let newNumberValue = parseFloat(result[p.name])
      if (isNaN(newNumberValue)) newNumberValue = oldRow[p.name]
      result[p.name] = newNumberValue
    }
  })
  return result
}

function createProcessRowUpdate(properties: EditorProperties, onRowUpdate: (newData: Record<string, unknown>) => void) {
  return (newRow: GridRowModel, oldRow: GridRowModel) =>
    new Promise<GridRowModel>(resolve => {
      const newRowCopy = translateNumberValue(properties, newRow, oldRow)
      resolve(newRowCopy)
      onRowUpdate(newRowCopy)
    })
}

function CustomToolbar() {
  return (
    <GridToolbarContainer>
      <GridToolbarColumnsButton />
      <GridToolbarFilterButton />
      <GridToolbarDensitySelector />
    </GridToolbarContainer>
  )
}

export function ObjectArrayEditor2({
  properties,
  data,
  onValueChange,
  onDelete,
  needFilter,
}: {
  properties: EditorProperties
  needFilter?: boolean
  data: Record<string, unknown>[]
  onValueChange: (ids: GridRowId[], filedName: string, value: unknown) => void
  onDelete?: (ids: GridRowId[]) => void
}) {
  const [rows, setRows] = useState(data)

  useEffect(() => {
    //   console.log(data);
    setRows(data)
  }, [properties, data, onValueChange])

  const [lastEditField, setLastEditField] = useState("")
  const apiRef = useGridApiRef()
  const context = useContext(EditorContext)

  const processRowUpdate = createProcessRowUpdate(properties, newRow => {
    if (!lastEditField) return
    const newValue = newRow[lastEditField]
    const selectRows = apiRef.current.getSelectedRows()
    const ids: GridRowId[] = []
    // const newRows = rows.map(r => {
    //   const id = r.id as GridRowId;
    //   if (id === newRow.id || selectRows.get(id)) {
    //     ids.push(id);
    //     return { ...r, [lastEditField]: newValue }
    //   }

    //   return r
    // })

    rows.forEach(r => {
      const id = r.id as GridRowId
      if (id === newRow.id || selectRows.get(id)) {
        ids.push(id)
      }
    })

    //  setRows(newRows)

    onValueChange(ids, lastEditField, newValue)
  })

  const columns = properties.map(p => ({
    field: p.name,
    headerName: p.title,
    editable: checkCanEdit(p),
    //  type: 'string',
    sortable: false,
    renderEditCell: context.editCellRenderBuilder(p),
    renderCell: context.cellRenderBuilder(p),
    disableColumnMenu: true,
    flex: p.valueType.getAttach("flex") || 1,
  }))

  // const solt = needFilter ? {
  //     toolbar: GridToolbar,
  // } :undefined;
  const solt = needFilter
    ? {
        toolbar: CustomToolbar,
      }
    : undefined
  const disableColumnFilter = needFilter ? false : true
  return (
    <Box sx={{ height: "100%", width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        hideFooter={rows.length <= 100}
        processRowUpdate={processRowUpdate}
        apiRef={apiRef}
        checkboxSelection={true}
        onCellEditStop={p => setLastEditField(p.field)}
        disableRowSelectionOnClick
        density="compact"
        showCellVerticalBorder
        slots={solt}
        disableDensitySelector
        disableColumnFilter={disableColumnFilter}
        pageSizeOptions={[25, 50, 99, 100]}
        // slotProps={
        //     {
        //         toolbar: {
        //             printOptions: { disableToolbarButton: true },
        //             csvOptions: { disableToolbarButton: true },

        //         }
        //     }
        // }
      />

      {onDelete ? (
        <SpeedDial
          ariaLabel="删除选中项"
          sx={{ position: "absolute", bottom: 40, right: 16 }}
          icon={<DeleteForeverOutlinedIcon />}
          onClick={() => {
            //console.log(1)
            const ids = Array.from(apiRef.current.getSelectedRows().keys())
            if (ids.length > 0) {
              onDelete(Array.from(ids))
            }
          }}
        ></SpeedDial>
      ) : null}
    </Box>
  )
}
