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');

var ddd = {
  "status": 0,
  "msg": "操作成功",
  "data": [
    {
      "id": 12,
      "uploadList": [
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "产权证",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/6f4bcd00-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "法人股东证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/71034100-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件1",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/761cf2d0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件2",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/78b68970-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件3",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/7b867250-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "执行董事证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/7f120a10-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "经理证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/80f03ff0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "监事证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8452cbe0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "购票人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/85fcf970-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "办税人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8799e090-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "财务负责人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/890668e0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "秘书联系人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8aad1400-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "社保缴费经办人证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8bf43a00-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "公积金缴费经办人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8d611070-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8eeedc60-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件4",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/90c263e0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件5",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/9252eef0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件6",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/94599460-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件7",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/95d537e0-b9d6-11ea-9e11-29abb292cf5f.png"
        }
      ]
    },
    {
      "id": 23,
      "uploadList": [
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "产权证",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/6f4bcd00-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "法人股东证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/71034100-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件1",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/761cf2d0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件2",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/78b68970-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件3",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/7b867250-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "执行董事证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/7f120a10-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "经理证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/80f03ff0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "监事证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8452cbe0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "购票人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/85fcf970-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "办税人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8799e090-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "财务负责人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/890668e0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "秘书联系人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8aad1400-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "社保缴费经办人证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8bf43a00-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "公积金缴费经办人",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8d611070-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/8eeedc60-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件4",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/90c263e0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-03 23-00-27 的屏幕截图.png",
          "title": "自然人股东证件5",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/9252eef0-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件6",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/94599460-b9d6-11ea-9e11-29abb292cf5f.png"
        },
        {
          "name": "2020-06-11 20-46-55 的屏幕截图.png",
          "title": "自然人股东证件7",
          "viewUrl": "http://test-1258715722.cos.ap-beijing.myqcloud.com/materials/95d537e0-b9d6-11ea-9e11-29abb292cf5f.png"
        }
      ]
    }
  ]
}

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.execPost({}, 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;
    }

    // materiadata = ddd.data;
    //遍历数据
    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 bucket = 'test-1258715722'; /* 必须 */
        var begion = 'ap-beijing';   /* 必须 */
        var that = this;
        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;
                  Bucket = credentials.tmpBucket;
                  Region = credentials.tmpRegion;
                }
              } 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 getParam = await new Promise(function (resv, rej) {
          cos.putObject({
            Bucket: bucket, /* 必须 */
            Region: begion,    /* 必须 */
            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';
          // //请求返回接口，传输上传接口
          await this.restclient.execPost(resultJson, icUpMaterialurl);
        }
      } 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 bucket = 'test-1258715722'; /* 必须 */
    var region = 'ap-beijing';   /* 必须 */
    var that = this;
    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;
              Bucket = credentials.tmpBucket;
              Region = credentials.tmpRegion;
            }
          } 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 subDoTask(params) {
    console.log(params);
    console.log("TestTask1.....");
  }
}
module.exports = IcZipTask;