var System = require("../../system");
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
class calculatepriceCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(calculatepriceCtl));
    this.tradeSve = System.getObject("service.tradeSve");
    this.trademarkSve = System.getObject("service.trademarkSve");
    this.accountSve = System.getObject("service.accountSve");
    this.calcSve = System.getObject("service.calculatepriceSve");
    this.orderSve = System.getObject("service.orderSve");
    this.tmapplierinfoSve = System.getObject("service.tmapplierinfoSve");
    this.imghandleApi = System.getObject("api.imghandle");
    this.gsbSearchApi = System.getObject("api.gsbtmsearch");
    this.gsbIcSearchApi = System.getObject("api.gsbicsearch");
    this.companyApi = System.getObject("api.company");
    this.pconfigSve = System.getObject("service.pconfigSve");
    this.oplogSve = System.getObject("service.oplogSve");

  }
  async initNewInstance(queryobj, req) {
    return system.getResult2({}, null);
  }
  async hookOrder(qobj, obj) {
    console.log(obj);
    var result = await this.service.hookOrder(obj);
    return System.getResult2(result, null);
  }
  async word2pic(o, req) {
    console.log("qqqqqqqqqqqwwwwwwwwwwwwwwwwwwwwwwwweeeeeeeeeeeeeeeeee");
    console.log(req.session.user.account);
    var app = req.session.app || null;
    var fs = 180;
    if (o.word && o.word.length > 1) {
      fs = 480 / o.word.length;
    }
    var obj = {
      "appKey": app ? app.appid : "",
      "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": app ? app.appid : "",
      "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": app ? app.appid : "",
      "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": app ? app.appid : "",
      "url": o.url
    };
    var code = o.code;
    // var url = settings.apiconfig.makeDeleForTMUrl;
    // 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);
    // }

    var result = await this.imghandleApi.makeDeleForTM(obj);
    var calc = await this.service.findOneByCode(code);
    calc = calc.dataValues;
    if (calc.id != null) {
      calc.createAuthorizeStuff = result.data.url;
      var rd = await this.service.update(calc);
    }
    return result;
  }
  async createWTS2(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": app ? app.appid : "",
      "url": o.url
    };
    var result = await this.imghandleApi.makeDeleForTM(obj);
    return result;
  }
  async save(queryobj, obj, req) {
    var user = req.session.user;
    var type = obj.type;
    var form = obj.form || null;
    var ncl = obj.ncl;
    var nclOnes = "";
    if (!form) {
      return { status: -1, msg: "保存失败，表单信息为空" };
      return false;
    }
    if (!ncl || ncl.length < 1) {
      return { status: -1, msg: "尼斯选项不能为空，请选择商标小项" };
      return false;
    }
    //统计官费
    var nclTotalPublicExpense = ncl.length * 300;
    for (var i = 0; i < ncl.length; i++) {
      if (ncl[i]) {
        if (ncl[i].nclThree.length > 10) {
          nclTotalPublicExpense += (ncl[i].nclThree.length - 10) * 30;
        }//每一类多余的0项的
        if (i != (ncl.length - 1)) {
          nclOnes = nclOnes + ncl[i].code + ",";
        } else {
          nclOnes = nclOnes + ncl[i].code;
        }
      }
    }

    //税率
    var invoiceTaxRate = await this.pconfigSve.getConfigValue("invoiceTaxRate");
    //平台使用费
    var platformUseFee = await this.pconfigSve.getConfigValue("platformUseProfit");
    var totalPlatformCost = parseFloat(platformUseFee) * ncl.length;
    //税费
    var invoiceTaxes = parseFloat(form.totalSum) - parseFloat(form.totalSum / (1 + (invoiceTaxRate / 100)));
    invoiceTaxes = invoiceTaxes.toFixed(2);

    var nclServiceCharge = parseFloat(form.totalSum - totalPlatformCost - nclTotalPublicExpense - invoiceTaxes);
    nclServiceCharge = nclServiceCharge.toFixed(2);
    if (parseFloat(nclServiceCharge) < 0) {
      return { status: -1, msg: "提报金额不足，请重新输入" };
      return false;
    }

    form["nclOneCodes"] = nclOnes;
    var nclobj = { "ncl": ncl };
    form["nclSmallCodes"] = JSON.stringify(nclobj);
    if (type == "mynew") {
      if (req && req.session && req.session.app) {
        form.app_id = req.session.app.id;
        form["user_id"] = req.session.user.id;
      }
      form["orderNum"] = "";
      form["code"] = Math.round(Math.random() * 500) + "" + user.id + "" + new Date().getTime();
      var rd = await this.service.create(form);
      return System.getResult2(rd, null);
    } else {
      var tm = await this.trademarkSve.findOne({ nclCalc_id: form.id });
      if (tm != null) {
        return { status: -1, msg: "保存失败，该商标正在处理中，不可修改" };
      }
      if (req && req.session && req.session.app) {
        form.app_id = req.session.app.id;
      }
      form.tmFormType = form.tmFormType.toString();
      var rd = await this.service.update(form);
      return System.getResult2(rd, null);
    }
    return false;
  }
  async copy(obj, req) {
    var user = req.session.user;
    var id = obj.calcId;
    var form = await this.service.findById(id);
    form = form.dataValues;
    form.id = "";
    form.created_at = null;
    form.updated_at = null;
    if (req && req.session && req.session.app) {
      form.app_id = req.session.app.id;
      form["user_id"] = req.session.user.id;
    }
    form.orderNum = "";
    form.status = "1";
    form["createAuthorizeStuff"] = "";
    form["code"] = Math.round(Math.random() * 500) + "" + user.id + "" + new Date().getTime();

    var rd = await this.service.create(form);
    return System.getResult2(rd, null);
  }
  // 查询所有
  // 计算总价
  // 创建订单数据
  // 生成商标 订单号
  // 核价单订单号回写
  async createOrder(obj, req) {
    // var len=ids.length;
    var ids = obj.calcIds;
    var user = req.session.user;
    var app = req.session.app;
    try {
      var result = await this.calcSve.createOrder(ids, user, app);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }

  };
  async findByIds(ids) {
    var apps = await this.service.findByIds(ids);
    return System.getResult2(apps, null);
  }

  async aiadive(obj, pobj, req) {
    var nclinfo = await this.service.aiadive(obj);
    return System.getResult2(nclinfo, null);
  }

  async detailfindByIds(obj, pobj, req) {
    var loaduserid = req.session.user.id;
    var trademarksource = { "proxyCode": pobj.proxyCode };
    var trademark = await this.trademarkSve.findOne(trademarksource);
    var calcsource = { "id": trademark.nclCalc_id };
    var apps = await this.service.findOne(calcsource);
    var applier = await this.tmapplierinfoSve.findOneByOrderNum(trademark.orderNum);
    var tminfos = System.getResult2(apps, null);
    tminfos.tm = trademark;
    tminfos["isself"] = true;
    if (loaduserid == trademark.user_id) {
      tminfos.isself = false;
    }
    tminfos.nclOneCodes = trademark.nclOneCodes;
    tminfos.calcTypeName = applier.typeName;
    tminfos.trademarksealAuthorizeStuff = trademark.sealAuthorizeStuff;
    tminfos.applieridentityCardPic = applier.identityCardPic;
    tminfos.applierbusinessLicensePic = applier.businessLicensePic;
    return tminfos;
  }
  async findByCodes(obj, req) {
    var codes = obj.codes;
    var apps = await this.service.findByCodes(codes);
    var result = System.getResult2(apps, null);
    var order = {};
    var applier = {};
    var wts = [];
    if (apps.rows.length > 0) {
      var orderNum = apps.rows[0].dataValues.orderNum;
      if (orderNum != "" && orderNum != null) {
        order = await this.orderSve.findOneByOrderNum(orderNum);//订单
        if (order) {
          applier = await this.tmapplierinfoSve.findOneByOrderNum(order.dataValues.orderNum);
          wts = await this.trademarkSve.getSealAuthorizeStuffByOrderNum(order.dataValues.orderNum);
        }
      }
    }
    result.order = order;
    result.applier = applier;
    result.wts = wts;
    return result;
  }
  async findByOrderNum(obj, req) {
    var orderNum = obj.orderNum;
    var apps = await this.service.findByOrderNum(orderNum);
    return System.getResult2(apps, null);
  }
  async getCodesByOrderNum(obj, req) {
    try {
      var orderNum = obj.orderNum;

      var apps = await this.service.findByOrderNum(orderNum);
      var codes = "";
      var rows = apps.rows;
      for (var i = 0; i < rows.length; i++) {
        var data = rows[i].dataValues;
        if (i != (rows.length - 1)) {
          codes = codes + data.code + ","
        } else {
          codes = codes + data.code;
        }
      }
      return { code: "1", value: codes };
    } catch (e) {
      return { code: "-1", value: "" };
    }
  }
  async getNclByLikeName(o, req) {
    var appkey = req.session.app.appid;
    var obj = {
      "name": o.name,
      "appKey": appkey
    };
    var result = await this.gsbSearchApi.getNclByLikeName(obj);
    return result;
  }
  async getNclByLikeNameAndNcl(qobj, o, req) {
    var appkey = req.session.app.appid;
    var obj = {
      "name": o.name,
      "appKey": appkey,

    };
    if (o.ncls && o.ncls.length > 0) {
      obj["ncls"] = o.ncls;
    }
    var result = await this.gsbSearchApi.getNclByLikeName_new(obj);
    return result;
  }
  async getCompanyInfoByLikeName(oo, o, req) {
    var appkey = req.session.app.appid;
    var data = {
      appKey: appkey,
      pagesize: 5,
      page: 0,
      companyName: o.likestr,
    };
    var company = await this.gsbIcSearchApi.companynamesearch(data);
    if (company.status != 0 || company.data.list.length == 0) {
      this.oplogSve.createDb({
        logLevel: "info",
        optitle: "大叔据没有查询到的公司",
        op: "/fqboss/app/base/controller/impl/calculatepriceCtl.js/getCompanyInfoByLikeName",
        content: pobj.likestr,
        clientIp: ""
      });
      return {};
    }
    return { data: company.data.list };
  }

  async getEntregistryByCompanyName(o, req) {//查询企业注册信息
    var appkey = req.session.app.appid;
    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 calstatus(obj, pobj, req) {

    if (obj.id != 0) {
      var form2 = await this.service.findById(obj.id);
      form2 = form2.dataValues;
      if (form2.status != "1") {
        return { status: -1, msg: "该提报单已生成订单,尼斯类别不可操作" };
      }
    }
    else {
      return { status: 1, msg: "" };
    }
  }
  async updateiobpic(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": app.appid,
      "jpgpath": o.key
    };
    var flag = o.flag;
    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);
      var orderNum = o.orderNum;
      var fobj = { orderNum: orderNum };
      var tmapplierinfo = await this.tmapplierinfoSve.findOne(fobj);
      if (flag == 'sfz') {
        tmapplierinfo.identityCardPic = j.data.url;
      }
      if (flag == 'yyzz') {
        tmapplierinfo.businessLicensePic = j.data.url;
      }
      await this.tmapplierinfoSve.update(tmapplierinfo.dataValues);
      return System.getResult2({ code: 0, data: j.data.url }, null);
    } catch (e) {
      console.log(e);
      return System.getResult2({ code: -1, data: null }, null);
    }

  }

  async updateweituoshupic(o, req) {
    try {
      var result = await this.service.updateweituoshupic(o, req);
      return System.getResult2({ code: 1, data: result }, null);
    } catch (e) {
      return System.getResult2({ code: -1, data: null }, null);
    }
  }


}
module.exports = calculatepriceCtl;
