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 shopApplet 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.pagestatisticsSve=system.getObject("service.pagestatisticsSve");
     this.wxminiSve=system.getObject("service.wxminiSve");
     this.customerrollpicSve=system.getObject("service.customerrollpicSve");
     this.wxminiWssySve=system.getObject("service.wxminiWssySve");
     this.wxminiBossSve=system.getObject("service.wxminiBossSve");

   }
   //获取渠道运营统计=get
   async getChannelTotal(obj,req){
     var openId = obj.openid;
     var channelCode = obj.channel_code;
     try {
       var result={
          code: 1,
          message: "success",
          shopNum:"",
          data: {}
       };
       if(openId==null||openId==""||openId=="undefined"){
         result.code=-101;
         result.message="openid参数有误";
         return result;
       }
       if(channelCode==null||channelCode==""||channelCode=="undefined"){
         result.code=-102;
         result.message="channel_code参数有误";
         return result;
       }
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openId);
       if(userInfo=="null"||userInfo==""){
         result.code=-103;
         result.message="用户信息有误";
         return result;
       }
       return await this.businesschanceSve.getChannelTotal(obj);
     } catch (e) {
       console.log("获取渠道运营统计异常:error*****************************************************************************");
       console.log(e.stack);
       //日志记录
       logCtl.error({
          optitle:"获取渠道运营统计异常,openid="+openid+"，channelCode="+channelCode,
          op:"wxapplet/impl/shopApplet/getChannelTotal",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: {}
         };
     }
   }
   //获取渠道需求列表=get
   async getChannelServiceList(obj,req){
     console.log("page===obj==============================");
     console.log(obj);
     var openid = obj.openid;
     var channelCode = obj.channel_code;
     try {
       var result={
          code: 1,
          message: "success",
          shopNum:"",
          data: {}
       };
       if(openid==null||openid==""||openid=="undefined"){
         result.code=-101;
         result.message="openid参数有误";
         return result;
       }
       if(channelCode==null||channelCode==""||channelCode=="undefined"){
         result.code=-102;
         result.message="channel_code参数有误";
         return result;
       }
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       if(userInfo=="null"||userInfo==""){
         result.code=-103;
         result.message="用户信息有误";
         return result;
       }
       return await this.businesschanceSve.getChannelBusinessList(obj);
     } catch (e) {
       console.log("获取渠道需求列表异常:error*****************************************************************************");
       console.log(e.stack);
       //日志记录
       logCtl.error({
          optitle:"获取渠道需求列表异常,openid="+openid+"，channelCode="+channelCode,
          op:"wxapplet/impl/shopApplet/getChannelServiceList",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: {}
         };
     }
   }
   //获取渠道列表=get
   async getChannelList(obj,req){
     try {
          return await this.shopSve.userChannel(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"获取用户渠道列表异常,openid="+obj.openid,
          op:"wxapplet/impl/shopApplet/getChannelList",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //第一个为get请求参数，第二个为post请求参数
   //一键开店=post
   async openShop(obj,req){
     try {
          return await this.shopSve.opOpenShop(req);
     } catch (e) {
       console.log("openShop===========error");
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"商城开店异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/openShop",
          content:e.stack,
          clientIp:req.clientIp
        });

       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //修改店铺
   async putShop(obj,req){
     try {
          return await this.shopSve.putShopInfo(req);
     } catch (e) {
       console.log("putShop===========error");
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"修改店铺异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/putShop",
          content:e.stack,
          clientIp:req.clientIp
        });

       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //客户推荐产品列表=get//1用户，2管理人员
   async getMyRecommendServiceItemList(obj,req){
     try {
       obj.usertype=1;
       //获取推荐
       obj.recommend=1;
       return await this.shopSve.getServiceItemList(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"产品推荐列表异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
          op:"wxapplet/impl/shopApplet/getMyRecommendServiceItemList",
          content:e.stack,
          clientIp:""
        });

       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   //客户产品列表=get//1用户，2管理人员
   async getMyServiceItemList(obj,req){
     try {
       obj.usertype=1;
       return await this.shopSve.getServiceItemList(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"产品列表异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
          op:"wxapplet/impl/shopApplet/getMyServiceItemList",
          content:e.stack,
          clientIp:""
        });

       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   //店主产品列表=get//1用户，2管理人员
   async getShopServiceItemList(obj,req){
     try {
       obj.usertype=2;
       return await this.shopSve.getServiceItemList(obj);
     } catch (e) {
       console.log(e.stack);
       //日志记录
       logCtl.error({
          optitle:"店主产品列表异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
          op:"wxapplet/impl/shopApplet/getShopServiceItemList",
          content:e.stack,
          clientIp:""
        });

       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   //客户产品展示=get//1用户，2管理人员
   async getServiceItemDetails(obj,req){
     try {
       obj.usertype=1;
        return await this.shopSve.getServiceItemDetails(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"产品展示异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
          op:"wxapplet/impl/shopApplet/getServiceItemDetails",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //店主产品展示====get //1用户，2管理人员
   async getShopServiceItemDetails(obj,req){
     try {
        obj.usertype=2;
        return await this.shopSve.getServiceItemDetails(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"店主产品展示异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
          op:"wxapplet/impl/shopApplet/getShopServiceItemDetails",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //下单接口-----客户自主下单=post
   async createOrder(obj,req){
     try {
         req.ordertype="2";
         return await this.shopSve.createOrder(req);
     } catch (e) {
       console.log(e.stack);
       //日志记录
       logCtl.error({
          optitle:"下单接口-----客户自主下单异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/createOrder",
          content:e.stack,
          clientIp:req.clientIp
        });
        return {
             code: -200,
             message: "error",
             data: null
          };
     }
   }
   //下单接口----代客下单=post
   async shopCreateOrder(obj,req){
     try {
       req.ordertype="16";
       return await this.shopSve.createOrder(req);
     } catch (e) {
       console.log(e.stack);
       //日志记录
       logCtl.error({
          optitle:"下单接口----代客下单异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/shopCreateOrder",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //客户获取订单列表=get
   async getOrder(obj,req){
     try {
       obj.usertype=1;
       return await this.shopSve.getOrderList(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"客户获取订单列表异常,openid="+obj.openid,
          op:"wxapplet/impl/shopApplet/getOrder",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   //店主获取订单列表=get
   async getShopkeeperOrder(obj,req){
     try {
       obj.usertype=2;
       return await this.shopSve.getOrderList(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"店主获取订单列表异常,openid="+obj.openid,
          op:"wxapplet/impl/shopApplet/getShopkeeperOrder",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: []
         };
     }
   }
   //客户获取订单详情=get
   async getOrderDetail(obj,req){
     try {
       obj.usertype=1;
       return await this.shopSve.getOrderDetails(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"客户获取订单列表异常,openid="+obj.openid,
          op:"wxapplet/impl/shopApplet/getOrderDetail",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //店主获取订单详情=get
   async getShopkeeperOrderDetail(obj,req){
     try {
       obj.usertype=2;
       return await this.shopSve.getOrderDetails(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"店主获取订单列表异常,openid="+obj.openid,
          op:"wxapplet/impl/shopApplet/getShopkeeperOrderDetail",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //修改价格----=post
   async putShopServiceItem(obj,req){
     try {
       return await this.shopSve.putServiceItem(req);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"修改价格异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/putShopServiceItem",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //修改用户(user表上的)关注的店铺----=post
   async putConcernCode(obj,req){
     try {
       return await this.shopSve.putUserConcernCode(req);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"修改用户关注的店铺异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/putConcernCode",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //获取店铺信息----=get
   async getShopInfo(obj,req){
     try {
       return await this.shopSve.getShopItemInfo(obj);
     } catch (e) {
       //日志记录
       logCtl.error({
          optitle:"获取店铺信息异常,openid="+req.openid,
          op:"wxapplet/impl/shopApplet/getShopInfo",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            message: "error",
            data: null
         };
     }
   }
   //小程序支付==================================================================================
   async minishoporder(obj,pobj,req){
    if(pobj){
      var result = {statusCode:0,message:""}
      var notify_url = "http://boss.gongsibao.com/wx/pay";
      var desc = pobj.name;
      var amount = pobj.totalSum;
      var product_id = pobj.code;
      var attach = pobj.openId+"$$$"+pobj.orderNum;
      var payType=pobj.pay_type==null||pobj.pay_type==""||pobj.pay_type=="undefined"?"hhr":pobj.pay_type;
      if(desc==null||desc==""||desc=="undefined"){
        result.statusCode=-103;
        result.message="desc参数有误";
        return result;
      }
      if(amount==null||amount==""||amount=="undefined"){
        result.statusCode=-103;
        result.message="amount参数有误";
        return result;
      }
      if(product_id==null||product_id==""||product_id=="undefined"){
        result.statusCode=-103;
        result.message="code参数有误";
        return result;
      }
      if(pobj.openId==null||pobj.openId==""||pobj.openId=="undefined"){
        result.statusCode=-103;
        result.message="openId参数有误";
        return result;
      }
      var result=null;
      if(payType=="hhr"){
        result=await this.wxminiSve.createJsUnifiedOrder(desc,amount,notify_url,product_id,pobj.openId,attach,null);
      }else if (payType=="wssy") {
        result=await this.wxminiWssySve.createJsUnifiedOrder(desc,amount,notify_url,product_id,pobj.openId,attach,null);
      }
      else if (payType=="boss") {
        result=await this.wxminiBossSve.createJsUnifiedOrder(desc,amount,notify_url,product_id,pobj.openId,attach,null);
      }
      return result;
    }
   return {statusCode:-1,msg:'参数传递异常'};
  }
  //页面统计----=post
  async addPageStatistics(obj,req){
    var openid = req.openid;
    var onlycode = req.onlycode;
    var code = req.code;
    var tjCode = req.tj_code;
    try {
      var result={
         code: 1,
         message: "success",
         shopNum:"",
         data: []
      };
      if(openid==null||openid==""||openid=="undefined"){
        result.code=-101;
        result.message="openid参数有误";
        return result;
      }
      if(onlycode==null||onlycode==""||onlycode=="undefined"){
        onlycode=null;
      }
      if(code==null||code==""||code=="undefined"){
        code=null;
      }
      if(tjCode==null||tjCode==""||tjCode=="undefined"){
        result.code=-103;
        result.message="shopname参数有误";
        return result;
      }
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      if(userInfo=="null"||userInfo==""){
        result.code=-104;
        result.message="用户信息有误";
        return result;
      }
      var tUserInfo=JSON.parse(userInfo);
      //目标唯一码（用户唯一码或店铺唯一码）
      tUserInfo.target_only_code=onlycode;
      //服务项目编码
      tUserInfo.item_code=code;
      //统计类型编码
      tUserInfo.statistics_code=tjCode;

      tUserInfo.client_ip=req.clientIp;
      return this.pagestatisticsSve.add(tUserInfo,result,1);
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"移动商城统计操作异常,openid="+openid+"，code="+code+"，onlycode="+onlycode+"statistics_code="+tjCode,
         op:"wxapplet/impl/shopApplet/addPageStatistics",
         content:e.stack,
         clientIp:req.clientIp
       });
      return {
           code: -200,
           message: "error",
           data: null
        };
    }
  }
  //获取需求信息----=get
  async getNeedList(obj,req){
    try {
      return await  this.businesschanceSve.getChanceTypeList(obj);
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"获取需求信息异常,openid="+req.openid,
         op:"wxapplet/impl/shopApplet/getNeedList",
         content:e.stack,
         clientIp:""
       });
      return {
           code: -200,
           message: "error",
           data: []
        };
    }
  }
  //发布需求----=post
  async addNeed(obj,req){
    try {
      return await this.businesschanceSve.addChanceType(req);
    } catch (e) {
      //日志记录
      logCtl.error({
         optitle:"发布需求异常,openid="+req.openid,
         op:"wxapplet/impl/shopApplet/addNeed",
         content:e.stack,
         clientIp:req.clientIp
       });
      return {
           code: -200,
           message: "error",
           data: null
        };
    }
  }
  //获取统计排行信息----=get
  async getRankList(obj,req){
    var tjCode = obj.tj_code;
    var topNum =obj.top_num;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    try {
      if(tjCode==null||tjCode==""||tjCode=="undefined"){
        result.code=-102;
        result.message="tjCode参数有误";
        return result;
      }
      return await this.pagestatisticsSve.getRankList(tjCode,Number(topNum));
    } catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
         optitle:"获取统计排行信息异常",
         op:"wxapplet/impl/shopApplet/getRankList",
         content:e.stack,
         clientIp:""
       });
      result.code=-200;
      result.message="error";
      return result;
    }
  }
  //获取友金所统计排行信息----=get
  async getYjsRankList(obj,req){
    var tjCode = obj.tj_code;
    var topNum =obj.top_num;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    try {
      if(tjCode==null||tjCode==""||tjCode=="undefined"){
        result.code=-102;
        result.message="tjCode参数有误";
        return result;
      }
      return await this.pagestatisticsSve.getYjsRankList(tjCode,Number(topNum));
    } catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
         optitle:"获取统计排行信息异常",
         op:"wxapplet/impl/shopApplet/getYjsRankList",
         content:e.stack,
         clientIp:""
       });
      result.code=-200;
      result.message="error";
      return result;
    }
  }
  //获取分裂排行信息----=get
  async getReferrerRankList(obj,req){
    var topNum =obj.top_num;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    try {
      return await this.accountService.getReferrerRankList(Number(topNum));
    } catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
         optitle:"获取分裂排行信息异常",
         op:"wxapplet/impl/shopApplet/getReferrerRankList",
         content:e.stack,
         clientIp:""
       });
      result.code=-200;
      result.message="error";
      return result;
    }
  }
//海报查询------------get
  async showcustomerrollpics(obj,req){
    var self=this;
    var openid=obj.openid;
    var picCategory=obj.picCategory;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    try{
      if(openid==null||openid==""||openid=="undefined")
      {
        result.code=-200;
        result.message="openid参数有误";
        return result;
      }
      if(picCategory==null||picCategory==""||picCategory=="undefined")
      {
        result.code=-200;
        result.message="picCategory参数有误";
        return result;
      }
      var userInfo =await self.cacheManager["AppletUserinfoCache"].get(openid);
      userInfo=JSON.parse(userInfo);
      var userpic=userInfo.customerrollpic_id==null||userInfo.customerrollpic_id==''||userInfo.customerrollpic_id=="undefnd"?'https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_457101542716244314201820201724314ic.png':userInfo.customerrollpic_id;
      var cobj={picType:"placard",picCategory:picCategory};
      var crpics=await self.customerrollpicSve.dao.model.findAll({where:cobj});
      if(crpics!=null&&crpics.length!=0){
        result.data={customerrollpicid:userpic,crpics:crpics};
      }else{
        result.data={customerrollpicid:userpic,crpics:[]};
      }
      return result;
    }catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
         optitle:"海报展示查询异常",
         op:"wxapplet/impl/shopApplet/showcustomerrollpics",
         content:e.stack,
         clientIp:""
       });
      result.code=-200;
      result.message="error";
      return result;
    }
  }

  //海报查询------------get
    async mycustomerrollpics(obj,req){
      var self=this;
      var openid=obj.openid;
      var result={
         code: 1,
         message: "success",
         data: {}
      };
      try{
        if(openid==null||openid==""||openid=="undefined")
        {
          result.code=-200;
          result.message="openid参数有误";
          return result;
        }
        var userInfo =await self.cacheManager["AppletUserinfoCache"].get(openid);
        userInfo=JSON.parse(userInfo);
        var crpics=await self.customerrollpicSve.dao.model.findById(userInfo.customerrollpic_id);
        if(crpics!=null&&crpics.length!=0){
          result.data={crpics:crpics};
        }else{
          var en={linkUrl:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_457101542716244314201820201724314ic.png"};
          result.data={crpics:en};
        }
        return result;
      }catch (e) {
        // console.log(e.stack);
        //日志记录
        logCtl.error({
           optitle:"海报展示查询异常",
           op:"wxapplet/impl/shopApplet/mycustomerrollpics",
           content:e.stack,
           clientIp:""
         });
        result.code=-200;
        result.message="error";
        return result;
      }
    }


//修改海报------------post
  async updatacustomerrollpic(obj,req){
    var self=this;
    var openid=req.openid;
    var customerrollpicid=req.customerrollpicid;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    try{
      if(openid==null||openid==""||openid=="undefined")
      {
        result.code=-200;
        result.message="openid参数有误";
        return result;
      }
      if(customerrollpicid==null||customerrollpicid==""||customerrollpicid=="undefined")
      {
        result.code=-200;
        result.message="customerrollpicid参数有误";
        return result;
      }
      var userInfo =await self.cacheManager["AppletUserinfoCache"].get(openid);
      userInfo=JSON.parse(userInfo);
      userInfo.customerrollpic_id=Number(customerrollpicid);
      var r=await self.userService.dao.model.update(userInfo,{where:{id:userInfo.id}});
      await self.cacheManager["AppletUserinfoCache"].del(openid);
      result.data=r;
      return result;
    }catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
         optitle:"修改海报异常",
         op:"wxapplet/impl/shopApplet/updatacustomerrollpic",
         content:e.stack,
         clientIp:""
       });
      result.code=-200;
      result.message="error";
      return result;
    }
  }


}
module.exports=shopApplet;
// var app = new shopApplet();
// var obj={
//   channel:"hhr",
//   code:"sbptsq",
//   customer_contact_info:
//   {
//    creditCode:"911101057889696760",
//    customer_contact:"111",
//    customer_type:"ent",
//    ent_name: "汉唐信通(北京)咨询股份有限公司",
//    mobile: "13075556693",
//    pay_type: "offline",
//    offline_pay_document:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_ovPx35GktY-8pn3GmpIYfcbmqZQk1545191652816.jpg",
//    remark:""
//   },
//   customer_num:2062926355,
//   num:1,
//   offline_pay_document:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_ovPx35GktY-8pn3GmpIYfcbmqZQk1545191652816.jpg",
//   onlycode:"odnZ4t9d_RtUEWg_PigNoO6xXdSs",
//   openid:"ovPx35GktY-8pn3GmpIYfcbmqZQk",
//   pay_type:"offline",
//   total_sum:899
// }
// app.shopCreateOrder({},obj).then(function(r){
//   console.log(r);
// })
