import inquirer from 'inquirer'
import ora from 'ora'
import chalk from 'chalk'
import serialize from 'serialize-javascript'
import { isNpmMaintainer } from '../../utils/npm'
import { sleep, spawnPromise } from '../../utils/other'
import { beautifyJs } from '../../utils/beautify-file'
import { PROJECT_DOC_DIST_PATH } from '../../constant/doc'
import {
  NPM,
  MATERIAL_TYPE,
  PROJECT_PACKAGE_JSON_PATH,
} from '../../constant/cli'
import { npm } from '../../utils/npm'
const array = require('lodash/array')
const fsEx = require('fs-extra')

// 检查上传权限
async function checkPermission(npmName: string) {
  const res: any = await spawnPromise(NPM, ['whoami']) // 不用spawnPromise这个方法的话拿不到npm返回值
  if (res.code === 1) {
    console.log(chalk.red(`请先登录npm账号`))
    return
  }

  const maintainerName = res.output.replace('\n', '')
  const isMaintainer = await isNpmMaintainer(npmName, maintainerName)
  if (!isMaintainer) {
    console.log(
      chalk.red(
        `您的账号暂无上传权限。请确认您是否是 ${npmName} 这个npm包的维护者`
      )
    )
    return false
  }

  return true
}

// // 上传文档到oss
// async function uploadOss(npmName) {
//   const distPath = STORYBOOK_DIST_PATH // 文档打包后的产物路径
//   const ossDir = encodeURIComponent(npmName) // 包名需要转义后作为oss存储目录
//   const status = await multipleFilesUpload(ossDir, distPath)

//   if (!status) {
//     return false
//   }

//   console.log('')
//   console.log(
//     chalk.green(`文档访问地址：`),
//     `https://imooc.ifreeovo.xyz/${encodeURIComponent(ossDir)}/index.html`
//   ) // 这里转义是因为阿里云会对oss的存储目录再进行转义，然后生成链接
//   return true
// }

// 重写package.json的files，keywords
async function overwritePackageJson(fileContent: any) {
  const { files, keywords } = fileContent
  if (!files) {
    fileContent.files = []
  }

  if (!keywords) {
    fileContent.keywords = []
  }

  const { type } = await inquirer.prompt({
    type: 'list',
    name: 'type',
    message: '请选择发布的物料类型',
    choices: MATERIAL_TYPE,
  })

  fileContent.files = array.union(fileContent.files, ['.arkdoc-dist']) // 利用lodash数组去重
  fileContent.keywords = array.union(fileContent.keywords, [
    `name=arkdoc&type=${type}`,
  ])

  const content = beautifyJs(
    serialize(fileContent, {
      unsafe: true,
    })
  )
  fsEx.writeFileSync(PROJECT_PACKAGE_JSON_PATH, content)
}

async function publishDoc() {
  const { isPublish } = await inquirer.prompt({
    type: 'confirm',
    name: 'isPublish',
    message: '请确认是否发布文档',
  })

  if (isPublish) {
    if (!fsEx.pathExistsSync(PROJECT_DOC_DIST_PATH)) {
      console.log(chalk.red('未找到打包文件，请先执行npm bulish --doc进行打包'))
      return
    }

    const spinner = ora('正在检查账号是否有发布权限，请稍等...').start()
    spinner.text = ''
    console.log('')

    // 使用npm命令判断用户是否登录
    // 验证登录用户是否是npm包的所有者，是的话才有上传权限
    if (!fsEx.pathExistsSync(PROJECT_PACKAGE_JSON_PATH)) {
      spinner.fail(
        chalk.red('当前路径下未找到package.json。请确认命令执行路径是否正确!')
      )
      return
    }
    const file = require(PROJECT_PACKAGE_JSON_PATH)
    const { name, version } = file
    const isValid = await checkPermission(name)
    if (!isValid) {
      spinner.stop()
      return
    }

    // 上传文档到oss
    spinner.text = '权限检查通过。'
    await sleep() // 防止spinner.text覆盖掉上一次的spinner.text显示
    console.log('')

    // 重写package.json的files，keywords
    spinner.stop()
    await overwritePackageJson(file)
    spinner.start('正在上传文档资源，请稍等...')
    await sleep()
    console.log('')

    const { status } = (await npm(['publish'])) as any
    if (status !== 0) {
      spinner.fail(chalk.red('文档上传失败!'))
      return
    }

    console.log('')
    console.log(
      chalk.green(`文档访问地址：`),
      `https://unpkg.com/${name}@${version}/.arkdoc-dist/index.html`
    )
    console.log('')
    spinner.succeed(chalk.green('文档上传成功!'))
  }
}

export default publishDoc
