import ora from 'ora'
import path from 'path'
import chalk from 'chalk'
import { DOC_ROOT_PATH } from '../../constant/doc'
import { npm } from '../../utils/npm'
import {
  STORYBOOK_DIST_PATH,
  PROJECT_DOC_DIST_PATH,
  STORYBOOK_CONFIG_PATH,
} from '../../constant/doc'
import { mergeConfig } from '../../utils/doc-methods'
import rimraf from 'rimraf'
import puppeteer from 'puppeteer'
const fsEx = require('fs-extra')

// 封面截图
async function screenshot() {
  const browser = await puppeteer.launch({
    // headless: false,
    defaultViewport: {
      width: 1024,
      height: 4000,
    },
  })
  const page = await browser.newPage()

  const configPath = path.join(STORYBOOK_CONFIG_PATH, 'main.js')
  const config = require(configPath)

  const pageUrl = `file://${PROJECT_DOC_DIST_PATH}/index.html?path=${config.coverPath}`
  await page.goto(pageUrl, { waitUntil: 'load' })

  return new Promise((resolve) => {
    setTimeout(async () => {
      try {
        // 关掉右侧控件
        const closeBtn = await page.waitForSelector(
          "button[title='Hide addons [A]']"
        ) as any
        closeBtn.click()

        await new Promise((resolve) => setTimeout(resolve, 1000)) // 等待界面重新渲染

        const iframe = await page.waitForSelector('#storybook-preview-iframe', {
          timeout: 2 * 1000,
        }) as any
        const iframeEle = await iframe.contentFrame() // 解析iframe
        const dom = await iframeEle.waitForSelector('#root', {
          timeout: 2 * 1000,
        })

        // 截图
        await dom.screenshot({
          path: path.resolve(PROJECT_DOC_DIST_PATH, './ark-cover-shot.png'),
        })
        await browser.close()
        resolve(true)
      } catch (e) {
        console.log(e)
        await browser.close()
        console.log(chalk.yellow('截取封面超时'))
        resolve(true)
      }
    }, 2000) // 等待页面重定向
  })
}

async function buildDoc() {
  // 打包编译文档
  const spinner = ora('正在编译打包文档，时间较长，请耐心等待...').start()
  spinner.text = ''
  console.log('')

  // 合并storybook配置
  mergeConfig()

  // 执行打包命令
  const { status } = await npm(['run', 'build-storybook'], {
    cwd: DOC_ROOT_PATH,
  }) as any
  if (status !== 0) {
    spinner.fail(
      chalk.red(
        '文档编译失败!编译前请先本地预览下文档，确保本地能够正常预览文档的情况下，再重新执行打包命令'
      )
    )
    return
  }

  // 清理之前的打包产物，然后重新把包复制到项目根路径
  if (fsEx.pathExistsSync(PROJECT_DOC_DIST_PATH)) {
    rimraf.sync(PROJECT_DOC_DIST_PATH)
  }
  fsEx.copySync(STORYBOOK_DIST_PATH, PROJECT_DOC_DIST_PATH)

  const configPath = path.join(STORYBOOK_CONFIG_PATH, 'main.js')
  const config = require(configPath)
  if (config.coverPath) {
    // 进行页面截图
    if (await screenshot()) {
      spinner.succeed(chalk.green('编译完成!'))
    } else {
      spinner.fail('编译失败')
    }
  } else {
    spinner.succeed(chalk.green('编译完成!'))
  }
}

export default buildDoc
