/**
 *官网静态资源发布本地并上传到测试环境
 **/
var path = require('path');
var settings = require('../settings');
var jsdom = require('jsdom');
var xtpl = require('xtpl');
var fs = require('fs');
var iconv = require('iconv-lite');
var vsftp = require('virtual-sftp');
var _ = require('../../lib/util');

module.exports = function (hoo, root, media, releaseSource) {

  var projectFiles = hoo.get('project.files');
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.push('/opening/*.html');
  hoo.set('project.files', projectFiles);

  var wwwSftpUpload = new vsftp({
    host: settings.sftpHost,
    username: settings.sftpUsername,
    password: settings.sftpPassword,
    remoteDir: '/dev_121.201.30.137_zs sftp (121.201.30.137)/www/www/',
    tryKeyboard: true
  });

  var wwwTplsSftpUpload = new vsftp({
    host: settings.sftpHost,
    username: settings.sftpUsername,
    password: settings.sftpPassword,
    remoteDir: '/dev_121.201.30.137_zs sftp (121.201.30.137)/www/www/',
    tryKeyboard: true
  });

  var hdSftpUpload = new vsftp({
    host: settings.sftpHost,
    username: settings.sftpUsername,
    password: settings.sftpPassword,
    remoteDir: '/dev_183_60_122_135_gz sftp (183.60.122.135)/www/www/huodong.37.com/',
    tryKeyboard: true
  });

  var hdConnected = false;
  var wwwConnected = false;
  var tplsConnected = false;
  var openingHtmlCreated = fs.existsSync(path.join(process.cwd(), settings.wwwTplsDir, root, 'opening', 'index.htm'));
  var uploadedResolve;
  var tplsWatched = false;

  hdSftpUpload.on('connect', function () {
    hdConnected = true;
    hoo.log.info('开始上传开服页文件（huodong.37.com）');
  })
    .on('error', function (error) {
      hoo.log.error('活动测试环境sftp连接异常');
    })
    .on('progress', function (progress) {
      var time = '[' + fis.log.now(true) + ']';
      process.stdout.write(
        ' - '.green.bold +
        time.grey + ' ' +
        progress.src.replace(/^\//, '') +
        ' >> '.yellow.bold +
        progress.target +
        '\n'
      );
    }).on('complete', function (hashes) {
    hdSftpUpload.addChecksum(hashes);
    if (hdConnected) {
      hoo.log.info('开服页文件上传完毕（huodong.37.com）');
    }
    hdSftpUpload.uploads = [];
    hdSftpUpload.itemJobs = [];
    wwwTplsSftpUpload.upload();
  });

  wwwSftpUpload.on('connect', function () {
    wwwConnected = true;
    hoo.log.info('官网测试环境sftp连接已建立');
  })
    .on('error', function (error) {
      hoo.log.error('开始上传官网静态资源（img1.37wanimg.com）');
    })
    .on('progress', function (progress) {
      var time = '[' + fis.log.now(true) + ']';
      process.stdout.write(
        ' - '.green.bold +
        time.grey + ' ' +
        progress.src.replace(/^\//, '') +
        ' >> '.yellow.bold +
        progress.target +
        '\n'
      );
    }).on('complete', function (hashes) {
    wwwSftpUpload.addChecksum(hashes);
    if (wwwConnected) {
      hoo.log.info('官网静态资源文件（img1.37wanimg.com）上传完毕');
    }
    wwwSftpUpload.uploads = [];
    wwwSftpUpload.itemJobs = [];
    hdSftpUpload.upload();
  });

  wwwTplsSftpUpload.on('connect', function () {
    tplsConnected = true;
    hoo.log.info('开始上传官网模板文件（common.tpl.37.com）');
  })
    .on('error', function (error) {
      hoo.log.error('官网测试环境sftp连接异常');
    })
    .on('progress', function (progress) {
      var time = '[' + fis.log.now(true) + ']';
      process.stdout.write(
        ' - '.green.bold +
        time.grey + ' ' +
        progress.src.replace(/^\//, '') +
        ' >> '.yellow.bold +
        progress.target +
        '\n'
      );
    })
    .on('complete', function (hashes) {
      wwwTplsSftpUpload.addChecksum(hashes);
      if (tplsConnected) {
        hoo.log.info('官网模板文件上传完毕（common.tpl.37.com）');
      }
      wwwTplsSftpUpload.uploads = [];
      wwwTplsSftpUpload.itemJobs = [];
      uploadedResolve();
    });

  wwwTplsSftpUpload.addPath(path.join(process.cwd(), settings.wwwTplsDir, root), path.join(settings.wwwTplsDomain, root));

  var defineConfig = {};
  /*main.htm模板内容*/
  var mainHtmlWindow = '';
  /*开服页模板内容*/
  var openingHtmlWindow = '';
  /*选服页模板内容*/
  var serverListHtmlWindow = '';
  /*手机官网*/
  var wapHtmlWindow = '';
  /*手机内页*/
  var wapContentHtmlWindow = '';
  var prePromise = new Promise(function (resolve) {
    jsdom.env(
      path.join(process.cwd(), settings.wwwTplsDir, root, 'main.htm'),
      {defaultEncoding: 'UTF-8'},
      function (err, window) {
        mainHtmlWindow = window;
        resolve();
      }
    );
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'server_list.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          serverListHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'wap/index.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          wapHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'wap/article/content.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          wapContentHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.openingRoot, settings.openingTemplatePath, root, 'index.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          openingHtmlWindow = window;
          resolve();
        }
      );
    });
  });

  var hooMatches = hoo.media(media, defineConfig).match('**', {
    useHash: !!releaseSource ? false : true,
    useCache: true
  })
    .match('/opening/*.html', {
      isInline: false,
      release: '$0'
    })
    .match('/css/main/**.{css,scss}', {
      packTo: '/static/bundle.css'
    })
    .match('/css/*main.{css,scss}', {
      packTo: '/static/bundle.css'
    })
    .match('/css/app/**.{css,scss}', {
      useSprite: true
    })
    .match('/static/bundle.css',{
      useSprite: true
    })
    .match('/opening/**.{css,scss}', {
      useSprite: true
    })
    .match('**.{png,jpg,mp4}', {
      domain: "http://" + path.join(settings.wwwDeployDomain, root).replace(/\\/g, '/')
    })
    .match('/opening/**', {
      domain: false
    })
    .match('/opening/**/(*.{css,scss})', {
      domain: '/static',
      release: path.join('css', root, '1/') + '$1$2'
    })
    .match('/opening/**/(*.{png,jpg})', {
      domain: '/static',
      release: path.join('images', root, '1/') + '$1$2'
    })
    .match('/css/images/extras/**', {
      useHash: false
    })
    .match('::package', {
      packager: hoo.plugin('map', {
        useTrack: false// 是否输出路径信息,默认为 true
      }),
      // 分析 __RESOURCE_MAP__ 结构，来解决资源加载问题
      postpackager: hoo.plugin('loader', {
        resourceType: 'amd',
        useInlineMap: true
      }, 'prepend')
    })
    .match('**', {
      deploy: [
        hoo.plugin('skip-packed', {
          // 配置项
          skipPackedToPkg: true,//是否过滤掉被打包的文件
          skipPackedToAIO: true,//是否过滤掉被 AllInOne 打包的文件
          skipPackedToCssSprite: true,//是否过滤掉被 css sprite 合并的文件。
          ignore: []//即便设置了过滤，但是如果目标文件 ignore 列表中，还是不会被过滤。glob 语法，数组或者字符串。
        }),
        function (options, modified, total, next) {
          var i = modified.length - 1;
          var file;
          while ((file = modified[i--])) {
            if (file.isHtmlLike) {
              modified.splice(i + 1, 1)
            } else if (file.isJsLike) {
              wwwSftpUpload.addPath(path.join(process.cwd(), settings.wwwDeployDir, root, file.getHashRelease()), path.join(settings.wwwDeployDomain, root, file.getHashRelease()));
              (function (file) {
                prePromise = prePromise.then(function () {
                  return new Promise(function (resolve) {
                    var jsLoader1 = mainHtmlWindow.document.getElementById("jsLoader");
                    var jsLoader2 = serverListHtmlWindow.document.getElementById("jsLoader");
                    jsLoader1 && (jsLoader1.src = 'http://' + path.join(settings.wwwDeployDomain, root, file.getHashRelease()).replace(/\\/g, '/'));
                    jsLoader2 && (jsLoader2.src = 'http://' + path.join(settings.wwwDeployDomain, root, file.getHashRelease()).replace(/\\/g, '/'));
                    resolve();
                  })
                })
              })(file);
            } else if (file.isCssLike) {
              (function (file) {
                if (file.filename === 'bundle') {
                  wwwSftpUpload.addPath(path.join(process.cwd(), settings.wwwDeployDir, root, file.getHashRelease()), path.join(settings.wwwDeployDomain, root, file.getHashRelease()));
                  prePromise = prePromise.then(function () {
                    return new Promise(function (resolve) {
                      var cssLoader1 = mainHtmlWindow.document.getElementById("cssLoader");
                      var cssLoader2 = serverListHtmlWindow.document.getElementById("cssLoader");
                      cssLoader1 && (cssLoader1.href = 'http://' + path.join(settings.wwwDeployDomain, root, file.getHashRelease()).replace(/\\/g, '/'));
                      cssLoader2 && (cssLoader2.href = 'http://' + path.join(settings.wwwDeployDomain, root, file.getHashRelease()).replace(/\\/g, '/'));
                      resolve();
                    })
                  });
                } else if (file.subdirname.indexOf('opening') !== -1) {
                  hdSftpUpload.addPath(path.join(settings.openingRoot, settings.openingStaticPath, file.getHashRelease()), path.join(settings.openingStaticPath, file.getHashRelease()))
                  prePromise = prePromise.then(function () {
                    return new Promise(function (resolve) {
                      var cssLoader = openingHtmlWindow.document.getElementById("cssLoader");
                      cssLoader && (cssLoader.href = file.map.uri);
                      resolve();
                    })
                  });
                } else if (file.map && file.map.uri.indexOf('app') !== -1) {
                  wwwSftpUpload.addPath(path.join(process.cwd(), settings.wwwDeployDir, root, file.map.uri), path.join(settings.wwwDeployDomain, root, file.map.uri));
                  prePromise = prePromise.then(function () {
                    return new Promise(function (resolve) {
                      var cssLoader1 = wapHtmlWindow.document.getElementById("cssLoader");
                      var cssLoader2 = wapContentHtmlWindow.document.getElementById("cssLoader");
                      cssLoader1 && (cssLoader1.href = 'http://' + path.join(settings.wwwDeployDomain, root, file.map.uri).replace(/\\/g, '/'));
                      cssLoader2 && (cssLoader2.href = 'http://' + path.join(settings.wwwDeployDomain, root, file.map.uri).replace(/\\/g, '/'));
                      resolve();
                    })
                  });
                }
              })(file);
            } else {
              if (file.subpath.indexOf('opening') === -1) {
                wwwSftpUpload.addPath(path.join(process.cwd(), settings.wwwDeployDir, root, file.getHashRelease()), path.join(settings.wwwDeployDomain, root, file.getHashRelease()));
              } else {
                hdSftpUpload.addPath(path.join(settings.openingRoot, settings.openingStaticPath, file.getHashRelease()), path.join(settings.openingStaticPath, file.getHashRelease()));
              }
            }
          }
          next();
        },
        require('../../lib/wwwLocalDeliver')(path.join(settings.wwwDeployDir, root), 'opening', path.join(settings.openingRoot, settings.openingStaticPath))
      ]
    });

  if (!releaseSource) {
    hooMatches.match('**.{css,scss}', {
      optimizer: hoo.plugin('clean-css', {})
    })
      .match('**.js', {
        optimizer: hoo.plugin('uglify-js')
      })
  }

  hoo.on('deploy:end', function () {
    hdConnected = false;
    wwwConnected = false;
    tplsConnected = false;

    return;
    console.log("xxxxxx");

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        if (openingHtmlCreated) {
          fs.writeFile(path.join(settings.openingRoot, settings.openingTemplatePath, root, 'index.htm'), openingHtmlWindow.document.documentElement.outerHTML, function (err) {
            if (err) {
              hoo.log.error(err);
              return;
            }
            resolve();
          });
        } else {
          resolve();
        }
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'main.htm'), mainHtmlWindow.document.body.innerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'server_list.htm'), serverListHtmlWindow.document.body.innerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'wap/index.htm'), wapHtmlWindow.document.documentElement.outerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'wap/article/content.htm'), wapContentHtmlWindow.document.documentElement.outerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
       /* if (!tplsWatched) {
          require('../../lib/watchFiles')(path.join(process.cwd(), settings.wwwTplsDir, root), function (event,target) {
            wwwTplsSftpUpload.addPath(target, path.relative(process.cwd(), target));
            console.log(target);
          });
          tplsWatched = true;
        }*/
        wwwSftpUpload.upload();
        uploadedResolve = resolve;
      });
    });

    prePromise.then(function () {
      console.log('---------------完成-----------------');
    });
  });
};
