var fs = require('fs') // 引入fs模块
var join = require('path').join
const path = require('path')
const { copy } = require('fs-extra')
const rimraf = require('rimraf')
const os = require('os')
const { isWindows } = require('../../utils/platform')
const { PAGES_PATH, ROUTER_CONFIG_FILE, ROUTER_FILE } = require('../../constants')
const project = require('../../project')
// 删除指定路径下的文件
// function deleteFile (path) {
//   if (fs.existsSync(path)) {
//     rimraf(path, function (err) { // 删除当前目录下的 aaa
//       if (err) console.log(err)
//     })
//   }
// }

// 获取指定文件夹下所有文件具体路径
function getJsonFiles (jsonPath) {
    let jsonFiles = []

    function findJsonFile (path) {
        let files = fs.readdirSync(path)
        files.forEach(function (item, index) {
            let fPath = join(path, item)
            let stat = fs.statSync(fPath)
            if (stat.isDirectory() === true) {
                findJsonFile(fPath)
            }
            if (stat.isFile() === true) {
                jsonFiles.push(fPath)
            }
        })
    }

    findJsonFile(jsonPath)
    return jsonFiles
}

// 创建嵌套文件夹
function mkdirsSync (dirname) {
    if (fs.existsSync(dirname)) {
        return true
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname)
            return true
        }
    }
}

// 这个方法有问题, des目录没用到, 建议用des, des用path.resolve来解析
function copyDir (ori, des, callback) {
    // 获取所有文件路径
    let files = getJsonFiles(ori)
    for (i = 0; i < files.length; i++) {
        // 原始文件地址
        let originPath = files[i]
        // 目标拷贝地址
        let desPath = originPath.replace('/resourse', '')
        // window下
        desPath = desPath.replace('\\resourse', '')
        //console.log('originPath : ==>', originPath);
        //console.log('desPath : ==>', desPath);

        // 目标拷贝文件夹路径
        let path = require('path')
        let desFilePath = path.parse(desPath).dir

        // 目录不存在时嵌套创建目录
        mkdirsSync(desFilePath)
        fs.writeFileSync(desPath, fs.readFileSync(originPath))
    }
    callback()
}

function firstToUpper (str) {
    str = str.trim()
    return str.replace(str[0], str[0].toUpperCase())
}

