/**
 * 数据编辑相关接口
 * */

import * as React from 'react'
import Axios from '../utils/xhr'
import {DATA_EDITOR_DB, DATA_FILED_TITLE} from "../const/path"


interface dbEditorConfigState {
    loading: boolean;
    error: null;
    dbList: any[]
}

//获取数据编辑的DB
export const useDataEditorDb = () => {
    const [state, setState] = React.useState<dbEditorConfigState>({
        loading: false,
        error: null,
        dbList: []
    })
    const requestData = () => {
        setState((preState) => {
            return {
                ...preState,
                loading: true,
                error: null
            }
        })
        Axios({
            url: DATA_EDITOR_DB
        }).then(({code, msg, data}) => {
            if (code) {    //接口报错的问题
                setState((preState) => {
                    return {
                        ...preState, loading: false, error: msg
                    }
                })
                return
            }

            setState(preState => ({
                ...preState,
                loading: false,
                dbList: data.list
            }))

        }).catch((error) => {
            setState(preState => ({...preState, loading: false, error: error.message}))
        })
    }

    return [state, requestData] as const
}


interface dataFiledState {
    loading: boolean;
    error: null;
    dataTitle: any[],
    searchData: any[],
    id:number,
    searchCode:string
}

//获取数据编辑的key
export const useDataFiledTitle = () => {
    const [state, setState] = React.useState<dataFiledState>({
        loading: false,
        error: null,
        dataTitle: [],
        searchData: [],
        id:0,
        searchCode:""
    })

    const requestData = (db_code: string) => {
        setState((preState) => ({
            ...preState,
            loading: true,
            error: null
        }))
        Axios({
            url: DATA_FILED_TITLE,
            params: {
                db_code: db_code
            }
        }).then(({code, msg, data}) => {

            if (code) {
                setState(preState => ({...preState, error: msg}))
                return
            }

            setState(prevState => (
                {
                    ...prevState,
                    loading: false,
                    dataTitle: data.data_title,
                    searchData: data.search_data
                }
            ))


        }).catch((error) => {
            setState(preState => ({...preState, error: error.message}))
        })
    }

    return [state, requestData,setState] as const
}






