import { message } from "antd"
import { useCallback, useEffect, useState } from "react"
import { useModel } from "umi"

function useIndexDB() {
    const [myDB, setMyDB] = useState<IDBDatabase>()
    const [data, setData] = useState<any>([])
    const [total, setTotal] = useState<any>(0)
    const { dispatch } = useModel('useOperating.useDB')
    /*新建或者打开数据库*/
    const createDB = useCallback(() => {
        let db: IDBDatabase | null = null
        let request = window.indexedDB.open('temporaryNews', 1) //打开数据库或新建数据库
        request.onupgradeneeded = function (event: any) {//数据库不存在和更新都会触发这个事件
            console.log('更新')
            db = event?.target?.result
            let objectStore: IDBObjectStore | undefined;
            if (!db?.objectStoreNames.contains('news')) {//假如news表不存在
                objectStore = db?.createObjectStore('temporaryNews', { autoIncrement: true });//创建news表，自动生成主键
                objectStore?.createIndex('knewsLink', 'knewsLink', { unique: false });//新建索引
                objectStore?.createIndex('title', 'title', { unique: false });
                objectStore?.createIndex('knewsThumbUrl', 'knewsThumbUrl', { unique: false });
                objectStore?.createIndex('description', 'description', { unique: false });
            }
        }
        request.onerror = function () {
            console.log('打开数据库失败')
        }
        request.onsuccess = function () {
            setMyDB(request.result)
            console.log('数据库打开成功')
        }
    }, [])
    /*新增数据*/
    const add = useCallback((params: { data: { newsUrl: string, newsTitle: string, newsPicUrl: string, newsDescription: string }[] }) => {
        let request: IDBRequest<IDBValidKey> | undefined = myDB?.transaction(['temporaryNews'], 'readwrite')//新建一个事务
            .objectStore('temporaryNews')//拿到 IDBObjectStore 对象
            .add(params);
        if (request) {
            request.onsuccess = function (event) {
                readAll({})
                console.log('数据写入成功', event.target, request);
                message.success('添加成功！')
            };
            request.onerror = function (event) {
                console.log('数据写入失败');
            }
        }
    }, [myDB, total])
    /*编辑更新数据*/
    const updata = useCallback(() => {
        let request: IDBRequest<IDBValidKey> | undefined = myDB?.transaction(['temporaryNews'], 'readwrite')//新建一个事务
            .objectStore('temporaryNews')//拿到 IDBObjectStore 对象
            .put(1);
        if (request) {
            request.onsuccess = function (event) {
                console.log('数据更新成功', event);
            };
            request.onerror = function (event) {
                console.log('数据更新失败');
            }
        }
    }, [myDB])
    /*删除数据*/
    const del = useCallback((params: number) => {
        let request: IDBRequest<undefined> | undefined = myDB?.transaction(['temporaryNews'], 'readwrite')
            .objectStore('temporaryNews')
            .delete(params);
        if (request) {
            request.onsuccess = function (event) {
                console.log('数据删除成功');
                message.success('删除成功！')
                readAll({})
            };
        }
    }, [myDB])
    /*查询数据*/
    const query = useCallback((params?: any) => {
        if (params) {
            readAll(params)
        } else {
            readAll({});
        }
    }, [myDB])
    /**遍历数据 */
    const readAll = useCallback((params: { str?: string, start?: number, end?: number }) => {
        let { str, start = 1, end = 10 } = params
        let objectStore = myDB?.transaction('temporaryNews').objectStore('temporaryNews');
        let arr: any[] = []
        if (objectStore) {
            //倒序读取IDBKeyRange.upperBound(10000000000, true), "prev"
            objectStore.openCursor(IDBKeyRange.upperBound(10000000000, true), "prev").onsuccess = function (event: any) {
                let cursor = event.target.result;
                if (str) {
                    if (cursor) {
                        let isOk = cursor?.value?.data?.some((item: any) => {
                            return Object.keys(item).some(key => { return item[key].indexOf(str) !== -1 })
                        })
                        if (isOk) {
                            arr.push({ ...cursor?.value, id: cursor?.key })
                        }
                        cursor.continue();
                    } else {
                        console.log('没有更多数据了！');
                        let newArr: any[] = []
                        arr.forEach((item: any, index: number) => {
                            if (index >= (start - 1) * end && index < start * end) {
                                newArr.push(item)
                            }
                        })
                        setData(newArr)
                        setTotal(arr.length)
                    }
                } else {
                    if (cursor) {
                        arr.push({ ...cursor?.value, id: cursor?.key })
                        cursor.continue();
                    } else {
                        console.log('没有更多数据了！');
                        let newArr: any[] = []
                        arr.forEach((item: any, index: number) => {
                            if (index >= (start - 1) * end && index < start * end) {
                                newArr.push(item)
                            }
                        })
                        setData(newArr)
                        setTotal(arr.length)
                    }
                }
            };
        }
    }, [myDB, data])
    /**分页 */
    const page = useCallback((params?: string) => {
        let objectStore = myDB?.transaction('temporaryNews').objectStore('temporaryNews');
        let arr: any[] = []
        if (objectStore) {
            objectStore.openCursor().onsuccess = function (event: any) {
                let cursor = event.target.result;
                console.log(cursor)
                if (params) {
                    if (cursor) {
                        let isOk = cursor?.value?.data?.some((item: any) => {
                            return Object.keys(item).some(key => { return item[key].indexOf(params) !== -1 })
                        })
                        if (isOk) {
                            arr.push({ ...cursor?.value, id: cursor?.key })
                        }
                        cursor.continue();
                    } else {
                        console.log('没有更多数据了！');
                        setData(arr)
                        setTotal(arr.length)
                    }
                } else {
                    if (cursor) {
                        arr.push({ ...cursor?.value, id: cursor?.key })
                        cursor.continue();
                    } else {
                        console.log('没有更多数据了！');
                        setData(arr)
                    }
                }
            };
        }
    }, [myDB, data])
    useEffect(() => {
        if (!myDB) {
            createDB()
        }
    }, [myDB])
    useEffect(() => {
        dispatch({ type: 'set', params: { data: data.length > 0 ? data : [], total } })
    }, [data, total])
    return { add, del, updata, query, readAll }
}

export default useIndexDB