var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
const AppletBase =require("../applet.base");
const logCtl=system.getObject("web.oplogCtl");
class bossShopApplet extends AppletBase{
   constructor(){
     super();
     this.cacheManager=system.getObject("db.cacheManager");
     this.businesschanceSve=system.getObject("service.businesschanceSve");
     this.orderService=system.getObject("service.orderSve");
     this.userService=system.getObject("service.userSve");
     this.accountService=system.getObject("service.accountSve");
     this.orderService=system.getObject("service.orderSve");
     this.shopSve=system.getObject("service.shopSve");
     this.wxminiSve=system.getObject("service.wxminiSve");
     this.connectionbh=system.getObject("db.connection").getConhb();
     this.customerinfoSve=system.getObject("service.customerinfoSve");
     this.usercustomerSve=system.getObject("service.usercustomerSve");
     this.utilstmSve=system.getObject("service.utilstmSve");
     this.utilsicSve=system.getObject("service.utilsicSve");
     this.utilscopyrightSve=system.getObject("service.utilscopyrightSve");
     this.utilspaSve=system.getObject("service.utilspaSve");
     this.trademarkSve=system.getObject("service.trademarkSve");
     this.tmflowSve=system.getObject("service.tmflowSve");
   }

   //------------------------------商标数据--------------------------------------------------
   //获取商标数量=post
   async getPfData(obj,req){
      var openid = req.openid;
      if(openid==null||openid==""||openid=="undefined"){
          return system.getResult2(null,null,null,"openid参数有误");
      }
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      if(userInfo=="null"||userInfo==""){
          return system.getResult2(null,null,null,"用户信息有误");
      }
      //评分的规则：满分85分。商标45分（共5个,），专利25分（共2个），著作权15分（共3个）
      //商标数量----applicant_cn
      var tmCountResult=await this.utilstmSve.tmCountByApplicantCn(req,"bossShopApplet");
      //著作权数量---author
      req.author=req.applicant_cn;
      var softwareCountResult=await this.utilscopyrightSve.softwareCountByAuthor(req,"bossShopApplet");
      var worksCountResult=await this.utilscopyrightSve.worksCountByAuthor(req,"bossShopApplet");
      //applicant_name
      req.applicant_name=req.applicant_cn;
      var paCountResult=await this.utilspaSve.paCountByApplicantName(req,"bossShopApplet");
      //总分
      var totalPf=0;
      //处理商标
      var tmCount=tmCountResult.status==0?tmCountResult.total:0;
      if(tmCount>=5){
        totalPf=totalPf+45;
      }else {
        totalPf=totalPf+tmCount*9;
      }

      //软件著作权数量
      var zzrjCount=softwareCountResult.status==0?softwareCountResult.total:0;
      //作品著作权数量
      var zzCount= worksCountResult.status==0?worksCountResult.total:0;
      //处理著作权
      var zzqCount=zzrjCount+zzCount;
      if(zzqCount>=3){
        totalPf=totalPf+15;
      }else {
        totalPf=totalPf+zzqCount*5;
      }
      //处理专利
      var paCount=paCountResult.status==0?paCountResult.total:0;
      if(paCount>=2){
        totalPf=totalPf+25;
      }else if (paCount==1) {
        totalPf=totalPf+12.5;
      }
      return {
            status: 0,
            msg: "操作成功",
            total: totalPf,
            data: [
              {
                tm_count:tmCount,//商标数量
                cr_count:zzqCount,//软著数量
                pa_count:paCount,//专利数量
                crrj_count:zzrjCount,//软件著作权数量
          			crzp_count:zzCount,//作品著作权数量,
                fm_count:paCountResult.status==0?paCountResult.data[0].fm_count:0,//发明数量
                wg_count:paCountResult.status==0?paCountResult.data[0].wg_count:0,//外观设计数量
                syxx_count:paCountResult.status==0?paCountResult.data[0].syxx_count:0//实用新型数量
              }],
            bizmsg: "empty"
        };


      //专利数量
      // return this.utilstmSve.tmCountByApplicantCn(req,"bossShopApplet");
   }
   //获取商标列表=post
   async getTmShortList(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilstmSve.tmShortListByApplicantCn(req,"bossShopApplet");
   }
   //获取商标数量=post
   async getTmDetails(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return System.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilstmSve.tmSearch(req,"bossShopApplet");
   }
   //获取商标流程=post
   async getTmFlow(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilstmSve.getTmFlow(req,"bossShopApplet");
   }
   //获取商标小类=post
   async getTmNclSmallCodes(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilstmSve.getTmNclSmallCodes(req,"bossShopApplet");
   }
   //--------------------------------工商数据------------------------------------
   //公司模糊精确查询=post
   async getCompanyByLikeCompany(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
     req.query_type="like";
     return this.utilsicSve.icDetailsByCompanyName(req,"bossShopApplet");
   }
   //公司精确查询=post
   async getCompanyByCompany(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilsicSve.icDetailsByCompanyName(req,"bossShopApplet");
   }
   //----------------------------------------------------著作权数据-----------------------
   //某个公司的软件著作权列表=postordersbysaleman
   async getSoftwareListByAuthor(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilscopyrightSve.softwareListByAuthor(req,"bossShopApplet");
   }
   //软件著作权详情=post
   async getSoftwareDetailsByAuthor(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilscopyrightSve.softwareDetailsByAuthor(req,"bossShopApplet");
   }

