require('./global/index');
const fs = require('fs');
const ora = require('ora');
const chalk = require('chalk');
// const webpack = require('webpack');
const path = require('path');
const qrcode = require('qrcode-terminal');
// const zipDir = require('zip-directory');
const superagent = require('superagent');
const extract = require('extract-zip');

const { launchStaticServer } = require('./pipeline/launch-server');
const { Compiler } = require('./pipeline/webpack-build');
const { zip } = require('./pipeline/zip');
const { getDebugUrl } = require('./pipeline/debug-tool');

const renderConfig = require('./webpack.render');
// const serviceConfig = require('./webpack.service');
const serviceConfigBase = require('./splitChunksConfig/webpack.service.base');
const serviceConfig = require('./splitChunksConfig/webpack.service');
const getIpAddress = require('./getIpAddress');

const ROOT = process.cwd();
const SRC = path.join(ROOT, 'src');
const DIST = path.join(ROOT, 'dist');
let wsInstance = null;


if (!fs.existsSync(path.join(ROOT, 'zip'))) {
    fs.mkdirSync(path.join(ROOT, 'zip'));
}

// zip 目录建立 static host，用于给 app 下载 zip 包
if (!process.env.TEST_BUILDER && process.argv.indexOf('no-serve') === -1) {
    launchStaticServer(path.join(ROOT, 'zip'));
}

// 强制校验 mid。
let midStr = '';

process.argv.some(arg => {
    if (arg.indexOf('mid') === 0) {
        midStr = arg;
        return true;
    }
});

if (midStr === '') {
    console.log('[bili-error]:请使用 mid 命令行进行构建，命令：npm run build mid=xxx \r\n');
    process.exit();
}

const spinner = ora('building for pages...');
spinner.start();

if (!fs.existsSync(path.join(ROOT, 'src/service.js'))) {
    fs.writeFileSync(path.join(ROOT, 'src/service.js'), '', 'utf-8');
}

// package.json 中的 small-app 的版本号
let packageSapp = ''
// 本地安装的small-app的版本号（包含：安装、没有安装）
let localSappVersion = ''
// 远端的small-app的版本号最新
let serveSappVersion = ''
// 远端的small-app的所有tag号
let serveSappAllTags = ''

// 检查本地 small-app版本号
try {
    const packageJson = fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8');
    const _packageJson = JSON.parse(packageJson);
    packageSapp = _packageJson.dependencies['bili-small-app'];
} catch (e) {
    console.log('[biliSapp - warn]:检测到当前小程序未安装「 bili-small-app 」。')
}

const exec = require('child_process').execSync;
// 检查远端 small-app版本号
try {
    const serveJSON = exec('npm view bili-small-app -json');
    serveSappVersion = JSON.parse(serveJSON.toString("utf8")).version;
    serveSappAllTags = JSON.parse(serveJSON.toString("utf8"))['dist-tags'];
} catch (e) {
    console.log('[biliSapp - warn]:', '检查「 bili-small-app 」最新版本失败，请在控制台检查「 npm view bili-small-app 」命令是否可用.')
}

let localSapp = {};

try {
    localSapp = JSON.parse(exec('npm list bili-small-app -json'));
    localSappVersion = localSapp.dependencies['bili-small-app'].version;
} catch (e) {
    // console.log('---', e)
    // 如果用户本地没有安装 bili-small-app 或者  使用 link 软链的，则npm会报错。
    // if (localSapp.problems.length > 0) {
    //     console.log('[biliSapp - warn]:', localSapp.problems.join('.'))
    // }
}

console.log('------>', packageSapp, localSappVersion, serveSappVersion);
console.log('------>', serveSappAllTags[packageSapp], path.join(ROOT, './'));

const isTagBySapp = !!serveSappAllTags[packageSapp]
console.log('isTagBySapp', isTagBySapp)
if (!isTagBySapp) {
    console.log('更新最新npm');
    exec('npm i bili-small-app@latest', {
        cwd: path.join(ROOT, './')
    });
    console.log('更新最新npm成功');

    // console.log('更新最新npm');
    // exec('npm i bili-small-app@latest')
    // console.log('更新最新npm 成功');
}

