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 businesschanceApplet extends AppletBase{
   constructor(){
     super();
     this.businesschanceService=system.getObject("service.businesschanceSve");
     this.orderService=system.getObject("service.orderSve");
     this.businesschanceSve=system.getObject("service.businesschanceSve");
     this.channelSve=system.getObject("service.channelSve");
     this.servicesitemSve=system.getObject("service.servicesitemSve");
     this.shopSve=system.getObject("service.shopSve");
   }
   async getBusinessChancesByHhrId(obj,req){
     try {
       var openid = obj.openid;
       console.log(openid);
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       if(userInfo==null||userInfo=="undefined"){
         return system.getResult2(null,null);
       }
       userInfo=JSON.parse(userInfo);
       console.log(userInfo);
       var userId=userInfo.id;
       var onlyCode=userInfo.onlyCode;
       var payUserIds= await this.orderService.getPayUserIdByOnlyCode(userInfo.onlyCode);
       var data={};
       if(obj.searchName==null|| obj.searchName==""||obj.searchName=="undefined"){
           if(payUserIds[0]==null){
             data[this.db.Op.or]=[
                  {shopOnlyCode:onlyCode}
                ];
           }else {
             data[this.db.Op.or]=[
                  {publisherId:{[this.db.Op.in]:payUserIds}},
                  {shopOnlyCode:onlyCode}
                ];
           }
       }else{
          if(payUserIds[0]==null){
            data[this.db.Op.or]=[
                 {[this.db.Op.or]:[{shopOnlyCode:onlyCode},
                                   {publisherName:{[this.db.Op.like]:"%"+obj.searchName+"%" }},
                                   {publisherMobile:{[this.db.Op.like]:"%"+obj.searchName+"%" }},
                                   {chanceTypeName:{[this.db.Op.like]: "%"+obj.searchName+"%" }},
                                   {chanceStatusName:{[this.db.Op.like]: "%"+obj.searchName+"%" }}]}
               ];
          }
          else {
            data[this.db.Op.or]=[
                 {publisherId:{[this.db.Op.in]:payUserIds}},
                 {[this.db.Op.or]:[{shopOnlyCode:onlyCode},
                                   {publisherName:{[this.db.Op.like]:"%"+obj.searchName+"%" }},
                                   {publisherMobile:{[this.db.Op.like]:"%"+obj.searchName+"%" }},
                                   {chanceTypeName:{[this.db.Op.like]: "%"+obj.searchName+"%" }},
                                   {chanceStatusName:{[this.db.Op.like]: "%"+obj.searchName+"%" }}]}
               ];
          }
       }
       var chances = await this.businesschanceService.findAllChances(data);
       if(chances==null||chances.length==0){
         return system.getResult2(null,null);
       }
       console.log("chances.....................................01");
       console.log(chances);
       //获取渠道名称
       var self=this;
       for (var i = 0; i < chances.length; i++) {
         if(chances[i]!=null){
           chances[i].channelName="";
         }
         if(chances[i].channelCode!=null&&chances[i].channelCode!=""&&chances[i].channelCode!="undefined"){
           var channel=await self.channelSve.getChannelItem(chances[i].channelCode);
           if(channel!=null){
             chances[i].channelName=channel.channelName;
           }
         }
       }
       console.log("chances--------------------------------------------------02");
       console.log(chances);
       return system.getResult2(chances,null);
     } catch (e) {
        console.log(e.stack);
        //日志记录
        logCtl.error({
           optitle:"获取我的商机异常,openid="+obj.openid,
           op:"wxapplet/impl/businesschanceApplet/getBusinessChancesByHhrId",
           content:e.stack,
           clientIp:req.clientIp
         });
     } finally {

     }


   }

   async findCustomers(obj,req){
     var openid = obj.openid;
     var nickName = obj.nickName;
     var userinfo = await this.getUserInfo(openid);
     userinfo=JSON.parse(userinfo);
     console.log(userinfo.unionId);
     console.log("findCustomers-----------------------getUserInfo------");
     console.log(userinfo);
     console.log(nickName);
     if(!nickName){
       return this.businesschanceService.findCustomersByOnlyCode(userinfo.unionId);
     }else{
       return this.businesschanceService.findCustomers(userinfo.unionId,nickName);
     }

   }
   //发布需求
   async submitneed(pobj,obj){
     var serviceItem_name="";
     var chanceType="yzc";
     if(obj.publisherName==""||obj.publisherName==null){
       return {code:-100,msg:"请填写您的姓名"};
     }
     if(obj.publisherMobile==""||obj.publisherMobile==null){
       return {code:-100,msg:"请填写您的电话"};
     }
     if(obj.notes!=""&&obj.notes.length>255){
       return {code:-100,msg:"备注字数超出限制，请重新填写"};
     }

     if(obj.channelCode==""){
       return {code:-110,msg:"channelCode参数传递错误"};
     }
     var channelItem=await this.channelSve.getChannelItem(obj.channelCode);
     if(channelItem==""||channelItem==null){
       return {code:-110,msg:"channelCode参数传递错误"};
     }

     if(obj.serviceItem_code==""){
       return {code:-110,msg:"serviceItem_code参数传递错误"};
     }
     var serviceItem=await this.servicesitemSve.findOneByCode(obj.serviceItem_code);
     if(serviceItem==""||serviceItem==null){
       return {code:-110,msg:"serviceItem_code参数传递错误"};
     }else{
       serviceItem_name=serviceItem.name;
       chanceType=serviceItem.itemType;
     }

     if(obj.publisherOnlyCode!=""&&obj.shopOnlyCode!=""){
       var pobj={
         publisherOnlyCode:obj.publisherOnlyCode,
         shopOnlyCode:obj.shopOnlyCode,
         serviceItem_code:obj.serviceItem_code,
         channelCode:obj.channelCode,
         chanceStatus:"1"
       }
       var result=await this.businesschanceService.findchance(pobj);
       if(result!=""&&result!=null){
         return {code:"0",msg:"您已经发布需求，请不要重复提交"};
       }
     }
     try{
       var reqParams={
         notes:obj.notes,
         publisherName:obj.publisherName,
         publisherMobile:obj.publisherMobile,
         channelCode:obj.channelCode,
         serviceItem_code:obj.serviceItem_code,
         serviceItem_name:serviceItem_name,
         publisherOnlyCode:obj.publisherOnlyCode,
         shopOnlyCode:obj.shopOnlyCode,
         chanceStatus:"1",
         chanceType:chanceType,
         channelProfitRatio:channelItem.profitType==1?(channelItem.everySingleProfit||0):0,//渠道分成比率（如：总额100，字段值30，则渠道的利润为30/100，剩下的则为平台利润）
         channelProfit:channelItem.profitType==2?(channelItem.everySingleProfit||0):0,//渠道利润
         profitType:channelItem.profitType//渠道利润类型:1: "比例分成", 2: "每单分成"
       }
       //新增的省份和城市
       var tCity=obj.city||"";
       var tProvince=obj.province||"";
       if(tCity && tProvince){
         reqParams.city=tCity;
         reqParams.province=tProvince;
       }
       // console.log(reqParams);
       var chance = await this.businesschanceService.create(reqParams);
       if(obj.shopOnlyCode!=null&&obj.shopOnlyCode!=""&&obj.shopOnlyCode!="undefined"&&chance){
          var shopItem=await this.shopSve.getShopItem(obj.shopOnlyCode);
          if(shopItem!=null&&shopItem.userMobile!=null&&shopItem.userMobile!=""&&shopItem.userMobile!="undefined"){
            //发送短信
            var smsClient=system.getObject("util.smsClient");
            smsClient.sendMsg(shopItem.userMobile,"亲，您的客户【"+obj.publisherName+"】于"+(new Date()).Format("yyyy-MM-dd")+"发布了关于【"+
                                   serviceItem_name+"】求购需求，赶紧到知产合伙人小程序中【我的商机】进行查看！");
          }
       }
       // console.log("-----------------chance-----------");
       // console.log(chance);
       // this.smsClient=System.getObject("util.smsClient");
       // this.smsClient.sendMsg("13381139519","亲爱的知产合伙人，你的客户于"+(new Date()).Format("yyyy-MM-dd")+"发布了新的需求，亲，赶紧去自己店铺去查看“我的商机”吧！");
       return {code:"1",msg:"发布成功"};
     }catch(e){
       console.log(e);
       logCtl.error({
          optitle:"submitneed 发布需求异常,publisherName="+obj.publisherName+"publisherMobile:"+obj.publisherMobile+"serviceItem_code="+obj.serviceItem_code+",shopOnlyCode="+obj.shopOnlyCode+"publisherOnlyCode="+obj.publisherOnlyCode,
          op:"wxapplet/impl/businesschanceApplet/submitneed",
          content:e.stack,
          clientIp:""
        });
       return {code:"-1",msg:"操作失败，请稍后重试"};
     }
   }
   //获取需求信息----=get
   async getNeedList(obj){
     try {
       return this.businesschanceSve.getTmTradeNeedList(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"获取需求信息异常,openid="+obj.openid,
          op:"wxapplet/impl/businesschanceApplet/getNeedList",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   async getTmTradeChanceDetail(obj){
     try {
       return this.businesschanceSve.getTmTradeDetails(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"获取需求详情信息异常,openid="+obj.openid,
          op:"wxapplet/impl/businesschanceApplet/getTmTradeChanceDetail",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }

}
module.exports=businesschanceApplet;
// var task=new businesschanceApplet();
// var obj ={openid:"ovPx35GktY-8pn3GmpIYfcbmqZQk",chanceId:"53"};
// task.getTmTradeChanceDetail(obj).then(function(result){
//   console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
