var system=require("../../../system")
const CtlBase = require("../../ctl.base");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd';   
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
var RPCClient = require('@alicloud/pop-core').RPCClient;
getAliTMClient = () => {
    return new RPCClient({
            accessKeyId: 'LTAI4FmyipY1wuLHjLhMWiPa',
            accessKeySecret: 'hp4FF18IDCSym1prqzxrAjnnhNH3ju',
            endpoint: 'https://trademark.aliyuncs.com',
            apiVersion: '2018-07-24'
        }
    );
}
reqbyget = async (obj) => {
    var action = obj.action;
    var reqbody = obj.reqbody;
    var reqAliclient = getAliTMClient();
    if (obj.apiVersion) {
        reqAliclient.apiVersion = obj.apiVersion;
    }
    var res = await reqAliclient.request(action, reqbody, {
        timeout: 10000, // default 3000 ms 2020 0916 lin修改3000为10000，原因ConfirmIcpIntention BizIds 超过5条会超时
        formatAction: true, // default true, format the action to Action
        formatParams: true, // default true, format the parameter name to first letter upper case
        method: 'GET', // set the http method, default is GET
        headers: {}, // set the http request headers
    });
    return res
}

class UploadCtl extends CtlBase {
    constructor() {
        super("common", CtlBase.getServiceName(UploadCtl));
        this.redisClient = system.getObject("util.redisClient");
        this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c  pdf2htmlEX --zoom 1.3 '{fileName}'";
        this.restS=system.getObject("util.execClient");
        this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
        //sed -i  's/1111/&BBB/' /tmp/input.txt
        //sed 's/{position}/{content}/g' {path}
  }
   async getOssConfig(){
    var policyText = {
        "expiration":"2119-12-31T16:00:00.000Z",
        "conditions":[
          ["content-length-range",0,1048576000],
          ["starts-with","$key","zc"]
        ]
    };
    var b = new Buffer(JSON.stringify(policyText));
    var policyBase64 = b.toString('base64');
    var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64

    var data={
        OSSAccessKeyId:accessKeyId,
        policy:policyBase64,
        Signature:signature,
        Bucket:'gsb-zc',
        success_action_status:201,
        url:url
   };

   return data;
  };
  async getOssConfigAli(){
      let res = await this.redisClient.ttl("zqq_alioss")
      if (res>0) {
          res = JSON.parse(await this.redisClient.get("zqq_alioss"))
      }else {
          res = await reqbyget({
              action: "GenerateUploadFilePolicy",
              reqbody: {
                  FileType: "ICON"
              }
          })
          let exp = Math.ceil((res.ExpireTime-Date.now())/1000)
          await this.redisClient.setWithEx("zqq_alioss", JSON.stringify(res),exp)
      }
    return {
        OSSAccessKeyId:res.AccessId,
        policy:res.EncodedPolicy,
        Signature:res.Signature,
        Bucket:'trade-mark-user-upload',
        url: "https://trade-mark-user-upload.oss-cn-beijing.aliyuncs.com",
        filedir: res.FileDir
   };
  };
   async upfile(srckey,dest){
     var oss=system.getObject("util.ossClient");
     var result=await oss.upfile(srckey,"/tmp/"+dest);
     return result;
   };
   async downfile(srckey){
     var oss=system.getObject("util.ossClient");
     var downfile=await oss.downfile(srckey).then(function(){
       downfile="/tmp/"+srckey;
       return downfile;
     });
     return downfile;
   };
   async pdf2html(obj){
     var srckey=obj.key;
     var downfile=await this.downfile(srckey);
     var cmd=this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
     var rtn=await this.restS.exec(cmd);
     var path="/tmp/"+srckey.split(".pdf")[0]+".html";
     var a=await this.insertToFile(path);
     fs.unlink("/tmp/"+srckey);
     var result=await this.upfile(srckey.split(".pdf")[0]+".html",srckey.split(".pdf")[0]+".html");
     return result.url;
   };
   async insertToFile(path){
      var cmd=this.cmdInsertToFilePattern+" "+path;
      return await this.restS.exec(cmd);
   };

}
module.exports=UploadCtl;
