/*
 * @Author: YeeChan
 * @Date: 2021-06-02 11:27:38
 * @Description: 
 */

'use strict';

let fs = require('fs');
let path = require('fire-path');

const { Client } = Editor.require("packages://sftp/node_modules/ssh2");
const archiver = Editor.require("packages://sftp/node_modules/archiver");

Editor.Panel.extend({

  style: fs.readFileSync(Editor.url("packages://sftp/panel/index.css"), "utf-8"),
  template: fs.readFileSync(Editor.url("packages://sftp/panel/index.html"), "utf-8"),

  // method executed when template and styles are successfully loaded and initialized
  ready() {
    const app = new window.Vue({
      el: this.shadowRoot,
      created() {
        this._panelCreated();
      },
      init() {
      },
      data: {
        cfgPath: Editor.url('packages://sftp/configsftp.json'),
        profile: null,
        uploadProgress: 0,
        remoteRoot: "/www/wwwroot/renyounew.5iape.com/",//远端的地址
        remotePath: "/www/wwwroot/renyounew.5iape.com/remoteGame/",//远端的地址
        clientConfig: {
          host: '47.102.195.197',
          port: 22,
          username: 'test',
          password: 'test'
        }
      },
      methods: {
        //保存配置
        saveProfile() {
          fs.writeFileSync(this.cfgPath, JSON.stringify(this.profile));
        },
        _panelCreated() {
          if (!fs.existsSync(this.cfgPath)) {
            let defaultData = {
              'localPath': './build/web-desktop/',
              'gameName': '',
              'remote': false
            }; // 你自己默认的数据
            fs.writeFileSync(this.cfgPath, JSON.stringify(defaultData));
          }
          this.profile = JSON.parse(fs.readFileSync(this.cfgPath, 'utf-8'));

        },

        //保存配置
        onBtnClickSave(event) {
          Editor.log('onBtnClickSave');
          this.saveProfile();
        },

        /**
       * 描述:连接远程电脑
       * 回调:then(conn) 连接远程的client对象
       */
        Connect(then) {
          let conn = new Client();
          conn.on("ready", function () {
            then(conn);
          }).on('error', function (err) {
            Editor.log("connect error!", err);
          }).on('end', function () {
            // console.log("connect end!");
          }).on('close', function (had_error) {
            //console.log("connect close");
          }).connect({
            host: '47.102.195.197',
            port: 22,
            username: 'root',
            password: '#WHmiR6g27i!w5OF'
          });
        },

        /**
         * 执行命令
         * @param {*} conn 
         * @param {*} cmd 
         * @param {*} then 
         */
        execCmd(conn, cmd, then) {
          conn.exec(cmd, function (err, stream) {
            if (err) {
              Editor.error(err)
              then(-1, err);
            } else {
              stream.on('close', function (code, signal) {
                Editor.log("命令执行完毕:" + cmd)
                then(0)
              }).on('data', function (data) {
                // Editor.log('STDOUT: ' + data);
                then(1, data);
              }).stderr.on('data', function (data) {
                Editor.log('执行命令错误: ' + data);
              });
            }
          });
        },

        //上传
        onBtnClickUpload2(event) {
          let me = this;
          if (me.profile.gameName == "") {//默认无
            Editor.log("请设置游戏的名字");
            return;
          }
          if (me.profile.localPath == "") {//默认无
            Editor.log("请设置本地的文件夹");
            return;
          }
          let localPath = path.resolve(Editor.Project.path, me.profile.localPath);
          //远程包
          if (me.profile.remote) {
            localPath = path.resolve(localPath, "remote");
            Editor.log("远程包上传");
          } else {
            Editor.log("远程包上传");
          }
          Editor.log('上传本地路径:' + localPath);
          if (!fs.existsSync(localPath)) {
            Editor.log('本地路径不存在:请重新设置');
            return
          }

          me.saveProfile();
          me.uploadProgress = 0;
          let remotePath = path.posix.join(me.remotePath, me.profile.gameName)

          let zipname = 'upload.zip';
          let zipFilePath = path.join(localPath, '../', zipname)

          Editor.log('准备压缩...');
          var output = fs.createWriteStream(zipFilePath);
          var archive = archiver('zip', {
            zlib: {
              level: 9
            }
          });
          output.on('close', function () {
            Editor.log('压缩完成');

            let remoteZipFilePath = path.join(remotePath, zipname)
            let remoteZipFilePathPosix = path.posix.join(remotePath, zipname)

            // Editor.log('zipFilePath ' + zipFilePath);
            // Editor.log('remoteZipFilePath ' + remoteZipFilePath);
            // Editor.log('remoteZipFilePathPosix ' + remoteZipFilePathPosix);
            me.Connect(function (conn) {
              // 判断文件夹的存在 删除并创建
              let cmd = `cd ${me.remotePath} && rm -rf ${me.profile.gameName} && mkdir ${me.profile.gameName}`;
              me.execCmd(conn, cmd, function (code, info) {
                if (code == 0) {
                  me.sftp(zipFilePath, remoteZipFilePath, remoteZipFilePathPosix);
                }
              });
            });
          });
          archive.pipe(output);
          if (me.profile.remote) {
            archive.directory(localPath, "remote");
          } else {
            archive.directory(localPath, false);
          }
          archive.finalize();
        },

        //上传
        sftp(zipFilePath, remoteZipFilePath, remoteZipFilePathPosix) {
          Editor.log("准备上传...")
          let me = this;
          me.Connect(function (conn) {
            conn.sftp((err, sftp) => {
              if (err) {
                throw err;
              }
              sftp.fastPut(zipFilePath, remoteZipFilePathPosix, {
                step: function (total, nb, fsize) {
                  let progess = Math.round(total / fsize * 100)
                  if (progess > 90) {
                    progess = 90;
                  }
                  me.uploadProgress = progess;
                }
              }, (err) => {
                if (err) {
                  throw err;
                }
                Editor.log('上传完成');
                conn.end();
                // 删掉本地的zip文件
                if (fs.existsSync(zipFilePath)) {
                  Editor.log('删掉本地zip文件 ' + zipFilePath)
                  fs.unlinkSync(zipFilePath);
                }
                //解压
                me.unzip(remoteZipFilePath);
              });
            });
          })
        },
        // 解压文件到当先目录
        unzip(zipfile) {
          Editor.log('准备解压...');
          let me = this;
          let zipName = path.basename(zipfile);
          let remotePath = path.posix.join(me.remotePath, me.profile.gameName)
          let cmd = `cd ${remotePath} && unzip -o  ${zipName}`;
          me.Connect(function (conn) {
            me.execCmd(conn, cmd, function (code, info) {
              if (code == 0) {
                Editor.log("解压完成");
                me.uploadProgress = 95;
                me.synShell()
              }
            });
          });
        },
        //同步shell
        synShell() {
          let me = this;
          let cmd2 = `cd ${me.remoteRoot} && ./mainscp.sh ${me.remotePath}${me.profile.gameName}`
          Editor.log("同步命令:" + cmd2)
          me.Connect(function (conn) {
            me.execCmd(conn, cmd2, function (code, info) {
              if (code == 0) {
                me.uploadProgress = 100;
                Editor.log("多服务器同步完成");
                let url = "https://renyousome.5iape.com/remoteGame/" + me.profile.gameName + "/";
                Editor.log("目标地址:" + url)
              } else {
                // Editor.log("同步中:" + info);
              }
            });
          });
        }

      }
    })
  },
});