import { EditorProperty } from "@iplusplus/y-model";
import { CellRender, CellRenderBuilder2, CellRenderParam } from "../types";
import { useGridApiContext } from "@mui/x-data-grid";
import { useState } from "react";
import { ObjectArrayEditorDialog } from "../../object-array-editor";

function ObjectArrayEditorDialogCell({ cellParams, properties,newRowProvider }:{
    cellParams: CellRenderParam
    properties:EditorProperty[],
    newRowProvider ?: (currentRows:Record<string, any>[])=>Promise<Record<string, any>[]>,

}){
    const {id,  value, field } = cellParams;
    const apiRef = useGridApiContext();
  //  const ref = React.useRef<HTMLElement>();
    const [open, setOpen] = useState(true);

    const onClose=(data ?:Record<string,any>[])=>{
        setOpen(false);
        apiRef.current.stopCellEditMode({
            id, field
        })

        if(data){
            apiRef.current.setEditCellValue({ id, field, value: data });
        }

    }
    console.log("render ObjectArrayEditorDialog")
    return open ? <ObjectArrayEditorDialog  properties={properties} data={value!} onClose={onClose} newRowProvider={newRowProvider} />:null;
}


function createObjectArrayEditRender(property:EditorProperty[]){
    return (params:CellRenderParam)=>{
        return <ObjectArrayEditorDialogCell cellParams={params} properties={property} />
    }
}

const renderObjectArrayCell: CellRender = () => {
    // console.log(params.value)
    return <div>双击查看</div> ;
  };

export const objectArrayRenderBuilder: CellRenderBuilder2 = (property: EditorProperty) => {
  const vt = property.valueType;
  if (vt.dataTypeName === "objectArray") {


    return {
      editorCellRender: createObjectArrayEditRender(vt.subProperty as EditorProperty[]),
      cellRender: renderObjectArrayCell,
    }
  }

  return undefined
}
