var system = require("../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const logCtl = system.getObject("web.oplogCtl");
var xlsx = require('node-xlsx');
var fs = require("fs");
class TrademarktransactionCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(TrademarktransactionCtl));
    this.uploadCtl = system.getObject("web.uploadCtl");
    this.utilstmTransactionSve = system.getObject("service.utilstmTransactionSve");
    this.GsbByTmSearchApi=system.getObject("api.bytmsearch");
    this.utilstmSve=system.getObject("service.utilstmSve");
    this.tm_status={1:"申请中",2:"已初审",3:"已注册",4:"已无效",5:"其他"};
    this.companyS = system.getObject("service.companySve");
    this.tm_gjfl={1:"01类 化学原料",2:"02类 颜料油漆",3:"03类 日化用品",4:"04类 燃料油脂",5:"05类 医药",6:"06类 金属材料",7:"07类 机械设备",8:"08类 手工器械",9:"09类 科学仪器",
                  10:"10类 医疗器械",11:"11类 灯具空调",12:"12类 运输工具",13:"13类 军火烟火",14:"14类 珠宝钟表",15:"15类 乐器",16:"16类 办公用品",17:"17类 橡胶制品",18:"18类 皮革皮具",19:"19类 建筑材料",20:"20类 家具",21:"21类 厨房洁具",22:"22类 绳网袋蓬",23:"23类 纱线丝",24:"24类 布料床单",
                  25:"25类 服装鞋帽",26:"26类 钮扣拉链",27:"27类 地毯席垫",28:"28类 健身器材",29:"29类 食品",30:"30类 方便食品",31:"31类 农林生鲜",32:"32类 啤酒饮料",33:"33类 酒",34:"34类 烟草烟具",35:"35类 广告销售",36:"36类 金融物管",37:"37类 建筑修理",38:"38类 通讯服务",
                  39:"39类 运输贮藏",40:"40类 材料加工",41:"41类 教育娱乐",42:"42类 科技服务",43:"43类 餐饮住宿",44:"44类 医疗园艺",45:"45类 社会服务"};
  }
  convertDate(time){
     if(time==null){
       return "";
     }
     var date =  new Date(Number(time*1000));
     var y = 1900+date.getYear();
     var m = "0"+(date.getMonth()+1);
     var d = "0"+date.getDate();
     return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
  }
  async findAndCountAll(queryobj, obj, req) {
    obj.codepath = req.codepath;
    if (req.session.user) {
      obj.uid = req.session.user.id;
    }
    if (req.codepath.indexOf("pmg") < 0 && req.companyid && req.companyid != "" && obj.search) {
      obj.search.createcompany_id = req.companyid;
      // if(obj.uid){
      //   obj.search.createuser_id = obj.uid;
      // }
    }
    var apps = await this.service.findAndCountAll(obj);
    if(apps && apps.results && apps.results.rows.length>0){
      var tmts = apps.results.rows;
      for(var i=0;i<tmts.length;i++){
        var tmt = tmts[i];
        var data2={
          reg_num:tmt.code,
          nclone_code:tmt.ncl_one_code
        }
        var qunzutms=await this.utilstmSve.getGroupNclInfo(data2);
        var spfwxmlist=[];
        var codelist=[];
        if(qunzutms.status==0){
          var exist = qunzutms.data.exist;
          for(var j=0;j<exist.length;j++){
            var c = exist[j];
            if(spfwxmlist.findIndex(f => f == c.small_name) < 0){
              spfwxmlist.push(c.small_name)
            }
            if(codelist.findIndex(f => f ==c.code)<0){
              codelist.push(c.code)
            }
          }
        }
        var spfwxm=spfwxmlist.join(",");
        var codes=codelist.join(",");
        tmt.spfwxm=spfwxm;
        tmt.codes=codes;
        if(tmt.dataValues){
          tmt.dataValues.spfwxm=spfwxm;
          tmt.dataValues.codes=codes;
        }
      }
    }
    
    return system.getResult2(apps, null);
  }
  //读取excel
  async readXlsx(srckey) {
    var path = await this.uploadCtl.downfile(srckey);
    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) {
        return { code: 1, data: data };
      } else {
        return { code: -1, mag: "文件数据为空" }
      }
    } else {
      return { code: -2, mag: "文件解析失败" }
    }
  }

