import { message } from 'ant-design-vue';
import { usePackagesStore } from '@/store/modules/chart/packagesStore';
import UpLoadImg from '@/assets/images/chart/photos/upload.png';
import { ImageConfig } from '../../Informations/mores/image/basis';
import { setSessionStorage, getSessionStorage } from '../../../../utils/storage';
import { FileApi } from '@/views/system/backend/file/api/FileApi';

const StoreKey = 'USER_MEDIA_PHOTOS';

let userPhotosList = getSessionStorage(StoreKey) || [];

const uploadFile = (callback = null) => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.png,.jpg,.jpeg,.gif'; // 这里只允许部分图片类型
  input.onchange = async () => {
    if (!input.files || !input.files.length) return;
    const file = input.files[0];
    const { name, size, type } = file;
    if (size > 1024 * 1024 * 5) {
      message.warning(`图片超出5M 限制，请重新上传！`);
      return false;
    }
    if (type !== 'image/png' && type !== 'image/jpeg' && type !== 'image/gif') {
      message.warning('文件格式不符合，请重新上传！');
      return false;
    }
    const reader = new FileReader();
    reader.onload = async () => {
      // 调用更新头像的接口
      const formData = new FormData();
      formData.append('file', file);
      const res = await FileApi.commonUpload('N', formData);
      callback && callback(res.data);
    };
    reader.readAsDataURL(file);
  };
  input.click();
};

const addConfig = {
  ...ImageConfig,
  category: 'private',
  categoryName: '私有的',
  package: 'photos',
  chartFrame: 'static',
  title: '点击上传图片',
  image: UpLoadImg,
  redirectComponent: `${ImageConfig.package}/${ImageConfig.category}/${ImageConfig.key}`, // 跳转组件路径规则：packageName/categoryName/componentKey
  disabled: true,
  configEvents: {
    // 点击上传事件
    addHandle: photoConfig => {
      uploadFile(e => {
        // 和上传组件一样配置，更换标题，图片，预设数据
        const packagesStore = usePackagesStore();
        const newPhoto = {
          ...ImageConfig,
          category: 'private',
          categoryName: '私有的',
          package: 'photos',
          chartFrame: 'static',
          title: e.fileOriginName,
          image: e.fileId,
          fileId: true,
          dataset: e.fileId,
          redirectComponent: `${ImageConfig.package}/${ImageConfig.category}/${ImageConfig.key}` // 跳转组件路径规则：packageName/categoryName/componentKey
        };
        userPhotosList.unshift(newPhoto);
        setSessionStorage(StoreKey, userPhotosList);
        // 插入到上传按钮前的位置
        packagesStore.addPhotos(newPhoto, 1);
      });
    }
  }
};

export default [addConfig, ...userPhotosList];
