import React, {createContext, useReducer} from "react";
import {dataReducer, initDataCenter} from "./reducer";
import apiConfig from "../config/apiConfig";
import {UPDATE_DATA} from "./action";

const Root = createContext({})
const PopContext = createContext({})

function DataCenter(props) {
    const [dataCenter, dispatch] = useReducer(dataReducer, initDataCenter, () => {
        return initDataCenter
    })

    const generateUrl = (path, requestData) => {
        if (requestData) {
            const keyArr = Object.keys(requestData)
            const paramsStr = keyArr.map((v, i) => {
                if (i === 0) {
                    return '?' + v + '=' + requestData[v]
                } else {
                    return '&' + v + '=' + requestData[v]
                }
            }).join('')
            console.log('发送请求：', apiConfig.domain + path + paramsStr)
            return apiConfig.domain + path + paramsStr
        }
        return apiConfig.domain + path
    }

    const fetchData = (path, requestData, dataName) =>
        fetch(generateUrl(path, requestData), {credentials: 'include'})
            .then(res => res.json())
            .then(res => {
                console.log(res);
                if (res.success) {
                    !!dataName && dispatch(UPDATE_DATA({[dataName]: res.data}))
                } else {
                    throw res
                }
                return res
            })
            .catch(e => {
                console.error(e)
                throw e
            })


    return (
        <Root.Provider value={{dataCenter, dispatch, fetchData}}>
            {
                props.children
            }
        </Root.Provider>
    )
}

export {
    Root,
    PopContext,
}
export default DataCenter