//excel批量导入创建
  async excelCreate(pobj,obj,req){
    var user = req.session.user;
    var srckey = obj.srckey;
    if(!srckey){
      return {code:-2,msg:"srckey参数错误"};
    }
    if(!user){
      return {code:-1,msg:"用户数据为空"};
    }
    try {
      var d = await this.readXlsx(srckey);
      if(!d || d.code!=1 || !d.data){
        return {code:-3,msg:"解析文件失败"}
      }
      // var data = d.data;
      // return d;
      var res = await this.service.excelCreate(d.data,user);

      return res
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }
  }
  //注册号获取商标详情
  async getDetailByCode(obj,req){
    var code = obj.code;
    // var user_id = obj.user_id;
    // var company_id = obj.company_id;
    var user = req.session.user;
    if(!code){
      return {code:-1,msg:"code参数错误"};
    }
    if(!user){
      return {code:-3,msg:"用户数据为空"};
    }
    // if(!user_id){
    //   return {code:-1,msg:"user_id参数错误"};
    // }
    // if(!company_id){
    //   return {code:-1,msg:"company_id参数错误"};
    // }
    try {
      var data = null;
      if(obj.ncl_one_code){//createuser_id:user.id,
        data = await this.service.dao.model.findOne({where:{ncl_one_code:obj.ncl_one_code,code:code,createcompany_id:user.company_id},raw:true});
      }else{//createuser_id:user.id,
        data = await this.service.dao.model.findOne({where:{code:code,createcompany_id:user.company_id},raw:true});
      }
      if(data){
        return {code:1,data:data}
      }else{
        return {code:-2,msg:"该商标不存在"};
      }
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }

  }
  //id获取商标详情
  async getDetailById(obj,req){
    var id = obj.id;
    // var user_id = obj.user_id;
    // var company_id = obj.company_id;
    var user = req.session.user;
    if(!id){
      return {code:-1,msg:"id参数错误"};
    }
    if(!user){
      return {code:-3,msg:"用户数据为空"};
    }
    try {
      var data = await this.service.dao.model.findOne({where:{id:id},raw:true});
      if(data){
        return {code:1,data:data}
      }else{
        return {code:-2,msg:"该商标不存在"};
      }
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }

  }
  //修改交易商标
  async updateTm(pobj,obj,req){
    var user = req.session.user;
    if(!user){
      return {code:-100,msg:"用户数据为空"};
    }
    obj["user"]=user;
    try {
      return this.service.updateTm(obj);
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }
  }
  //商标交易检索
  async tmTransactionSearch(query,obj){
      console.log("----------------------");
      console.log(obj);
      var result={rows:[],total:""};
      var sources=[];
      var codes=[];
      var keyword=obj.keyword;
      var tm_nclcode=obj.tm_nclcode;
      var price_min = obj.min;
      var price_max = obj.max;
      var tm_structure=obj.tm_structure;
      if(obj.tm_word == '1-2个字'){
        var tm_word = 2;
      }else if(obj.tm_word == '3个字'){
        var tm_word = 3;
      }else if(obj.tm_word == '4个字'){
        var tm_word = 4;
      }else if(obj.tm_word == '5个字'){
        var tm_word = 5;
      }else if(obj.tm_word == '5个字以上'){
        var tm_word = 6;
      }else{
        var tm_word ='';
      }
      var order_field='';
      if(obj.order == "价格"){
        order_field= "platform_quoted_price";
      }else if(obj.order == "时间"){
        order_field= "created_at";
      }
      var sort = obj.sort;
      var pagesize=obj.pagesize;
      var currentpage=obj.currentpage;
      var data={
        keyword:keyword,
        tm_nclcode:tm_nclcode,
        price_min:price_min,
        price_max:price_max,
        tm_structure:tm_structure,
        tm_word:tm_word,
        order_field:order_field,
        sort:sort,
        pagesize:pagesize,
        currentpage:currentpage
      };
      console.log("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzjjjjjjjjjjjjjjjjjj");
      console.log(data);
      var that = this;
      var tms =await this.utilstmTransactionSve.tmTransactionSearch(data);//获取查询结果
      // console.log(tms);
      if(tms.status==0){
        result.total=tms.total;
        tms.data.forEach(function(tm){
          var source={
               tm_name:tm.tm_name,//商标名称
               platform_quoted_price:tm.platform_quoted_price,//平台售价
               ncl_one_codes:tm.ncl_one_codes,//尼斯大类
               ncl_one_codes_name:that.tm_gjfl[tm.ncl_one_codes],//国际分类名称
               tm_regist_num:tm.tm_regist_num,//注册号
               pic_url:tm.pic_url,                          //图片url
               pic_url_user:tm.pic_url_user                //用户自己上传的图片url
             }
            sources.push(source)
        });
        result.rows=sources;
      }
      console.log("=====================+++++++++++++++++++++++++");
      // console.log(result);
      return system.getResult2(result,null);
  }
  //通过注册号查询，返回一个list
  async tmRegistSearch(obj){
    var result={rows:[]};
    var registNum=obj.registNum;
    var obj={
      registNum:registNum
    }
    var that = this;
    console.log(obj);
    var tms =await this.utilstmTransactionSve.tmRegistSearchsve(obj);//获取查询结果
    var sources=[]
    if(tms.status == 0){
      result.count=tms.total;
      for (var i = 0; i < tms.data.length; i++) {
        var tm =tms.data[i];
        var sbzch=tm.tm_regist_num;
        var gjfl=tm.ncl_one_codes;
        var data={
          reg_num:sbzch,
          nclone_code:gjfl
        }
        console.log(data);
        var qunzutms=await this.utilstmSve.getGroupNclInfo(data);
        console.log(qunzutms);
        var spfwxmlist=[]
        if(qunzutms.status==0){
          spfwxmlist=qunzutms.data.exist;
          // qunzutms.data.exist.forEach(function(c){
          //   console.log(c);
          //   if(spfwxmlist.findIndex(f => f == c.small_name) < 0){
          //     spfwxmlist.push(c.small_name)
          //   }
          // });
        }
        var source={
             sbmc:tm.tm_name,//商标名称
             gjfl:tm.ncl_one_codes,//国际分类
             gjflname:that.tm_gjfl[tm.ncl_one_codes],//国际分类名称
             sbzch:tm.tm_regist_num,//商标注册号
             sbzt:that.tm_status[tm.status],//商标状态
             sqrq:that.convertDate(tm.apply_day),//申请日期
             csrq:that.convertDate(tm.first_notice_day),//初审日期
             zcrq:that.convertDate(tm.original_regist_notice_day),//注册日期
             zcr:tm.applicant_cn,//申请人
             jzrq:that.convertDate(tm.tm_end_day) ,//截止日期
             yzcr:tm.original_applicant_cn,//原申请人
             zcdz:tm.applicant_cn_addr,//申请地址
             dljg:tm.tm_agency,//代理机构
             spfwxmlist:spfwxmlist,
             logo:tm.pic_url,//商标图样
        };
        sources.push(source);
      }
      result.rows=sources;
    };
    return system.getResult2(result,null);
  }
  //商标号和国际分类号查询
  async tmRegistGjflSearch(obj){
    console.log(obj);
    var result={rows:[]};
    var sbzch=obj.sbzch;
    var gjfl=obj.gjfl;
    var sources=[];
    var data={
      sbzch:sbzch,
      gjfl:gjfl,
    };
    var that = this;
    var detailtms= await this.GsbByTmSearchApi.tradeMarkDetailapi(data);
    var data2={
      reg_num:sbzch,
      nclone_code:gjfl
    }
    var qunzutms=await this.utilstmSve.getGroupNclInfo(data2);
    var spfwxmlist=[]
    if(qunzutms.status==0){
      spfwxmlist=qunzutms.data.exist;
      // qunzutms.data.exist.forEach(function(c){
      //   if(spfwxmlist.findIndex(f => f == c.small_name) < 0){
      //     spfwxmlist.push(c.small_name)
      //   }
      // });
    }
    if(detailtms.status == 0 && detailtms.data.length>0){
      var tm=detailtms.data[0];
      var source={
        sbmc:tm.tm_name,//商标名称
        gjfl:tm.ncl_one_codes,//国际分类
        gjflname:that.tm_gjfl[tm.ncl_one_codes],//国际分类名称
        sbzch:tm.tm_regist_num,//商标注册号
        sbzt:that.tm_status[tm.status],//商标状态
        sqrq:that.convertDate(tm.apply_day),//申请日期
        csrq:that.convertDate(tm.first_notice_day),//初审日期
        zcrq:that.convertDate(tm.original_regist_notice_day),//注册日期
        zcr:tm.applicant_cn,//申请人
        jzrq:that.convertDate(tm.tm_end_day) ,//截止日期
        yzcr:tm.original_applicant_cn,//原申请人
        zcdz:tm.applicant_cn_addr,//申请地址
        dljg:tm.tm_agency,//代理机构
        spfwxmlist:spfwxmlist,
        logo:tm.pic_url,//商标图样
      };
      sources.push(source);
    }
    result.rows=sources;
    return system.getResult2(result,null);
  }

  async tmTransactionDetail(query,obj){//商标交易详情接口
    console.log(obj);
    var result={detail:{}};
    var sbzch=obj.sbzch;
    var gjfl=obj.gjfl;
    var data={
      sbzch:sbzch,
      gjfl:gjfl,
    };
    var that = this;
    var detailtms= await this.GsbByTmSearchApi.tradeMarkDetailapi(data);
    var ts= await this.utilstmTransactionSve.tmTransactionDetailsve(data);//获取查询结果
    var data2={
      reg_num:sbzch,
      nclone_code:gjfl
    }
    var qunzutms=await this.utilstmSve.getGroupNclInfo(data2);
    var spfwxmlist=[];
    var codelist=[];
    if(qunzutms.status==0){
      qunzutms.data.exist.forEach(function(c){
        if(spfwxmlist.findIndex(f => f == c.small_name) < 0){
          spfwxmlist.push(c.small_name)
        }
        if(codelist.findIndex(f => f ==c.code)<0){
          codelist.push(c.code)
        }
      });
    }
    var spfwxm=spfwxmlist.join(",");
    var codes=codelist.join(",");
    var sbmc="";
    var gjfl="";
    var gjflname="";
    var sbzch="";
    var sbzt="";
    var sqrq="";
    var csrq="";
    var zcrq="";
    var zcr="";
    var jzrq="";
    var yzcr="";
    var zcdz="";
    var dljg="";
    var logo="";
    var pic_url_user="";
    var platform_quoted_price="";
    var tm_introduction="";
    if(detailtms.status == 0 && detailtms.data.length>0){
      var tm=detailtms.data[0];
      sbmc=tm.tm_name;//商标名称
      gjfl=tm.ncl_one_codes;//国际分类
      gjflname=that.tm_gjfl[tm.ncl_one_codes];//国际分类名称
      sbzch=tm.tm_regist_num;//商标注册号
      sbzt=that.tm_status[tm.status];//商标状态
      sqrq=that.convertDate(tm.apply_day);//申请日期
      csrq=that.convertDate(tm.first_notice_day);//初审日期
      zcrq=that.convertDate(tm.original_regist_notice_day);//注册日期
      zcr=tm.applicant_cn;//申请人
      jzrq=that.convertDate(tm.tm_end_day) ;//截止日期
      yzcr=tm.original_applicant_cn;//原申请人
      zcdz=tm.applicant_cn_addr;//申请地址
      dljg=tm.tm_agency;//代理机构
      logo=tm.pic_url;//商标图样
    }
    if(ts.status == 0 && ts.data.length>0){
      var tm=ts.data[0];
      platform_quoted_price=tm.platform_quoted_price;//平台售价
      tm_introduction=tm.tm_introduction;//商标简介
      pic_url_user=tm.pic_url_user;      //用户自己上传的图片url
    }
    result.detail={
      sbmc:sbmc,//商标名称
      gjfl:gjfl,//国际分类
      gjflname:gjflname,//国际分类名称
      sbzch:sbzch,//商标注册号
      sbzt:sbzt,//商标状态
      sqrq:sqrq,//申请日期
      csrq:csrq,//初审日期
      zcrq:zcrq,//注册日期
      zcr:zcr,//申请人
      jzrq:jzrq,//截止日期
      yzcr:yzcr,//原申请人
      zcdz:zcdz,//申请地址
      dljg:dljg,//代理机构
      logo:logo,//商标图样
      spfwxm:spfwxm,//商品/服务项
      codes:codes,//群组
      pic_url_user:pic_url_user,     //用户自己上传的图片url
      platform_quoted_price:platform_quoted_price,//平台售价
      tm_introduction:tm_introduction//商标简介
    }
    console.log(result);
    return system.getResult2(result,null);
  }

  async updatePublishStatus(pobj,obj,req){
    var user = req.session.user;
    if(user){
      obj["user"]=user;
      try {
        return this.service.updatePublishStatus(obj);
      } catch (error) {
        return {code:-200,msg:"操作失败"};
      }
    }else{
      return {code:-201,msg:"获取用户失败，请重新登录"};
    }
  }
  //通过申请人获取商标 -- 目前用于 商标交易》》企业发布交易商标
  async fetchDataByApplier(obj,req){
    var user = req.session.user;
    if(user){
      var data = await this.utilstmSve.tmShortListByApplicantCn(obj,"");
      var result={code:1,count:0,data:[]};
      if(data && data.status==0){
        result.count=data.total;
        result.data=data.data;
      }
      return result;
    }else{
      return {code:-100,msg:"用户数据为空"};
    }
  }
  //通过注册号获取商标 -- 目前用于 商标交易》》企业发布交易商标
  async fetchDataByRegistNums(obj,req){
    var user = req.session.user;
    if(user){
      var registNums = [];
      if(!obj.registNums || obj.registNums.length<1){
        return {code:-1,msg:"registNums参数错误"}
      }
      for(var i=0;i<obj.registNums.length;i++){
        if(obj.registNums[i]){
          registNums.push(obj.registNums[i]);
        }
      }
      if(!registNums || registNums.length<1){
        return {code:-2,msg:"registNums参数错误"}
      }
      obj.registNums=registNums;
      var data = await this.utilstmSve.tmShortListByRegistNums(obj,"");
      var result={code:1,count:0,data:[]};
      if(data && data.status==0){
        result.count=data.total;
        result.data=data.data;
      }
      return result;
    }else{
      return {code:-100,msg:"用户数据为空"};
    }
  }

   //发布申请人商标 -- 目前用于 商标交易》》企业发布交易商标
   async publishApplierTm(pobj,obj,req){
    var user = req.session.user;
    if(user){
      obj["user"]=user;
      try {
        var result = await this.service.publishApplierTm(obj);
        return result;
      } catch (error) {
        return {code:-200,msg:"操作失败"};
      }

    }else{
      return {code:-100,msg:"用户数据为空"};
    }
  }

  async editTmtsType(pobj,obj,req){
    var user = req.session.user;
    if(user){
      obj["user"]=user;
      try {
        var result = await this.service.editTmtsType(obj);
        return result;
      } catch (error) {
        return {code:-200,msg:"操作失败"};
      }
    }else{
      return {code:-100,msg:"用户数据为空"};
    }
  }
  //获取某类型的交易商标
  async findByTmType(obj,req){
    if(!obj.company_id){
      //获取当前域名
      var hostname = req.hostname;
      // console.log("xccccccccccccccccccccccccccccccccccccccc", hostname);
      //按照hostname去查找公司站点信息
      var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
      if(companytmp){
        obj.company_id=companytmp.id;
      }
    }
    try {
      return this.service.findByTmType(obj);
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }
  }
  //获取商标交易的所有发布者
  async findAllCreateUser(pobj,obj,req){
    var company_id = "";
    var hostname = req.hostname;
    // console.log("xccccccccccccccccccccccccccccccccccccccc", hostname);
    //按照hostname去查找公司站点信息
    try {
      var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
      if(companytmp){
        company_id=companytmp.id;
      }else{
        return {code:-1,msg:"未查到公司信息"}
      }
      var sql = "select id,nickName from p_user  where id in (select createuser_id from (SELECT DISTINCT createuser_id FROM `bi_trademarktransaction` where createcompany_id="+company_id
      +" )as user)";
      var tmpResult = await this.service.dao.customQuery(sql);
      return {code:1,data:tmpResult}
    } catch (error) {
      console.log(error);
      return {code:-200,msg:"操作失败"}
    }

  }

  //获取推荐交易商标（热门，推荐，特价，精品 ）
  async findAllRecommendTm(obj,req){
    if(!obj.company_id){
      //获取当前域名
      var hostname = req.hostname;
      // console.log("xccccccccccccccccccccccccccccccccccccccc", hostname);
      //按照hostname去查找公司站点信息
      var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
      if(companytmp){
        obj.company_id=companytmp.id;
      }
    }
    try {
      return this.service.findAllRecommendTm(obj);
    } catch (error) {
      return {code:-200,msg:"操作失败"};
    }
  }
}
module.exports = TrademarktransactionCtl;
// var task = new TrademarktransactionCtl();
// task.findAllCreateUser(null,null).then(d=>{
//   console.log("ddddddddddddddddddddddddddddddddddddd");
//   console.log(d);
// })

// task.tmRegistSearch({registNum:"23531230"}).then(d=>{
//   console.log("ddddddddddddddddddddddddddddddddddddd");
//   console.log(d.data.rows[0].spfwxmlist);
// })

// task.tmRegistGjflSearch({sbzch:"23531230",gjfl:"16"}).then(d=>{
//   console.log("ddddddddddddddddddddddddddddddddddddd");
//   console.log(d.data.rows);
//   console.log(d.data.rows[0].spfwxmlist);
// })