   //某个公司的作品著作权列表=post
   async getWorksListByAuthor(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
     return this.utilscopyrightSve.worksListByAuthor(req,"bossShopApplet");
   }
   //作品著作权详情=post
   async getWorksDetailsByAuthor(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
      return this.utilscopyrightSve.worksDetailsByAuthor(req,"bossShopApplet");
   }

   //----------------------------------------------------专利数据-----------------------
   //专利数量=post
   async getPaCount(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
     return this.utilspaSve.paCountByApplicantName(req,"bossShopApplet");
   }
   //专利列表=post
   async getPaShortList(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
     return this.utilspaSve.paShortListByApplicantName(req,"bossShopApplet");
   }
   //专利详情=post
   async getPaDetails(obj,req){
     var openid = req.openid;
     if(openid==null||openid==""||openid=="undefined"){
         return system.getResult2(null,null,null,"openid参数有误");
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
         return system.getResult2(null,null,null,"用户信息有误");
     }
     req.page_size=1;
     req.current_page=1;
     return this.utilspaSve.paDetails(req,"bossShopApplet");
   }
//-----------------------------------------其他---------------------------------------------

//通过客户查首席服务官----=get
  async selservicerbycustomer(obj,req){
    try {
      if( obj.openid ==null　||　obj.openid==""　|| obj.openid =="undefined" )
      {
        return {code:-200,msg:'参数错误'};
      }
      var obj = {openId:obj.openid};
      var userinfo=await this.userService.findOne(obj);
      if(userinfo){
        var ucobj = {customerNum:userinfo.customerNum};
        var ucinfo=await this.usercustomerSve.findOne(ucobj);
        if(ucinfo)
        {
          var sobj = {id:ucinfo.user_id};
          var suserinfo=await this.userService.findOne(sobj);
          if(suserinfo){
            return {code:0,msg:'查询成功',data:suserinfo};
          }
          else {
            return {code:0,msg:sobj};
          }
        }
        else {
          return {code:0,msg:ucobj};
        }
      }

    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"首席服务官查询失败,客户openid="+obj.openid+"时间："+obj.t,
         op:"wxapplet/impl/bossShopApplet/selservicerbycustomer",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             message: "error",
             data: null
          };
    } finally {

    }
  }


async customersbysalemanlist(){
  try {
    var sql='SELECT * from h_behivetoboss';
    var users=await this.userService.dao.customQuery(sql);
    for(var i=0;i<users.length;i++){
      var obj = {mobile:users[i].wxmobile};
      var userinfo=await this.userService.findOne(obj);
      if(userinfo)
      {
        var r=await this.customersbysaleman(null,{openId:userinfo.openId,mobile:users[i].bmobile});
      }
    }
     return r;
  } catch (e) {
    //日志记录
    logCtl.error({
       optitle:"导入老客户数据",
       op:"wxapplet/impl/bossShopApplet/customersbysalemanlist",
       content:e.stack
       });
  } finally {

  }
}

