const TaskBase = require("../../task.base");
const settings = require("../../../../config/settings");
var excel = require('exceljs');
var archiver = require('archiver');
var xlsx = require('node-xlsx');
const system = require("../../../system");
const fs = require('fs');
const COS = require('cos-nodejs-sdk-v5');
const request = require('request');
var child_process = require('child_process');

class IcZipTask extends TaskBase {
  constructor() {
    super(TaskBase.getServiceName(IcZipTask));
    this.cosgetsecreturl = settings.cosGetSecreturl();
    this.icMaterialurl = settings.icMaterialurl();
    this.restclient = system.getObject("util.restClient");
  }


  async subBeforeTask(params) {
    //创建目录,判断文件目录是否存在，不存在就创建  /tmp/icp
    var icpPath = '/tmp/ic'
    if (!fs.existsSync(icpPath)) {
      fs.mkdirSync(icpPath);
    }
    //请求材料数据
    var materiadata = [];
    try {
      var icGetMaterialurl = this.icMaterialurl + '/web/bizchance/materialCtl/waitGenerate';
      console.log(icGetMaterialurl);
      var rtn = await this.restclient.execPost3({}, icGetMaterialurl);
      if (!rtn || !rtn.stdout) {
        return;
      }
      var result = JSON.parse(rtn.stdout);
      if (result.status == 0) {
        if (result.data.length > 0) {
          materiadata = result.data;
        } else {
          return;
        }
      } else {
        return;
      }
    } catch (error) {
      // console.log(error);
      return;
    }
    try {
      var that = this;
      var bucketandregion = await this.getBucketRegion(that.cosgetsecreturl)
      var bucket = bucketandregion.bucket; /* 必须 */
      var region = bucketandregion.region;   /* 必须 */
      var cos = new COS({
        getAuthorization: function (options, callback) {
          // 异步获取临时密钥
          request({
            url: that.cosgetsecreturl,
            data: {
              // 可从 options 取需要的参数
              // Bucket: 'test-1258715722', /* 必须 */
              // Region: 'ap-beijing',    /* 必须 */
            }
          }, function (err, response, body) {
            try {
              var resultdata = JSON.parse(body);
              if (resultdata.status == 1) {
                var data = resultdata.data;
                var credentials = data.credentials;
              }
            } catch (e) { }
            if (!data || !credentials) return console.error('credentials invalid');
            callback({
              TmpSecretId: credentials.tmpSecretId,        // 临时密钥的 tmpSecretId
              TmpSecretKey: credentials.tmpSecretKey,      // 临时密钥的 tmpSecretKey
              XCosSecurityToken: credentials.sessionToken, // 临时密钥的 sessionToken
              ExpiredTime: data.expiredTime,               // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
            });
          });
        }
      });
    } catch (error) {
      return;
    }

    //遍历数据
    for (var j = 0; j < materiadata.length; j++) {
      try {
        var icinfo = materiadata[j];
        //编号id
        var Id = icinfo.id;
        var id_dir = '/tmp/ic/' + Id;
        //创建目录,判断文件目录是否存在，不存在就创建  /tmp/icp
        if (!fs.existsSync(id_dir)) {
          fs.mkdirSync(id_dir);
        }
        //下载文件
        var files = icinfo.uploadList;
        await this.downFile(files, id_dir);


        //打包压缩
        var zipdir = id_dir + '.zip';
        var output = fs.createWriteStream(zipdir);
        var archive = archiver('zip');
        archive.on('error', function (err) {
          throw err;
        });
        archive.pipe(output);
        archive.directory(id_dir, false);
        await archive.finalize();

        var resultJson = {
          'id': Id,
          'url': ''
        }
        //把打包文件上传到cos
        var getParam = await new Promise(function (resv, rej) {
          cos.putObject({
            Bucket: bucket, /* 必须 */
            Region: region,    /* 必须 */
            Key: zipdir,       /* 必须 */
            Body: fs.createReadStream(zipdir),
          }, function (err, data) {
            if (err) {
              rej(false);
            } else {
              if (data.statusCode == 200) {
                resv(data.Location);
              } else {
                resv(false);
              }
            }
          });
        });
        if (getParam) {
          resultJson.url = 'http://' + getParam;
          console.log(resultJson);
          var icUpMaterialurl = this.icMaterialurl + '/web/bizchance/materialCtl/updateZipById';
          // //请求返回接口，传输上传接口
          var res = await this.restclient.execPost3(resultJson, icUpMaterialurl);
          console.log(res);
        }
      } catch (error) {
        continue;
      }
    }
    // 删除文件夹
    for (var j = 0; j < materiadata.length; j++) {
      var icinfo = materiadata[j];
      //编号id
      var Id = icinfo.id;
      //文件夹
      var id_dir = '/tmp/ic/' + Id;
      //压缩包
      var id_zip = id_dir + '.zip';
      // if (fs.existsSync(id_dir)) {
      //   // delete
      //   child_process.spawn('rm', ['-r', id_dir]);
      // }
      // if (fs.existsSync(id_zip)) {
      //   child_process.spawn('rm', [id_zip]);
      // }
    }

  }
  //下载文件函数
  async downFile(data, dir) {
    // console.log(data, dir);
    //下载文件
    var that = this;
    var bucketandregion = await this.getBucketRegion(that.cosgetsecreturl)
    var bucket = bucketandregion.bucket; /* 必须 */
    var region = bucketandregion.region;   /* 必须 */
    var cos = new COS({
      getAuthorization: function (options, callback) {
        // 异步获取临时密钥
        request({
          url: that.cosgetsecreturl,
          data: {
            // 可从 options 取需要的参数
            // Bucket: "brg-1257943044",   /* 必须 */
            // Region: "ap-nanjing",       /* 必须 */
          }
        }, function (err, response, body) {
          try {
            var resultdata = JSON.parse(body);
            if (resultdata.status == 1) {
              var data = resultdata.data;
              var credentials = data.credentials;
            }
          } catch (e) { }
          if (!data || !credentials) return console.error('credentials invalid');
          callback({
            TmpSecretId: credentials.tmpSecretId,        // 临时密钥的 tmpSecretId
            TmpSecretKey: credentials.tmpSecretKey,      // 临时密钥的 tmpSecretKey
            XCosSecurityToken: credentials.sessionToken, // 临时密钥的 sessionToken
            ExpiredTime: data.expiredTime,               // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
          });
        });
      }
    });
    var downfiles = data;
    for (var i = 0; i < downfiles.length; i++) {
      var filedata = downfiles[i];
      var viewUrl = filedata.viewUrl;
      var arr = viewUrl.split("myqcloud.com/")
      if (arr.length > 1) {
        var key = arr[arr.length - 1];
        var key_arr = key.split(".")
        var key_type = key_arr[key_arr.length - 1];
        var title = filedata.title;
        if (title) {
          var titlename = title + '.' + key_type;
          var output = dir + '/' + titlename;
          await this.downLoadFile(bucket, region, cos, key, output);
        }
      }
    }
  }
  downLoadFile(bucket, region, cos, key, output) {
    return new Promise((resolve, reject) => {
      cos.getObject({
        Bucket: bucket, /* 必须 */
        Region: region,    /* 必须 */
        Key: key,
        Output: output,
      }, function (err, data) {
        // console.log(err || data);
        if (err) {
          reject(false);
        } else {
          resolve(true);
        }
      });
    })
  }
  //获取账号和地域信息
  async getBucketRegion(cosgetsecreturl) {
    var br = {
      bucket: 'csig-brgicp-dev-1258344699', /* 必须 */
      region: 'ap-guangzhou',  /* 必须 */
    }
    try {
      var rtn = await this.restclient.execPost({}, cosgetsecreturl);
      if (!rtn || !rtn.stdout) {
        return br;
      }
      var result = JSON.parse(rtn.stdout);
      if (result.status == 1) {
        var credentials = result.data.credentials;
        br.bucket = credentials.tmpBucket;
        br.region = credentials.tmpRegion;
        return br;
      } else {
        return br;
      }
    } catch (error) {
      // console.log(error);
      return br;
    }
  }

  async subDoTask(params) {
    console.log(params);
    console.log("TestTask1.....");
  }
}
module.exports = IcZipTask;