/*
 * @Author: your name
 * @Date: 2021-09-27 10:45:50
 * @LastEditTime: 2022-01-04 16:51:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/components/MccsEditableTable/index.tsx
 */

import { Pagination, Popconfirm } from 'antd';
import React, { useState, useEffect, useRef } from 'react'
import { EditableProTable } from '@ant-design/pro-table';
import { Key } from 'antd/lib/table/interface';


//仅仅对pro-table简单的包装，详细使用参考antd pro

const objectSimpleFilter = (obj: object, keyToDel: string) => {
    return JSON.parse(JSON.stringify(obj, function (key, value) {
        if (key == keyToDel) {
            return undefined;
        } else {
            return value;
        }
    }))
}

const MccsEditableTable: React.FC<MccsEditableTableType.MccsEditableTableProps> = (props) => {

    const { columns = [], request, addHandle, pagination, editHandle, delHandle, reload, edit = true, ...rest } = props;
    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
    const [dataSource, setDataSource] = useState<any>([]);
    const tableRef = useRef<any>();
    const [tableColumns, setTableColumns] = useState<any[]>([]);
    const [pageData, setPageData] = useState({ current: 1, pageSize: 10 });
    const [total, setTotal] = useState(0);



    const mccsEditableTableAction = {
        title: '操作',
        valueType: 'option',
        width: '10%',
        align: 'center',
        render: (text: string, record: any, _: any, action: any) => [
            <a
                key="editable"
                onClick={() => {
                    action?.startEditable?.(record.id);
                }}
            >
                编辑
            </a>,
            <Popconfirm
                title="是否确定删除?"
                key="del"
                onConfirm={()=>{
                    // console.log({text,record,_,action});
                    delHandle && delHandle(record);
                    setDataSource(dataSource.filter((item: any) => item.id !== record.id));
                }}
                okText="确定"
                cancelText="取消"
            >
                <a> 删除 </a>
            </Popconfirm>
        ]
    }


    const getData = async () => {
        if (request) {
            const resp = await request(pageData.current, pageData.pageSize);
            const { data, current = 1, total = 0 } = resp;

            setTotal(total);
            setDataSource(data);
        }
    }

    const onShowSizeChangeHandle = (current: number, pageSize: number) => {
        setPageData({ ...pageData, current, pageSize });

    }

    const pageChangeHandle = (page:number,pageSize:number|undefined)=>{
        //分页页码变化时
        // console.log({page,pageSize});
        setPageData({current:page,pageSize:pageSize?pageSize:10});
    }

    const generateRowKey = ()=>{
        const currentAddRowkey = (Math.random() * 1000000).toFixed(0);
        // setCurrentEditRowkey(currentAddRowkey);
        return currentAddRowkey
    }

    useEffect(() => {
        //加载模块获取数据
        getData();

    }, [reload]);



    useEffect(() => {

        const hasIndex = columns.findIndex(item => item.valueType == 'option');
        // console.log({hasIndex,edit});
        if (hasIndex == -1 && edit) {
            //当无操作按钮时，自行添加默认
            setTableColumns([...columns, mccsEditableTableAction]);
            return;
        }
        if (!edit) {
            //当非编辑下时除去操作项
            setTableColumns(columns.filter(item => item.valueType != 'option'));
            tableRef.current.cancelEditable(editableKeys[editableKeys.length-1]);

            return;
        }



        setTableColumns(columns);

    }, [columns, edit]);


    useEffect(() => {
        getData();
    }, [pageData]);




    return (
        <div>
            <EditableProTable
                {...rest}
                rowKey="id"
                columns={tableColumns}
                // request={request}
                controlled={edit}
                value={dataSource}
                actionRef={tableRef}
                onChange={setDataSource}
                recordCreatorProps={
                    edit ? {
                        record: () => {
                            return { id:generateRowKey()}
                        },
                        newRecordType: 'dataSource',
                    } : false
                }
                editable={{
                    type:'multiple',
                    editableKeys,
                    actionRender: (row, config, defaultDoms) => {
                        return [defaultDoms.save, defaultDoms.cancel];
                    },
                    onSave: async (rowKey, data, row) => {
                        const { id } = data;
                        console.log({dataSource});
                        if (typeof id == 'string') {
                            //新增
                            addHandle && addHandle(objectSimpleFilter(data, 'id'));
                        } else if(typeof id == 'number') {
    
                            editHandle && editHandle(data);
                        }
                    },
                    onChange: (editableKeys: Key[], editableRows: {id:string}|{id:string}[])=>{
                        //  console.log({editableKeys,editableRows});
                         setEditableRowKeys(editableKeys)
                    },
                    deletePopconfirmMessage: '确认删除？'
                }}
            />

            {
                pagination && (
                    <div className='pagination' style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}>
                        <Pagination
                            size='small'
                            showSizeChanger
                            onChange={(page,pageSize)=>pageChangeHandle(page,pageSize)}
                            onShowSizeChange={onShowSizeChangeHandle}
                            current={pageData.current}
                            total={total}
                        />
                    </div>
                )
            }
        </div>
    )
}

export default MccsEditableTable
