import path from 'path'
import { fileURLToPath } from 'url'
import vue from '@vitejs/plugin-vue2'
import serveStatic from 'serve-static'
import fs from 'fs-extra'

export default {
  plugins: [vue(), customPlugin()],
  resolve: {
    alias: {
      '@': '/src/',
    },
  },
  server: {
    port: 8000,
    proxy: {
      '/prefab-behavior': {
        // 代理到旧资源库
        target: 'https://test-studio.3dlink.cn/asset/',
        changeOrigin: true,
      },
    },
  },
}

function getPackageList() {
  const packagesPath = path.resolve(__dirname, './packages')
  let packageList = fs
    .readdirSync(packagesPath)
    .filter((item) => {
      const jsonPath = path.resolve(packagesPath, item, 'bundle.json')
      return fs.existsSync(jsonPath)
    })
    .map((item) => {
      const jsonPath = path.resolve(packagesPath, item, 'bundle.json')
      const prefabPath = path.resolve(packagesPath, item, 'prefab.json')
      delete require.cache[require.resolve(jsonPath)]
      const json = require(jsonPath)
      const prefabUrl = require(prefabPath)
      return {
        name: json.name,
        pkgJson: json,
        dirName: item,
        modelId: prefabUrl.root?.resources?.models?.[0]?.url,
      }
    })
  return packageList
}

function customPlugin() {
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
  const watchDirs = ['packages', 'index.html'].map((item) =>
    path.resolve(__dirname, item).replace(/\\/g, '/')
  )

  return {
    name: 'start-api-serve',
    // 监听 packages 目录的变化
    handleHotUpdate({ file, server }) {
      const shouldReload = watchDirs.some((dir) => file.startsWith(dir))
      if (shouldReload) {
        server.ws.send({
          type: 'full-reload',
          path: '*',
        })
      }
    },
    configureServer(server) {
      const app = server.middlewares

      app.use(serveStatic('dist'))

      app.use('/local-api/prefab-list', (req, res) => {
        let items = getPackageList()
        items = items.map((item) => {
          let previewPath = fs.readdirSync()
          if (item.modelId) {
            previewPath = `http://img.model.3dmomoda.com/models/${item.modelId}/0/screenshot.jpg`
          } else {
            // 查找 preview
            try {
              const files = fs.readFileSync(
                path.resolve(packagesPath, item.dirName)
              )
              previewPath = files.map(
                (file) =>
                  path.basename(file).startsWith('preview') &&
                  /(jpg|jpeg|png|svg|gif)/.test(path.extname(file))
              )
            } catch (e) {
              console.warn(e)
            }
          }
          return {
            ...item,
            aliasName: item.pkgJson.aliasName,
            usePath: `/${item.dirName}`,
            previewPath: previewPath,
          }
        })
        res.end(JSON.stringify({ data: { items } }))
      })

      app.use('/local-api/upload', async (req, res) => {
        const uploadDir = path.resolve(__dirname, './public/_cache')
        fs.ensureDirSync(uploadDir)
        const form = formidable({
          uploadDir,
          maxFileSize: 5 * 1024 * 1024,
          multiples: true,
          keepExtensions: false, // 这里设置为 true 会导致 sonar 报错
        })

        const ret = await new Promise((resolve, reject) => {
          // 解决上面 keepExtensions false 后缀丢失的问题
          form.on('fileBegin', (formName, file) => {
            const ext = path.extname(file.originalFilename)
            if (ext) {
              file.newFilename += ext
              file.filepath += ext
            }
          })
          form.parse(req, (err, fields, files) => {
            if (err) {
              reject(err)
              return
            }
            resolve({ fields, files })
          })
        })
        const { newFilename } = ret.files.file

        res.end(
          httpSuccess({
            url: `/_cache/${newFilename}`,
          })
        )
      })
    },
  }
}

function httpSuccess(data, message = '操作成功', code = 200) {
  return JSON.stringify({
    code,
    message,
    data,
  })
}
