// 生成唯一ID
const generateId = () => Math.random().toString(36).substr(2, 9);

// 初始化本地存储数据
const initLocalStorage = () => {
  if (!localStorage.getItem('directories')) {
    localStorage.setItem('directories', JSON.stringify([
      {
        id: 'root',
        name: '根目录',
        parentId: null,
        children: [
          {
            id: 'dir1',
            name: '2024投放素材',
            parentId: 'root',
            children: [
              {
                id: 'dir1-1',
                name: '春节活动',
                parentId: 'dir1',
                children: []
              }
            ]
          },
          {
            id: 'dir2',
            name: '产品图库',
            parentId: 'root',
            children: []
          }
        ]
      }
    ]));
  }

  if (!localStorage.getItem('materials')) {
    localStorage.setItem('materials', JSON.stringify([
      {
        id: generateId(),
        name: '示例图片1.jpg',
        type: 'image',
        size: 1024 * 1024 * 2, // 2MB
        url: 'https://picsum.photos/400/300',
        directoryId: 'dir1-1',
        createTime: new Date().toISOString()
      },
      {
        id: generateId(),
        name: '示例视频1.mp4',
        type: 'video',
        size: 1024 * 1024 * 10, // 10MB
        url: 'https://www.w3schools.com/html/mov_bbb.mp4',
        directoryId: 'dir2',
        createTime: new Date().toISOString()
      }
    ]));
  }
};

// Mock Service 类
export class MockService {
  constructor() {
    initLocalStorage();
  }

  // 获取目录树
  async getDirectories() {
    return new Promise((resolve) => {
      setTimeout(() => {
        const directories = JSON.parse(localStorage.getItem('directories'));
        resolve(directories);
      }, 300);
    });
  }

  // 创建目录
  async createDirectory({ name, parentId }) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const directories = JSON.parse(localStorage.getItem('directories'));
        const newDir = {
          id: generateId(),
          name,
          parentId,
          children: []
        };

        const addToParent = (dirs) => {
          for (let dir of dirs) {
            if (dir.id === parentId) {
              dir.children.push(newDir);
              return true;
            }
            if (dir.children && dir.children.length) {
              if (addToParent(dir.children)) return true;
            }
          }
          return false;
        };

        if (parentId) {
          addToParent(directories);
        } else {
          directories.push(newDir);
        }

        localStorage.setItem('directories', JSON.stringify(directories));
        resolve(newDir);
      }, 300);
    });
  }

  // 删除目录
  async deleteDirectory(id) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const directories = JSON.parse(localStorage.getItem('directories'));
        const materials = JSON.parse(localStorage.getItem('materials'));

        const removeDir = (dirs) => {
          for (let i = 0; i < dirs.length; i++) {
            if (dirs[i].id === id) {
              dirs.splice(i, 1);
              return true;
            }
            if (dirs[i].children && dirs[i].children.length) {
              if (removeDir(dirs[i].children)) return true;
            }
          }
          return false;
        };

        // 将目录下的文件移动到根目录
        const updatedMaterials = materials.map(material => {
          if (material.directoryId === id) {
            return { ...material, directoryId: 'root' };
          }
          return material;
        });

        removeDir(directories);
        localStorage.setItem('directories', JSON.stringify(directories));
        localStorage.setItem('materials', JSON.stringify(updatedMaterials));
        resolve({ success: true });
      }, 300);
    });
  }

  // 获取文件列表
  async getMaterials(directoryId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const materials = JSON.parse(localStorage.getItem('materials'));
        const filtered = materials.filter(m => m.directoryId === directoryId);
        resolve(filtered);
      }, 300);
    });
  }

  // 上传文件
  async uploadFile(file, directoryId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const materials = JSON.parse(localStorage.getItem('materials'));
          const newMaterial = {
            id: generateId(),
            name: file.name,
            type: file.type.startsWith('image/') ? 'image' : 'video',
            size: file.size,
            url: file.type.startsWith('image/') 
              ? 'https://picsum.photos/400/300?' + new Date().getTime()  // 模拟新的图片URL
              : 'https://www.w3schools.com/html/mov_bbb.mp4', // 模拟视频URL
            directoryId,
            createTime: new Date().toISOString()
          };

          materials.push(newMaterial);
          localStorage.setItem('materials', JSON.stringify(materials));
          resolve({ code: 0, message: 'success', url: newMaterial.url });
        };
        reader.readAsDataURL(file);
      }, 1000); // 模拟上传耗时
    });
  }

  // 移动文件
  async moveFile(fileId, targetDirectoryId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const materials = JSON.parse(localStorage.getItem('materials'));
        const updatedMaterials = materials.map(material => {
          if (material.id === fileId) {
            return { ...material, directoryId: targetDirectoryId };
          }
          return material;
        });
        localStorage.setItem('materials', JSON.stringify(updatedMaterials));
        resolve({ success: true });
      }, 300);
    });
  }

  // 删除文件
  async deleteFile(fileId) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const materials = JSON.parse(localStorage.getItem('materials'));
        const index = materials.findIndex(m => m.id === fileId);
        if (index > -1) {
          materials.splice(index, 1);
          localStorage.setItem('materials', JSON.stringify(materials));
        }
        resolve({ success: true });
      }, 300);
    });
  }
}