async ordersbysalemanlist(){
  try {
    var sql='SELECT * from h_behivetoboss';
    var users=await this.userService.dao.customQuery(sql);
    for(var i=0;i<users.length;i++){
      var obj = {mobile:users[i].wxmobile};
      var userinfo=await this.userService.findOne(obj);
      if(userinfo)
      {
        var r=await this.customersbysaleman(null,{openId:userinfo.openId,mobile:users[i].bmobile});
      }
    }
     return r;
  } catch (e) {
    //日志记录
    logCtl.error({
       optitle:"导入老客户订单数据",
       op:"wxapplet/impl/bossShopApplet/ordersbysalemanlist",
       content:e.stack
       });
  } finally {

  }
}

//初始化客户----=post
  async customersbysaleman(obj,req){
    try {
      if( req.openId ==null||req.openId==""|| req.openId =="undefined" )
      {
        return {code:-200,msg:'参数错误'};
      }
      if( req.mobile ==null||req.mobile==""|| req.mobile =="undefined" )
      {
        return {code:-200,msg:'参数错误'};
      }
      var obj = {openId:req.openId}
      var userinfo=await this.userService.findOne(obj);
      if( userinfo ){
          var sql='SELECT DISTINCT cc.mobile mobile,cc.real_name cname,cci.company_name companyname ';
          sql +="FROM sys_permission_employee uu JOIN so_order so JOIN crm_customer cc join crm_company_intention cci ON uu.id = so.owner_id and so.account_id=cc.account_id and cci.pkid = so.company_id where uu.mobile='"+req.mobile+"' and so.add_time > '2017-01-01' and so.payable_price>100";
          var customerinfos=await this.connectionbh.query( sql );
          if( customerinfos ){
            var result=await this.customerinfoSve.firstloading( userinfo, customerinfos[0,0] );
            return result;
          }
        else{
          return {code:0,msg:"暂无数据",data:0};
        }
      }
      else {
        return {code:-200,msg:'用户不存在',data:0};
      }
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"初始化客户信息失败,openid="+req.openId,
         op:"wxapplet/impl/bossShopApplet/customersbysaleman",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             message: "error",
             data: null
          };
    }
  }
//初始化订单----=post
  async ordersbysaleman(obj,req){
    try {
      if( req.openId ==null||req.openId==""|| req.openId =="undefined" )
      {
        return {code:-200,msg:'参数错误'};
      }
      if( req.mobile ==null||req.mobile==""|| req.mobile =="undefined" )
      {
        return {code:-200,msg:'参数错误'};
      }
      var obj = {openId:req.openId};
      var userinfo=await this.userService.findOne(obj);
      if( userinfo ){
          var sql="SELECT ";
          sql +=" cc.mobile mobile, cc.real_name cname, so.no orderNum, so.prod_name itemName, so.is_invoice invoiceApply,";
          sql +=" so.payable_price totalSum, so.process_status_id orderStatus, so.account_name customerContact, so.account_mobile customerMobile, so.add_time add_time";
          sql +=" FROM sys_permission_employee uu JOIN so_order so JOIN crm_customer cc ON uu.id = so.owner_id AND so.account_id = cc.account_id";
    　　　 sql +=" WHERE uu.mobile = '"+req.mobile+"' AND so.add_time > '2017-01-01' AND so.is_close = 0";
         var orderinfos=await this.connectionbh.query(sql);
          if( orderinfos ){
            var result=await this.orderService.firstloading( userinfo, orderinfos[0,0] );
            return result;
          }
      }
      else {
        return {code:-200,msg:'用户不存在'};
      }
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"初始化订单信息失败,openid="+req.openId,
         op:"wxapplet/impl/bossShopApplet/ordersbysaleman",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             message: "error",
             data: null
          };
    } finally {

    }

  }
  async findbhtm(){
    var r=await this.trademarkSve.getBhtminfo();
    return r;
  }

//根据申请人查询商标数量进度
  async getTmsByApplyCount(obj,req){
    try {
      if(obj.applyName==null||obj.applyName==""||obj.applyName=="undefined"){
        return {code:-200,msg:'参数错误',data:null};
      }
      obj.applyName=await this.getConvertSemiangleStr(obj.applyName);
      var count=await this.trademarkSve.dao.findCount({where:{applyName:obj.applyName}});
      return {code:1,msg:'查询成功',data:count}
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"根据申请人查询商标数量进度失败,openid="+obj.applyName,
         op:"wxapplet/impl/bossShopApplet/getTmsByApplyCount",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             msg: "error",
             data: null
          };
    }
  }
