import path from 'path'
// import inquirer from 'inquirer'
import chalk from 'chalk'
import ora from 'ora'

import { downloadRepo } from '../../utils/git'
import { npm, getPackageLatestVersion } from '../../utils/npm'
import { ejsWriteFile } from '../../utils/file'
const shell = require('shelljs')
const inquirer = require('inquirer')
const fsEx = require('fs-extra')


// 更新r3项目依赖
async function updateR3Dependencies() {
  const R3Version = await getPackageLatestVersion('@syman/burgeon-r3')
  const ARKVersion = await getPackageLatestVersion('@syman/ark-ui')
  const BCLVersion = await getPackageLatestVersion('@syman/ark-ui-bcl')

  let writePath = path.resolve(process.cwd(), './index.html')
  await ejsWriteFile(writePath, writePath, {
    R3_VERSION: R3Version,
    BCL_VERSION: BCLVersion,
    ARK_VERSION: ARKVersion,
  })

  writePath = path.resolve(process.cwd(), './package.json')
  await ejsWriteFile(writePath, writePath, {
    R3_VERSION: R3Version,
    ARK_VERSION: ARKVersion,
  })
}

// 更新r3项目依赖
async function updateArkUiDependencies() {
  const ARKVersion = await getPackageLatestVersion('@syman/ark-ui')

  const writePath = path.resolve(process.cwd(), './index.html')
  await ejsWriteFile(writePath, writePath, {
    ARK_VERSION: ARKVersion,
  })
}

const templateList: any = {
  r3: {
    name: 'r3框架项目', // 命令行选项名称
    git: 'https://gitee.com/bojun_front_end/r3-project-template.git', // git地址
    branch: 'r3-template', // git分支
    script: 'npm start', // 项目启动脚本
    updateDependencies: updateR3Dependencies,
  },
  'ark-ui': {
    name: 'ark-ui项目',
    git: 'https://gitee.com/bojun_front_end/r3-project-template.git',
    branch: 'ark-ui-template',
    script: 'npm start',
    updateDependencies: updateArkUiDependencies,
  },
}

// init命令执行逻辑
async function execInit() {
  const templateChoices = Object.keys(templateList).map((key) => {
    return {
      name: templateList[key].name,
      value: key,
    }
  })

  const { projectName } = await inquirer.prompt({
    type: 'input',
    name: 'projectName',
    message: '请输入项目名称',
    validate: function (value: any) {
      const done = this.async()
      // 检查是否输入项目名称
      if (!value) {
        done('项目名称不能空，请重新输入')
      }

      // 检查是否含有中文
      if (/[\u4e00-\u9fa5]/.test(value)) {
        done('项目名称不能包含中文，请重新输入')
      }
      // 校验项目名称是否重复
      if (fsEx.pathExistsSync(value)) {
        done('项目名称已存在，请重新输入')
      } else {
        done(null, true)
      }
    },
  })
  const { template } = await inquirer.prompt({
    type: 'list',
    name: 'template',
    message: '请选择模板',
    choices: [...templateChoices],
  })

  // 调试
  if (process.env.debug) {
    console.log(chalk.yellow(`debug: 已选择模板:${template}`))
    console.log(
      chalk.yellow(
        `debug: 执行git操作: git clone ${templateList[template].git} -b ${templateList[template].branch}`
      )
    )
  }

  // 下载模板
  const spinner = ora('正在下载模板，请稍等...').start()
  console.log('')
  const createStatus = downloadRepo(templateList[template], {}, projectName)

  if (!createStatus) {
    spinner.fail(chalk.red('模板下载失败'))
    return
  }
  spinner.succeed(chalk.green('模板下载成功'))

  // 去掉模板里的git
  shell.cd(projectName)
  shell.rm('-rf', '.git')

  // 检查依赖是否需要更新
  spinner.start('正在更新模板依赖版本，请稍等...')
  await templateList[template].updateDependencies()
  spinner.succeed(chalk.green('模板依赖版本更新成功'))

  // 安装项目依赖
  spinner.start('开始安装所需依赖，请稍等...')
  console.log('')
  const { status: installStatus } = (await npm(['install'])) as any
  if (installStatus === 0) {
    spinner.succeed(chalk.green('依赖安装成功'))
    console.log('')
    console.log('使用如下命令可运行项目：')
    console.log('')
    console.log(chalk.blue(`cd ${projectName}`)) // 进入项目根目录
    console.log(chalk.blue(templateList[template].script)) // 执行启动脚本
    console.log('')
  } else {
    spinner.fail(chalk.red('依赖安装失败'))
  }
}

export default execInit
