const system = require("../../system");
const ServiceBase = require("../sve.base");
const settings = require("../../../config/settings");
var moment = require('moment');
const claimAddHours = 72;//认领添加的时间（单位小时）=3天
const protectAddHours = 168;//保护添加的时间（单位小时）=7天
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
var xlsx = require('node-xlsx');
var fs = require("fs");
const logCtl = system.getObject("web.oplogCtl");
class TrademarktransactionService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(TrademarktransactionService));
    this.uploadCtl = system.getObject("web.uploadCtl");
    this.utilstmTransactionSve = system.getObject("service.utilstmTransactionSve");
  }
  //导出excel
  async writeXlsx(arrList) {
    var buffer = xlsx.build([
      {
        name: 'sheet1',
        data: arrList
      }
    ]);
    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' };
    var r = await this.uploadCtl.upfile(fileName + '.xlsx',fileName + '.xlsx');
    fs.unlink('/tmp/' + fileName + '.xlsx', e => {
      console.log("fail");
    });
    console.log(r.url);
    return r.url;
  }
  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('');
  }
  //excel批量导入创建
  async excelCreate(dataList,user){
    var objList=[];
    var errList = [];
    if(!user){
      return {code:-1,msg:"user数据为空"};
    }
    if(dataList.length<0){
      return {code:-2,msg:"数据为空"};
    }
    var columnList = dataList[0];//列名数组
    var sbmcIndex=0;//商标名称列的下标 解决文件列变换导致传入商标出错问题
    var sqhIndex=1; //申请号下标
    var mjsjIndex=2;//卖家售价下标
    var mjxmIndex=3;//卖家姓名下标
    var mjdhIndex=4;//卖家电话下标
    if(!columnList || !columnList[0] || !columnList[1] || !columnList[2] || !columnList[3] || !columnList[4]){//无列名 或 列名缺失
      return {code:-3,msg:"上传文件列名与模板文件不一致"};
    }
    var errorColumnList = dataList[0];//列名数组
    errorColumnList.push("备注");
    errList.push(columnList);
    for(var i=0;i<5;i++){//校验列名 各个列的下标重新赋值
      var column = columnList[i];
      column=column.trim();//去掉前后空格
      column=column.substring(0,3);//取前四位
      if(column=="商标名"){
        sbmcIndex=i;
      }else if(column=="申请号"){
        sqhIndex=i;
      }else if(column=="卖家售"){
        mjsjIndex=i;
      }else if(column=="卖家姓"){
        mjxmIndex=i;
      }else if(column=="卖家电"){
        mjdhIndex=i;
      }else{
        return {code:-3,msg:"上传文件列名与模板文件不一致"};
      }
    }
    var codeList=[];//待插入的商标号数组
    var dataList2 = [];
    for(var i=1;i<dataList.length;i++){//判断清除重复数据，提取商标号 用于商标查重
      if(dataList[i][sqhIndex]){
        var codeString=dataList[i][sqhIndex].toString();
        if(codeList.indexOf(codeString)>=0){
          //重复商标
        }else{
          dataList2.push(dataList[i]);
          codeList.push(codeString);
        }
      }
    }
    dataList=dataList2;
    console.log(dataList.length);
    if(dataList.length>2000){//一次最多上传1000个商标 多余部分不做处理
      dataList = dataList.slice(0,2000);
    }
    console.log(dataList.length);
    var tmtcodes=[];//重复的已存在的商标号数组
    //查询商标数据
    var tmts = await this.dao.model.findAll({
      where:{code:{ [this.dao.db.Op.in]: codeList }},
      attributes: ["code"],
      raw:true
    });
    for(var i=0;i<tmts.length;i++){
      tmtcodes.push(tmts[i].code);
    }
    for(var i=0;i<dataList.length;i++){
      var d = dataList[i];
      if (d) {
        if(!d[0]&&!d[1]&&!d[2]&&!d[3]&&!d[4]){
          //空行 不予处理
        }else if(!(d[0]&&d[1]&&d[2]&&d[3]&&d[4])){
          d[5]="";
          if(!d[sbmcIndex]){
            d[5]=d[5]+"商标名称不能为空;";
          }
           if(!d[sqhIndex]){
            d[5]=d[5]+"申请号不能为空;";
          }
           if(!d[mjsjIndex]){
            d[5]=d[5]+"卖家售价不能为空;";
          }
           if(!d[mjxmIndex]){
            d[5]=d[5]+"卖家姓名不能为空;";
          }
           if(!d[mjdhIndex]){
            d[5]=d[5]+"卖家电话不能为空;";
          }
          errList.push(d);
        }else{
          var platform_quoted_price = Number(d[mjsjIndex])*1.2+1000;
          platform_quoted_price = platform_quoted_price.toFixed(2);
          // var sbmcIndex;//商标名称列的下标 解决文件列变换导致传入商标出错问题
          // var sqhIndex; //申请号下标
          // var mjsjIndex;//卖家售价下标
          // var mjxmIndex;//卖家姓名下标
          // var mjdhIndex;//卖家电话下标
          var obj = { excelName:d[sbmcIndex],trademark_type:"ordinary",
            name: d[sbmcIndex], code: d[sqhIndex],business_quoted_price:d[mjsjIndex],contacts:d[mjxmIndex],mobile:d[mjdhIndex],
            createcompany_id:user.company_id,createuser_id:user.id,platform_quoted_price:platform_quoted_price,
            publish_status:"audit"
          };
          var tmcode = d[sqhIndex]?d[sqhIndex].toString():"";
          if(tmtcodes && tmtcodes.length>0 && tmtcodes.indexOf(tmcode)>=0){
            d[5]="该商标已存在";
            errList.push(d);
          }else{
            objList.push(obj);
          }
        }
      }
    }
    var data = null;
    var exportExcelUrl = null;
    var successCount = 0;
    var errorCount = 0;
    if(errList && errList.length>1){
      exportExcelUrl = await this.writeXlsx(errList);
      errorCount = errList.length-1;
    }
    if(objList.length>0){
      data = await this.dao.model.bulkCreate(objList,{});
      console.log(data);
      if(data && data.length>0){
        successCount = data.length;
      }
    }
    return {code:1,exportExcelUrl:exportExcelUrl,sum:dataList.length,successCount:successCount,errorCount:errorCount};
    
  }

  //es插入后 回写商标数据
  async updataFromEs(obj){
    if(!obj.code){
      return {code:-1,msg:"code参数错误"};
    }
    if(!obj.ncloneList || obj.ncloneList.length<1){
      return {code:-2,msg:"ncloneList参数错误"};
    }
    if(!obj.user_id){
      return {code:-3,msg:"user_id参数错误"};
    }
    if(!obj.company_id){
      return {code:-4,msg:"company_id参数错误"};
    }
    var tmt = await this.dao.model.findOne({where:{code:obj.code,createuser_id:obj.user_id,createcompany_id:obj.company_id},raw:true});
    if(!tmt){
      return {code:-5,msg:"商标数据不存在"};
    }
    if(!obj.tm_applier){
      return {code:-6,msg:"tm_applier参数错误"};
    }
    if(!obj.pic_url){
      return {code:-7,msg:"pic_url参数错误"};
    }
    if(!obj.tm_status_name){
      return {code:-8,msg:"tm_status_name参数错误"};
    }
    if(!obj.publish_status){
      return {code:-9,msg:"publish_status参数错误"};
    }
    if(!obj.tm_group){
      return {code:-10,msg:"tm_group参数错误"};
    }
    if(!obj.tm_service_item){
      return {code:-11,msg:"tm_service_item参数错误"};
    }
    if(!obj.tm_introduction){
      return {code:-12,msg:"tm_introduction参数错误"};
    }
    if(!obj.tm_start_day){
      return {code:-13,msg:"tm_start_day参数错误"};
    }
    if(!obj.tm_end_day){
      return {code:-14,msg:"tm_end_day参数错误"};
    }
    if(!obj.op_notes){
      return {code:-15,msg:"op_notes参数错误"};
    }
    var nclOnes = ncloneList.join(",");
    obj["ncl_one_code"]=nclOnes;
    await this.dao.model.update(obj, { where: { id: tmt.id }});
    return {code:1}
  }

  //
  async updateTm(obj){
    var user = obj.user;
    var pic_url = obj.pic_url;
    var contacts = obj.contacts;
    var mobile = obj.mobile;
    var business_quoted_price = obj.business_quoted_price;
    var platform_quoted_price = obj.platform_quoted_price;
    var tm_introduction = obj.tm_introduction;
    var code = obj.code;
    if(!code){
      return {code:-1,msg:"code参数错误"};
    }
    // if(!pic_url){
    //   return {code:-3,msg:"pic_url参数错误"};
    // }
    if(!contacts){
      return {code:-4,msg:"contacts参数错误"};
    }
    if(!mobile){
      return {code:-5,msg:"mobile参数错误"};
    }
    if(!business_quoted_price){
      return {code:-6,msg:"business_quoted_price参数错误"};
    }
   //createuser_id:user.id,
    var tmts = await this.dao.model.findAll({where:{code:code,createcompany_id:user.company_id},raw:true});
   
    if(!tmts || tmts.length<1){
      return {code:-2,msg:"商标数据不存在"};
    }
    var tmt = tmts[0];
    var updateObj = {code:code};
    if(pic_url){
      updateObj["pic_url"]=pic_url;
    }
    if(contacts){
      updateObj["contacts"]=contacts;
    }
    if(mobile){
      updateObj["mobile"]=mobile;
    }
    if(business_quoted_price){
      updateObj["business_quoted_price"]=business_quoted_price;
      var price = Number(business_quoted_price)*1.2+1000;
      price = price.toFixed(2);
      updateObj["platform_quoted_price"]=price;

    }
    // if(tm_introduction){
    //   updateObj["tm_introduction"]=tm_introduction;
    // }
    updateObj["tm_introduction"]=tm_introduction || "";
    if(tmt.publish_status!="audit" && tmt.publish_status!="fail"){
      var esupdateobj={
        sbzch:code,
        platform_quoted_price:updateObj.platform_quoted_price,
        tm_introduction:tm_introduction,
        is_transaction:tmt.publish_status=="uppershelf"?"1":"0",
        pic_url_user:pic_url
      }
      var rc=system.getObject("util.execClient");
      var esResult = await this.utilstmTransactionSve.tmTransactionUpdatesve(esupdateobj,rc);
      if(esResult.status!=0){
        var esupdateobj2={
          sbzch:code,
          platform_quoted_price:tmt.platform_quoted_price,
          tm_introduction:tmt.tm_introduction,
          is_transaction:tmt.publish_status=="uppershelf"?"1":"0",
          pic_url_user:tmt.pic_url
        }
        var esResult2 = await this.utilstmTransactionSve.tmTransactionUpdatesve(esupdateobj2,rc);
        return {code:-5,msg:"操作失败"}; 
      }
    }
    var that=this;
    return this.db.transaction(async function (t) {
      for(var i=0;i<tmts.length;i++){
        await that.dao.model.update(updateObj,{where:{id:tmts[i].id}, transaction: t });
      }
      return {code:1};
    })
  }
  //修改发布状态
  async updatePublishStatus(obj){//codeList:商标号列表，type:1上架 2下架
    var codeList=obj.codeList;
    var type = obj.type;
    var user = obj.user;
    if(!codeList || codeList.length<1){
      return {code:-1,msg:"code参数错误"};
    }
    if(!type){
      return {code:-2,msg:"type参数错误"};
    }
    var tmts = await this.dao.model.findAll({where:{code:{ [this.dao.db.Op.in]: codeList },createuser_id:user.id,createcompany_id:user.company_id},raw:true});
    if(!tmts || tmts.length<1){
      return {code:-3,msg:"该商标不存在"};
    }
    // "tm_transaction_publish_status":{"audit":"审核中","fail":"审核不通过","success":"审核通过","uppershelf":"上架","lowershelf":"下架"}//商标交易发布状态
    for(var i=0;i<tmts.length;i++){
      var status = tmts[i].publish_status;
      if( status=="audit" || status=="fail" ){
        return {code:-4,msg:"操作失败，存在"+tmts[i].publish_status_name+"状态的商标"};
      }
    }
    for(var i=0;i<tmts.length;i++){
      var esupdateobj={
        sbzch:tmts[i].code,
        platform_quoted_price:tmts[i].platform_quoted_price,
        tm_introduction:tmts[i].tm_introduction,
        is_transaction:type=="1"?"1":"0",
        pic_url_user:tmts[i].pic_url
      }
      var rc=system.getObject("util.execClient");
      var esResult = await this.utilstmTransactionSve.tmTransactionUpdatesve(esupdateobj,rc);
      if(esResult.status!=0){
        for(var j=0;j<i;j++){
          var esupdateobj2={
            sbzch:tmts[j].code,
            platform_quoted_price:tmts[j].platform_quoted_price,
            tm_introduction:tmts[j].tm_introduction,
            is_transaction:tmts[j].publish_status=="uppershelf"?"1":"0",
            pic_url_user:tmts[j].pic_url
          }
          var esResult2 = await this.utilstmTransactionSve.tmTransactionUpdatesve(esupdateobj2,rc);
        }
        logCtl.info({
          optitle: "查看商标交易修改接口错误-info",
          op: "/base/service/impl/trademarktransactionSve.js/updatePublishStatus",
          content: JSON.stringify(esResult) ,
          clientIp: ""
        });
        return {code:-5,msg:"操作失败"}; 
      }
    }
    var that=this;
    return this.db.transaction(async function (t) {
      for(var i=0;i<tmts.length;i++){
        var status = tmts[i].publish_status;
        if( status!="audit" && status!="fail" ){
          if(type==1){
            that.dao.model.update({publish_status:"uppershelf"}, { where: { id: tmts[i].id }, transaction: t });
          }
          if(type==2){
            that.dao.model.update({publish_status:"lowershelf"}, { where: { id: tmts[i].id }, transaction: t });
          }
        }
      }
      return {code:1,msg:"操作成功"};
    })
  }

  //发布申请人商标 -- 目前用于 商标交易》》企业发布交易商标
  async publishApplierTm(obj){
    var user = obj.user;
    var contacts = obj.contacts;//联系人
    var mobile = obj.mobile;//联系电话
    var dataList = obj.tms;
    if(!contacts){
      return {code:-1,msg:"contacts参数错误"};
    }
    if(!mobile){
      return {code:-2,msg:"mobile参数错误"};
    }
    if(!dataList || dataList.length<1){
      return {code:-3,msg:"dataList参数错误"};
    }
    var resultList=[["商标图样","商标名称","申请号","类别","法律状态","申请人","发布价格","商标简介","备注"]];
    var objList=[];
    var data = null;
    var exportExcelUrl = null;
    var successCount = 0;
    var errorCount = 0;
    for(var i=0;i<dataList.length;i++){
      var d = dataList[i];
      var result=[d.pic_url,d.tm_name,d.tm_regist_num,d.ncl_one_codes,d.status,"",d.price,d.desc];
      var tmt = await this.dao.model.findOne({where:{code:d.tm_regist_num},raw:true});
      if(!d.price){
        result[8]="该商标价格为空";
        errorCount=errorCount+1;
      }else if(tmt){
        result[8]="该商标已存在";
        errorCount=errorCount+1;
      }else{
        result[8]="发布成功";
        var platform_quoted_price = Number(d.price)*1.2+1000;
        platform_quoted_price = platform_quoted_price.toFixed(2);
        var obj = {trademark_type:"ordinary",
          name: d.tm_name, code: d.tm_regist_num,business_quoted_price:d.price,contacts:contacts,mobile:mobile,
          createcompany_id:user.company_id,createuser_id:user.id,platform_quoted_price:platform_quoted_price,
          publish_status:"audit",pic_url:d.pic_url,tm_introduction:d.desc
        };
        objList.push(obj);
      }
      resultList.push(result);
    }

    if(resultList && resultList.length>1){
      exportExcelUrl = await this.writeXlsx(resultList);
    }
    if(objList.length>0){
      data = await this.dao.model.bulkCreate(objList,{});
      console.log(data);
      if(data && data.length>0){
        successCount = data.length;
      }
    }
    return {code:1,exportExcelUrl:exportExcelUrl,sum:dataList.length,successCount:successCount,errorCount:errorCount};
    
    
    


  }
  //修改交易商标类型
  async editTmtsType(obj){
    var user = obj.user;
    var ids = obj.ids;
    var type = obj.type;
    if(!ids || ids.length<1){
      return {code:-1,msg:"ids参数错误"};
    }
    if(!type){
      return {code:-2,msg:"type参数错误"};
    }
    if(type && type!="ordinary"){//非普通商标
      var tmtypeobj= {"ordinary":"普通商标","specialoffer":"特价商标","highquality":"精品商标","hot":"热门商标","recommended":"推荐商标"};
      var tmts = await this.dao.model.findAll({where:{trademark_type:type,createcompany_id:user.company_id},raw:true});
      if(tmts){
         var len = ids.length+tmts.length;
         if(len>20){
           var typename = tmtypeobj[type];
           return {code:-3,msg:"操作失败，该类型的商标超过20个"};
         }
      }
    }
    var that=this;
    return this.db.transaction(async function (t) {
      var obj={trademark_type:type,updateuser_id:user.id};
      await that.dao.model.update(obj,{where:{id:{ [that.dao.db.Op.in]: ids },createcompany_id:user.company_id},transaction: t});
      return {code:1};
    })

  }
  //获取某类型的交易商标
  async findByTmType(obj){
    var type = obj.type;
    var company_id = obj.company_id;
    if(!company_id){
      return {code:-1,msg:"company_id参数错误"};
    }
    if(!type){
      return {code:-2,msg:"type参数错误"};
    }
    var othertmts=[];
    var tmts = await this.dao.model.findAll({
      where:{trademark_type:type,createcompany_id:company_id,publish_status:"uppershelf"},
      attributes: ["id", "code", "name", "platform_quoted_price", "pic_url", "ncl_one_code"],
      limit:20,
      offset:0,
      raw:true
    });
    if(!tmts || tmts.length<20){
      var limit=20-tmts.length;
      othertmts=await this.dao.model.findAll({
        where:{
          trademark_type:type,publish_status:"uppershelf",
          createcompany_id:{
             [this.dao.db.Op.ne]: company_id 
          }
        },
        attributes: ["id", "code", "name", "platform_quoted_price", "pic_url", "ncl_one_code"],
        limit:limit,
        offset:0,
        raw:true
      });
      if(othertmts && othertmts.length>0){
        tmts.push.apply(tmts,othertmts);
      }
    }
    return {code:1,data:tmts};
  }

  //获取推荐交易商标（热门，推荐，特价，精品 ）
  async findAllRecommendTm(obj){
    var company_id = obj.company_id;
    if(!company_id){
      return {code:-1,msg:"company_id参数错误"};
    }
    var othertmts=[];
    // "specialoffer": "特价商标", "highquality": "精品商标", "hot": "热门商标", "recommended": "推荐商标"
    var tmts = await this.dao.model.findAll({
      where:{
        [this.db.Op.or]: [{ trademark_type: "specialoffer" }, { trademark_type: "highquality"},{ trademark_type: "hot"}, { trademark_type: "recommended"}],
        createcompany_id:company_id,
        publish_status:"uppershelf"},
      attributes: ["id", "code", "name", "platform_quoted_price", "pic_url", "ncl_one_code"],
      limit:40,
      offset:0,
      raw:true
    });
    if(!tmts || tmts.length<40){
      var limit=40-tmts.length;
      othertmts=await this.dao.model.findAll({
        where:{
          [this.db.Op.or]: [{ trademark_type: "specialoffer" }, { trademark_type: "highquality"},{ trademark_type: "hot"}, { trademark_type: "recommended"}],
          publish_status:"uppershelf",
          createcompany_id:{
             [this.dao.db.Op.ne]: company_id 
          }
        },
        attributes: ["id", "code", "name", "platform_quoted_price", "pic_url", "ncl_one_code"],
        limit:limit,
        offset:0,
        raw:true
      });
      if(othertmts && othertmts.length>0){
        tmts.push.apply(tmts,othertmts);
      }
    }
    return {code:1,data:tmts};
  }
}
module.exports = TrademarktransactionService;
// var test = new TrademarktransactionService();
// test.findAllRecommendTm({company_id:4}).then(function(d){
//   console.log("#################################");
//   console.log(d);
//   console.log(d.data.length);
// })