//根据申请人查询商标进度
  async getTmsByApply(obj,req){
    try {
      if(obj.applyName==null||obj.applyName==""||obj.applyName=="undefined"){
        return {code:-200,msg:'参数错误',data:null};
      }
      obj.applyName=await this.getConvertSemiangleStr(obj.applyName);
      var tms=await this.trademarkSve.dao.model.findAll({where:{applyName:obj.applyName}});
      if(tms!=null&&tms.length>0)
      {
        return {code:1,msg:'查询成功',data:tms}
      }
      else {
        return {code:1,msg:'查询成功',data:null}
      }
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"根据申请人查询商标进度失败,openid="+obj.applyName,
         op:"wxapplet/impl/bossShopApplet/getTmsByApply",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             msg: "error",
             data: null
          };
    }
  }
  async getConvertSemiangleStr(str){
    var result = "";
    str=str.replace(/\s+/g,"");
    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;
  };

  async getTmStatusDetails(obj,req){
    try {
      var self=this;
      if(obj.proxyCode==null||obj.proxyCode==""||obj.proxyCode=="undefined"){
        return {code:-200,msg:'参数错误',data:null};
      }
      var tm=await this.trademarkSve.findOne({proxyCode:obj.proxyCode});
      if(tm){
        var tmflow=[];
        if(tm.tmSourceType==8){
          var sql='SELECT sa.path url,sa.create_time create_time, sa.name filename';
          sql +=' FROM ig_trade_mark itm JOIN sys_attachment sa ON itm.id = sa.foreign_key';
          sql +=" WHERE (sa.`name` LIKE '%RECVCOMMIT%' OR sa.`name` LIKE '%3%') and itm.code='"+ tm.tmRegistNum +"'"
          var myfiles=await this.connectionbh.query(sql);
           if(myfiles){
             myfiles[0,0].forEach(a=>{
               if(a.filename.indexOf("RECVCOMMIT")>0){
                 var source={};
                 source.name="商标注册申请书";
                 source.filepath=a.url;
                 source.create_time=a.create_time;
                 tmflow.push(source);
               }
               if(a.filename.indexOf("3")>0){
                 var source={};
                 source.name="商标注册受理通知书";
                 source.filepath=a.url;
                 source.create_time=a.create_time;
                 tmflow.push(source);
               }
             })
             if(tm.tmStatus=='9'){
               var source={};
               source.name="初审公告";
               source.filepath='';
               source.create_time=tm.updated_at;
               tmflow.push(source);
             }
           }
           else {
             return {code:1,msg:'查询成功',data:null};
           }
        }
        else{
          var tmflowinfos=await self.tmflowSve.dao.model.findAll({where:{proxyCode:tm.proxyCode}});
          if(tmflowinfos!=null&&tmflowinfos.length>0){
            tmflowinfos.forEach(a=>{
              if(a.tmStatus=='RECVCOMMIT'){
                var source={};
                source.name="商标注册申请书";
                source.filepath=a.returnReceiptUrl;
                source.create_time=a.created_at;
                tmflow.push(source);
              }
              if(a.tmStatus=='3'){
                var source={};
                source.name="商标注册受理通知书";
                source.filepath=a.returnReceiptUrl;
                source.create_time=a.created_at;
                tmflow.push(source);
              }
            })
            if(tm.tmStatus=='9'){
              var source={};
              source.name="初审公告";
              source.filepath='';
              source.create_time=tm.updated_at;
              tmflow.push(source);
            }
          }
          else {
            return {code:1,msg:'查询成功',data:null};
          }
        }
        var data={tminfo:tm,tmflow:tmflow}
        return {code:1,msg:'查询成功',data:data};
      }
      else {
        return {code:1,msg:'暂无数据',data:null};
      }
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"查询商标进度详情信息失败,openid="+obj.proxyCode,
         op:"wxapplet/impl/bossShopApplet/getTmStatusDetails",
         content:e.stack,
         clientIp:req.clientIp
         });
        return {
             code: -200,
             msg: "error",
             data: null
          };
    }
  }



}
module.exports=bossShopApplet;