/* 更新路由配置
originPath 页面路径
routerPath 路由配置路径
*/
function registerRouterConfig (rootPath, pagePaths, routerPath) {
    let routerJS = `import React from 'react';
import {createAppContainer, createStackNavigator} from 'react-navigation';
  //引入各页面
import Xupd from '~/pages/xupd';
  
const routes = {
    Xupd: {
      screen: Xupd,
    }
  };
  
  const options = {
    initialRouteName: 'Xupd',
    defaultNavigationOptions: {
      headerTintColor: '#fff',
      headerStyle: {
        backgroundColor: '#fff',
      },
    },
    headerMode: 'none',
    mode: 'card',
    onTransitionStart: (to, from) => {},
    onTransitionEnd: (to, from) => {},
  };
  
  class Routers extends React.Component {
    constructor(props) {
      super(props);
    }
  
    render() {
      // this.props change options
      if (this.props.routerName) {
        options.initialRouteName = this.props.routerName;
        const keys = Object.keys(routes);
        keys.forEach((key) => {
          routes[key].params = {};
        });
        routes[this.props.routerName].params = {
          isNative: true,
          ...this.props,
        };
      }
      const StackNavigator = createAppContainer(
        createStackNavigator(routes, options),
      );
      return <StackNavigator />;
    }
  }
  export default Routers;
  `
    const path = require('path')
    const pageDir = project.fs.resolve(PAGES_PATH)

    var replaceStr0 = ''
    var replaceStr1 = ''
    for (i = 0; i < pagePaths.length; i++) {
        let pagePath = pagePaths[i].toString()
        var filePath = path.resolve(pageDir,pagePath)
        if (isWindows()){
            filePath = filePath.replace(/\\/g, "/");
        }
        var importPath = filePath.split('pages/')[1]
        // 页面名称(首字母大写)
        var upFileName = pagePath.toString().replace(/\//g, '_').replace(/\./g, '_')
        upFileName = firstToUpper(upFileName)
        if (isWindows()){
            importPath.replace(/\\/g,"/")
        }
        let importPagePath = `import ${upFileName} from '~/pages/${importPath}';`
        let pageRouter = `  ${upFileName}: {
      screen: ${upFileName},
    },`

        if (replaceStr0.trim() == '') {
            replaceStr0 = `${importPagePath}`
        } else {
            replaceStr0 = `${replaceStr0}\n${importPagePath}`
        }

        if (replaceStr1.trim() == '') {
            replaceStr1 = `${pageRouter}`
        } else {
            replaceStr1 = `${replaceStr1}\n  ${pageRouter}`
        }
    }

    //console.log(replaceStr0)
    //console.log(replaceStr1)

    if (replaceStr0.trim() != '' && replaceStr1.trim() != '') {
        let str = 'const routes = {'
        let importStr = `${replaceStr0}
  \n
  ${str}
  ${replaceStr1}`

        // 防止相同文件重复导入
        routerJS = routerJS.replace(importStr, str)
        //console.log(importStr);
        // 导入文件模块
        routerJS = routerJS.replace(str, importStr)
    }
    fs.writeFileSync(routerPath, routerJS, 'utf8', function (err) {
        if (err)
            console.log('页面路由文件配置失败：' + err)
        else
            console.log('页面路由文件配置成功')
    })
}

function changeXcodeAppDelegateLaunchRouterPage (routerPageName) {
    let rootPath = process.cwd()

    let moduleName = path.parse(rootPath).base
    let appDelegatePath = `${rootPath}/ios/${moduleName}/AppDelegate.swift`
    let configJsonPath = `${rootPath}/src/router/config.json`

    if (fs.existsSync(appDelegatePath) && fs.existsSync(configJsonPath)) {
        let data = fs.readFileSync(configJsonPath)

        let routerConfig = JSON.parse(data)
        let originRouter = routerConfig.routerName

        // 修改Xcode启动路由
        // let oriStr = `"routerName":"${originRouter}"`
        let oriStr = `"routerName":"${originRouter}"`
        let desStr = `"routerName":"${firstToUpper(routerPageName)}"`

        //console.log(oriStr)
        //console.log(desStr)

        updateFileContent(appDelegatePath, oriStr, desStr)

        // 记录Xcode启动路由
        // routerConfig.routerName = firstToUpper(routerPageName)
        // let routerStr = JSON.stringify(routerConfig)
        // fs.writeFileSync(configJsonPath, routerStr)
    }
}

function changeAndroidActivityLaunchRouterPage (routerPageName) {
    let rootPath = process.cwd()
    let moduleName = path.parse(rootPath).base
    let launchActivity = path.normalize(`${rootPath}/android/app/src/main/java/com/${moduleName}/MainActivity.java`)
    // let moduleLaunchActivity = path.normalize(`${rootPath}/android/app/rn/src/main/java/com/${moduleName}/RnActivity.java`)
    let configJsonPath = path.normalize(`${rootPath}/src/router/config.json`)
    console.log('module ' + moduleName)
    console.log('launchActivity ' + launchActivity)
    if (fs.existsSync(launchActivity) && fs.existsSync(configJsonPath)) {
        let data = fs.readFileSync(configJsonPath)

        let routerConfig = JSON.parse(data)
        let originRouter = routerConfig.routerName
        console.log('ChangeAndroidActivity routerPageName ' + routerPageName)
        // 修改Xcode启动路由
        let oriStr = `"routerName", "${originRouter}"`
        let desStr = `"routerName", "${firstToUpper(routerPageName)}"`
        console.log(oriStr)
        console.log(desStr)

        updateFileContent(launchActivity, oriStr, desStr)
        // updateFileContent(moduleLaunchActivity, oriStr, desStr)
        console.log('oriStr: ' + oriStr + ' destStr: ' + desStr)

        // routerConfig.routerName = firstToUpper(routerPageName)
        // let routerStr = JSON.stringify(routerConfig)
        // fs.writeFileSync(configJsonPath, routerStr)
    }
}

/**
 * 更新configure.json 的router
 * @param routerPageName
 */
function updateConfigure (routerPageName) {
    let rootPath = process.cwd()
    let configJsonPath = path.normalize(`${rootPath}/src/router/config.json`)
    if (fs.existsSync(configJsonPath)) {
        let data = fs.readFileSync(configJsonPath)
        let routerConfig = JSON.parse(data)
        routerConfig.routerName = firstToUpper(routerPageName)
        let routerStr = JSON.stringify(routerConfig)
        fs.writeFileSync(configJsonPath, routerStr)
    }
}

/**
 * 获取Config的router
 */
function getOriginalRouterName (routerPage) {
    let rootPath = process.cwd()
    let configJsonPath = path.normalize(`${rootPath}/src/router/config.json`)
    if (fs.existsSync(configJsonPath)) {
        let data = fs.readFileSync(configJsonPath)
        let routerConfig = JSON.parse(data)
        return routerConfig.routerName
    }
}

/**
 * 更新文件内容
 * @param path 被更新文件路径
 * @param find 原始需要被替换的内容
 * @param content 替换成的新内容
 */
function updateFileContent (path, find, content) {
    if (fs.existsSync(path)) {
        let fileContent = fs.readFileSync(path).toString()
        fileContent = fileContent.replace(new RegExp(find, 'g'), content)
        fs.writeFileSync(path, fileContent, 'utf8')
        console.debug('更新文件 ' + path + ' [成功]')
        return
    }
    console.error('更新文件 ' + path + ' [失败]')
}

module.exports = {
    // deleteFile,
    copyDir, registerRouterConfig, updateFileContent, getJsonFiles,
    changeXcodeAppDelegateLaunchRouterPage, changeAndroidActivityLaunchRouterPage,
    getOriginalRouterName, updateConfigure
}

