var System = require("../../system")
const crypto = require('crypto');
var xlsx = require('node-xlsx');
var fs = require("fs");
var accesskey = 'DHmRtFlw2Zr3KaRwUFeiu7FWATnmla';
var accessKeyId = 'LTAIyAUK8AD04P5S';
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
class ToolCtl {
  constructor() {
    this.imghandleApi = System.getObject("api.imghandle");
    this.gsbSearchApi = System.getObject("api.gsbtmsearch");
    this.gsbIcSearchApi = System.getObject("api.gsbicsearch");
    this.uploadCtl = System.getObject("web.uploadCtl");
    this.bytmsearch = System.getObject("api.bytmsearch");
    this.ossClient = System.getObject("util.ossClient");
    this.wxSve = System.getObject("service.wxSve");
    this.cacheManager = System.getObject("db.cacheManager");
    this.appKeyStr = "wx76a324c5d201d1a4";
    this.mailClient = System.getObject("util.mailClient");
    this.redisClient=System.getObject("util.redisClient");
    this.pytmreportSve = System.getObject("service.pytmreportSve");
    this.companySve = System.getObject("service.companySve");
    this.wxuserSve = System.getObject("service.wxuserSve");
  }
  async getUidStr(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  async writeFile(filePath, dataBuffer) {
    var promise = new Promise(function (resv, rej) {
      fs.writeFile(filePath, dataBuffer, function (err, data) {
        if (err) {
          rej(err);
          // console.log(err);
        } else {
          resv("success");
        }

      });
    });
    return promise;
  }
  //读取excel
  async readXlsx(srckey) {
    var path = await this.uploadCtl.downfile(srckey);
    console.log(path);
    console.log("obj");
    if (!path) {
      return { code: -3, mag: "path为空" }
    }
    var obj = xlsx.parse(path);
    fs.unlink(path, e => {
      console.log("fail");
    });
    if (obj && obj.length > 0) {
      var data = obj[0].data;
      if (data && data.length > 1) {
        var tmlist = [];
        for (var i = 1; i < data.length; i++) {
          var d = data[i];
          if (d[0] && d[0] != "undefined" && d[1] && d[1] != "undefined") {
            var o = { ncl_type: d[0], tm_name: d[1] };
            tmlist.push(o);
          }
        }
        // var wresult = await this.writeXlsx(tmlist);
        // console.log(wresult);
        // var r = await this.uploadCtl.upfile(wresult.name,wresult.name);
        // fs.unlink(wresult.path,e=>{
        //   console.log("fail");
        // });
        // console.log(r.url);
        return { code: 1, data: tmlist };
      } else {
        return { code: -1, mag: "文件数据为空" }
      }
    } else {
      return { code: -2, mag: "文件解析失败" }
    }
  }
  async writeXlsx(excelObj) {
    var data = [];
    var arr = [["类别", "商标名称", "结果", "障碍备注"]];
    for (var i in excelObj) {
      var value = excelObj[i];
      var a = [];
      var tmnames = "";
      if (value.tmnames && value.tmnames.length > 0) {
        tmnames = value.tmnames.join(';');
      }
      a.push(value.ncl_type);
      a.push(value.tm_name);
      a.push(value.ratetext);
      a.push(tmnames);
      arr.push(a);
    }
    console.log(arr);
    var buffer = xlsx.build([
      {
        name: 'sheet1',
        data: arr
      }
    ]);
    var fileName = await this.getUidStr(12, 62);
    fileName = fileName + "_" + new Date().getTime().toString();
    //将文件内容插入新的文件中
    var a = await fs.writeFileSync('/tmp/' + fileName + '.xlsx', buffer, { 'flag': 'w' });
    return { path: '/tmp/' + fileName + '.xlsx', name: fileName + '.xlsx' };
  }
  //智能分析 bycquerytm.html
  async bycznfx(obj, req) {
    var url = obj.url;
    if (!url) {
      return { code: -1, mag: "文件地址为空" }
    }
    var srckey = url.split("aliyuncs.com/")[1];
    var tmresult = await this.readXlsx(srckey);
    if (tmresult && tmresult.code == 1) {
      var tmlist = tmresult.data;
      var rtmlist = await this.bytmsearch.tmncloneSearchs({ tmlist: tmlist });
      console.log(rtmlist);
      if (rtmlist && rtmlist.status == 0 && rtmlist.data) {
        var wresult = await this.writeXlsx(rtmlist.data);
        console.log(wresult);
        var r = await this.uploadCtl.upfile(wresult.name, wresult.name);
        fs.unlink(wresult.path, e => {
          console.log("fail");
        });
        console.log(r.url);
        return { code: 1, data: r };
      } else {
        return { code: -111, mag: "计算通过率失败" }
      }

    } else {
      return tmresult
    }
  }
  //文字转图片
  async word2pic(o, req) {
    var app = req.session.app;
    var fs = 180;
    if (o.word && o.word.length > 1) {
      fs = 480 / o.word.length;
    }
    var obj = {
      "word": o.word,
      "fs": fs,
      "bs": 500,
    };
    var url = settings.apiconfig.onLineMakeTMUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //图片彩色转黑白
  async toblack(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.toblackUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //调整商标图样宽高
  async adjustTMSize(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.adjustTMSizeUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //创建委托书
  async createWTS(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "url": o.url
    };
    var result = await this.imghandleApi.makeDeleForTM(obj);
    return result;
  }
  //图片转pdf
  async pic2pdf(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.bzLicenseForTMUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //调整委托书大小
  async adjustWTSSize(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.wtsUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //通过名字查询尼斯信息
  async getNclByLikeName(o, req) {
    var obj = {
      "name": o.name,
      "appKey": this.appKeyStr
    };
    var result = await this.gsbSearchApi.getNclByLikeName(obj);
    return result;
  }

  async getNcl(queryobj, req) {
    var that = this;
    var appkey = this.appKeyStr;
    var result = { rows: [], count: 0 };
    var sources = [];
    var nclcode = queryobj.nclcode;
    var data = {
      nclcode: nclcode,
      appKey: appkey,
    };
    var ncls = await this.gsbSearchApi.getNcl(data);
    var noCodeList = [];
    if (ncls.status == 0) {
      result.count = ncls.total;
      var d = ncls.data;
      for (var i = 0; i < d.length; i++) {
        var c = d[i];
        var source = { code: "", name: "", fullname: "", pcode: "", disabled: false };
        source.code = c.code;
        source.pcode = c.pid;
        source.name = c.name;
        source.fullname = !c.code || c.code == "undefined" ? c.name : (c.code + " " + c.name);
        if (c.level == 1) {
          source.type = 1;
        }
        if (!c.code || c.code == "undefined") {
          noCodeList.push(source);
        } else {
          sources.push(source);
        }
      }
      for (let index = 0; index < noCodeList.length; index++) {
        const element = noCodeList[index];
        if (element) {
          sources.push(element);
        }
      }
      result.rows = sources;
    }
    return System.getResult2(result, null);
  }
  async getCompanyInfoByLikeName(oo, o, req) {
    var appkey = this.appKeyStr;
    var data = {
      appKey: appkey,
      pagesize: 5,
      page: 0,
      companyName: o.likestr,
    };
    var company = await this.gsbIcSearchApi.companynamesearch(data);
    if (company.status == 0) {
      return { data: company.data.list };
    } else {
      return {};
    }

  }
  async getEntregistryByCompanyName(o, req) {
    var appkey = this.appKeyStr;
    var data = {
      appKey: appkey,
      pagesize: 1,
      page: 0,
      companyName: o.companyName,
    };
    var company = await this.gsbIcSearchApi.companynameonesearch(data);
    if (company.status == 0 && company.data.totalSize > 0) {
      return company.data.list[0];
    } else {
      return {};
    }

  }
  async getCropperPic(qobj, obj, req) {
    var that = this;
    var base64 = obj.base64;
    if (base64) {
      if (base64.indexOf(";base64,") > 0) {
        base64 = base64.split(";base64,")[1];
      }
      var img = base64;
      var uid = await this.getUidStr(6, 60);
      try {
        var fileName = "zc_cropper" + new Date().getTime() + uid + ".jpg";
        var filePath = '/tmp/' + fileName;
        var dataBuffer = new Buffer(img, 'base64');
        console.log(dataBuffer);
        var result = null;
        var r = await this.writeFile(filePath, dataBuffer);
        if (r == "success") {
          var result = await that.ossClient.upfile(fileName, filePath);
          fs.unlink(filePath, e => {
            console.log("fail");
          });
          return result.url;
        } else {
          return null;
        }

      } catch (e) {
        return null;
      }
    }
  }
  //标准商标图样上传（生成黑白商标，调整商标宽高 使其合规）
  async uploadStandardTm(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": this.appKeyStr,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.uploadStandardTmUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
  }
  //根据大类 名称查询尼斯
  async getNclByLikeNameAndNcl(qobj, o, req) {
    var obj = {
      "name": o.name,
      "appKey": this.appKeyStr,

    };
    if (o.ncls && o.ncls.length > 0) {
      obj["ncls"] = o.ncls;
    }
    var result = await this.gsbSearchApi.getNclByLikeName_new(obj);
    return result;
  }

  //生成企业监控报告
  async createMonitoringReport(obj){
    var mycompanyname = obj.companyname;
    var email = obj.email;
    if(!mycompanyname){
      return {code:-1,msg:"企业名称参数错误"};
    }
    mycompanyname= await this.getConvertSemiangleStr(mycompanyname);
    if(!email){
      return {code:-2,msg:"邮箱参数错误"};
    }
    var url = "http://43.247.184.92:8015/tmdoc/api/createdoc?mycompanyname="+encodeURIComponent(mycompanyname);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rc.execGet({}, url).then(rtn=>{
        var j = rtn.stdout;
        console.log("fanhui");
        console.log(j);
        if(j.indexOf("gsb-zc.oss-cn-beijing.aliyuncs.com")>=0){
          var text="企业监控报告";
          var html = '<a href="'+j+'">企业监控报告</a>'
          var result = this.mailClient.sendMsg(email, "企业监控报告", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
        }
      })
      return {code:1};
    } catch (e) {
      console.log(e);
      return {code:-200,msg:"操作失败"};
    }
  }



  //生成企业监控报告-h5
  async createMonitoringReportH5(obj){
    var key="create_tmrepotCache"
    if(!obj.companyname){
      return {code:-1,msg:"企业名称参数错误"};
    }
    if(!obj.email){
      return {code:-2,msg:"邮箱参数错误"};
    }
    obj.companyname= await this.getConvertSemiangleStr(obj.companyname);
    var source={
      companyname:obj.companyname,
      phonenum:obj.phonenum,
      email:obj.email,
      type:1
    }
    if(obj.entcode){
      var ent = await this.companySve.dao.model.findOne({where:{code:obj.entcode,isEnabled:1},raw:true});
      if(ent){
        source["channel_company_id"]=ent.id;
        if(obj.wxuser_id){
          source["wxuser_id"]=obj.wxuser_id;
        }
      }
    }
    logCtl.info({
      optitle: "生成企业监控报告-h5",
      op: "tooCtl/createMonitoringReportH5",
      content: JSON.stringify(obj)+"---------------"+JSON.stringify(source),
      clientIp: ""
    });
    var search={companyname:obj.companyname,status:1,type:1};
    var info=await this.pytmreportSve.findOne(search);
    if(info){
      var html = '<a href="'+info.filepath+'">企业监控报告</a>'
      var result = await this.mailClient.sendMsg(obj.email, "企业监控报告", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
      source.filepath=info.filepath;
      source.status=1;
      await this.pytmreportSve.create(source);
      return {code:1};
    }else{
      var result=await this.pytmreportSve.create(source);
      if(result){
      this.redisClient.rpush(key,result.id);
      }
      return {code:1};
    }
  }

//生成企业专利监控报告-h5
  async createPatentReportH5(obj){
    var key="create_patentrepotCache"
    if(!obj.companyname){
      return {code:-1,msg:"企业名称参数错误"};
    }
    if(!obj.email){
      return {code:-2,msg:"邮箱参数错误"};
    }
    obj.companyname= await this.getConvertSemiangleStr(obj.companyname);
    var source={
      companyname:obj.companyname,
      phonenum:obj.phonenum,
      email:obj.email,
      type:2
    }
    if(obj.entcode){
      var ent = await this.companySve.dao.model.findOne({where:{code:obj.entcode,isEnabled:1},raw:true});
      if(ent){
        source["channel_company_id"]=ent.id;
        if(obj.wxuser_id){
          source["wxuser_id"]=obj.wxuser_id;
        }
      }
    }
    logCtl.info({
      optitle: "生成企业专利监控报告-h5",
      op: "tooCtl/createPatentReportH5",
      content: JSON.stringify(obj)+"---------------"+JSON.stringify(source),
      clientIp: ""
    });
    var search={companyname:obj.companyname,status:1,type:2};
    var info=await this.pytmreportSve.findOne(search);
    if(info){
      var html = '<a href="'+info.filepath+'">企业专利监控报告</a>'
      var result = await this.mailClient.sendMsg(obj.email, "企业专利监控报告", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
      source.filepath=info.filepath;
      source.status=1;
      await this.pytmreportSve.create(source);
      return {code:1};
    }else{
      var result=await this.pytmreportSve.create(source);
      if(result){
      this.redisClient.rpush(key,result.id);
      }
      return {code:1};
    }
  }

  //获取渠道企业商标报告统计信息
  async getChannelMonitoringReportStatistic(obj){
    var entcode = obj.entcode;
    if(!entcode){
      return {code:-1,msg:"渠道码参数错误"};
    }
    try {
      var ent = await this.companySve.dao.model.findOne({where:{code:obj.entcode,isEnabled:1},raw:true});
      if(!ent && ent.id){
        return {code:-1,msg:"渠道公司不存在"};
      }
      // var datalist = await this.pytmreportSve.dao.model.findAll({
      //   where:{channel_company_id:ent.id},
      //   include: [{
      //     model: this.wxuserSve.dao.db.models.company,
      //     attributes: ["id", "openid", "nick_name", "head_img"],
      //     raw: true
      //   }],
      //   raw:true
      // });
      var sql = "SELECT tmreport.id AS tmreport_id, companyname, filepath, phonenum, email, channel_company_id, wxuser_id, openid, nick_name, head_img "+
      "FROM "+
      "( "+
      "SELECT id, companyname, filepath, phonenum, email, channel_company_id, wxuser_id FROM `py_tmreport` "+
      "WHERE deleted_at IS NULL AND channel_company_id IS NOT NULL and channel_company_id="+ent.id+
      " ) AS tmreport "+
      "LEFT JOIN ( "+
      "SELECT id, openid, nick_name, head_img FROM wx_user WHERE deleted_at IS NULL "+
      ") AS wxuser ON wxuser.id = tmreport.wxuser_id";
      var tmpResult = await this.pytmreportSve.dao.customQuery(sql);
      return {code:1,data:tmpResult};
    } catch (e) {
      return {code:-100,msg:"操作失败",err:e.stack};
    }


  }

  async getConvertSemiangleStr(str) {
    var result = "";
    var len = str.length;
    for (var i = 0; i < len; i++) {
      var cCode = str.charCodeAt(i);
      //全角与半角相差（除空格外）：65248（十进制）
      cCode = (cCode >= 0xFF01 && cCode <= 0xFF5E) ? (cCode - 65248) : cCode;
      //处理空格
      cCode = (cCode == 0x03000) ? 0x0020 : cCode;
      result += String.fromCharCode(cCode);
    }
    return result;
  }
}
module.exports = ToolCtl;



// var a=await this.createMonitoringReport({companyname:companyname});