// let buildType = 'sapp';
// let mode = 'build';
// let base = null;
// process.argv.forEach(arg => {
//     if (arg.indexOf('--watch') === 0 || arg.indexOf('-w') === 0) {
//         mode = 'watch';
//     } else if (arg.indexOf('--widget') === 0) {
//         buildType = 'widget';
//     } else if (arg.indexOf('--base') === 0) {
//         base = arg.split('=')[1];
//     }
// });
//
// // const compiler = new Compiler([renderConfig(ROOT), serviceConfig(ROOT, SRC)]);
// const compiler = new Compiler([renderConfig(ROOT, 'development'), serviceConfigBase(ROOT, SRC, 'development'), serviceConfig(ROOT, SRC, 'development')]);
//
// if (mode === 'build') {
//     compiler.build(false).then(() => {
//         compilerDone();
//     });
// } else if (mode === 'watch') {
//     compiler.watch(false, compilerDone);
// }
//
// async function compilerDone() {
//     // fs.unlink(path.join(SRC, 'service.js'), () => {});
//
//     // 兜底，分包如果没打出common.service.js，则手动写一个空的，因为客户端逻辑是加载到common.service.js才进行分包逻辑
//     if (!fs.existsSync(path.join(DIST, './common.service.js'))) {
//         fs.writeFileSync(path.join(DIST, './common.service.js'), '"";', 'utf-8');
//     }
//
//     spinner.stop();
//
//     const zipName = new Date().toJSON().replace(/[-:.TZ]/g, '') + '.zip';
//     if (!fs.existsSync(path.join(ROOT, 'zip'))) {
//         fs.mkdirSync(path.join(ROOT, 'zip'));
//     }
//     const zipPath = path.join(ROOT, 'zip', zipName);
//     let zipLatestName = 'latest.zip';
//
//     if (mode === 'watch') {
//         zipLatestName = 'watch.zip';
//     }
//     const latestZipPath = path.join(ROOT, 'zip', zipLatestName);
//
//     const zipFiles = [latestZipPath];
//     if (mode === 'build') {
//         zipFiles.push(zipPath);
//     }
//
//     if (base) {
//         if (!path.isAbsolute(base)) {
//             base = path.resolve(process.cwd(), base);
//         }
//         const targetDist = path.resolve(process.cwd(), 'dist/');
//
//         if (!fs.existsSync(base)) {
//             console.error('base 路径不存在，请检查路径是否正确');
//             process.exit();
//         }
//
//         try {
//             await extract(base, { dir: targetDist });
//         } catch (e) {
//             console.error(e);
//
//             process.exit();
//         }
//     }
//
//     zip(DIST, ...zipFiles).then(async() => {
//         const ip = getIpAddress();
//         const sapprc = JSON.parse(fs.readFileSync(path.join(ROOT, '.sapprc'), 'utf8'));
//         let storageId = '';
//         // let debugURL = `https://miniapp.bilibili.com/applet/debug/${sapprc.appId}_${sapprc.vAppId}?url=${encodeURIComponent(`http://${ip}:3000/${zipName}`)}`;
//         // let debugURL = `https://miniapp.bilibili.com/applet/debug/${sapprc.appId}_${sapprc.vAppId}?url=${encodeURIComponent(`http://${ip}:3000/${zipLatestName}`)}`;
//         let debugURL = getDebugUrl({
//             type: buildType,
//             ip,
//             zipName: zipLatestName,
//             sapprc,
//             embedBase: !!base
//         });
//
//         if (midStr) {
//             // mid=xxx
//             let mid = midStr.slice(4);
//
//             try {
//                 let uploadUrl = '';
//
//                 let upZipResponse = await superagent
//                     .post('http://mall-mng.bilibili.co/mall-mng/picture/image')
//                     .attach('file', latestZipPath, zipName);
//                 if (upZipResponse.status === 200 && upZipResponse.body.code === 0 && upZipResponse.body.data) {
//                     uploadUrl = 'http:' + upZipResponse.body.data;
//                 } else {
//                     console.log('本地构建失败，请重试');
//                     process.exit();
//                     return;
//                 }
//
//                 // 本地调试校验参数判断
//                 let _tempParam = {appId: sapprc.appId, url: uploadUrl, isValidUrl: 0 }
//                 if (global._bili_cache_data.isInternal) {
//                     _tempParam.staff = mid;
//                 } else {
//                     _tempParam.mid = mid;
//                 }
//
//                 let upResponse = await superagent
//                     .post('http://miniapp.bilibili.com/api/storage/dev_storage/upload')
//                     .send(_tempParam)
//                     .set('Accept', 'application/json');
//                 if (upResponse.status === 200 && upResponse.body.code === 0) {
//                     storageId = upResponse.body.data;
//                     debugURL = getDebugUrl({
//                         type: buildType,
//                         ip,
//                         zipName: zipLatestName,
//                         sapprc,
//                         storageId
//                     });
//                 } else {
//                     console.log('本地构建失败：', upResponse.body.message);
//                     process.exit();
//                     return;
//                 }
//             } catch (error) {
//                 console.log('本地构建失败，请重试');
//                 process.exit();
//                 return;
//             }
//         }
//
//         console.log(chalk.cyan('  Build service complete.\n'));
//         if (process.env.TEST_BUILDER || process.argv.indexOf('no-serve') !== -1) {
//             return;
//         }
//
//         let devtoolPort;
//         // 调试工具静态端口一般从10022开始
//         // 发现window版本扫描接口较慢，这里就不做过多的扫描了
//         for (let i = 10022; i < 10028; i++) {
//             try {
//                 const response = await superagent.post(`http://localhost:${i}/devtool-scan`).send({});
//                 if (response.status === 200 && response.text === 'small-app-devtool-application listened...') {
//                     devtoolPort = i;
//                     break;
//                 }
//             } catch (error) {
//                 // console.error(error);
//             }
//         }
//         if (devtoolPort) {
//             await superagent.post(`http://localhost:${devtoolPort}/devtool-debug`).send({ debugURL });
//             console.log(chalk.cyan('检测到调试工具正在运行，可以使用调试工具进行调试啦'));
//         } else {
//             qrcode.generate(debugURL, {small: true});
//             console.log(debugURL);
//             console.log(chalk.cyan('真机调试服务正在运行，可以用手机扫码调试构建出来的安装包啦'));
//         }
//         console.log(chalk.cyan('若要重新构建需退出（ctrl+c），再执行一次 npm run build'));
//
//         wsInstance && wsInstance.send('hotreload');
//     });
// }
