import { getImageBases } from '@/services/common/api';
import React, { useEffect, useState } from 'react';
const UploadContext = React.createContext();

const sleep = time =>
  new Promise((res, rej) => {
    setTimeout(() => {
      res();
    }, time);
  });

const PictureWallProvider = props => {
  const { children, ...rest } = props;
  const [imgBed, setImgBed] = useState([]);

  const update = () =>
    getImageBases('icon,androidMenu,menuNew,logo,CityTemp')
      .then(res => {
        if (res.code === 0) {
          const { data } = res;
          let arr = data.filter(item => item.moduleName !== 'menu') || [];
          data.forEach(item => {
            if (item.baseUrl && item.moduleName !== 'CityTemp') {
              if (!localStorage.getItem('pd2-baseUrl')) {
                localStorage.setItem('pd2-baseUrl', item.baseUrl);
              }
            }
          });
          setImgBed(arr);
        }
      })
      .catch(err => {
        // eslint-disable-next-line no-console
        console.error(err);
        return sleep(10000).then(update);
      });
  useEffect(() => {
    update();
  }, []);
  return <UploadContext.Provider value={{ imgBed, update }}>{children}</UploadContext.Provider>;
};

export { UploadContext as default, PictureWallProvider };
