const system=require("../../system");
const ServiceBase=require("../sve.base");
class ShopService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ShopService));
     this.cacheManager=system.getObject("db.cacheManager");
     this.servicesitemDao=system.getObject("db.servicesitemDao");
     this.shopserviceitemDao=system.getObject("db.shopserviceitemDao");
     this.ordercustomerinfoDao=system.getObject("db.ordercustomerinfoDao");
     this.userDao=system.getObject("db.userDao");
     this.pconfigSve=system.getObject("service.pconfigSve");
     this.orderSve=system.getObject("service.orderSve");
     this.channelSve=system.getObject("service.channelSve");
     this.tmcustomerinfoDao=system.getObject("db.tmcustomerinfoDao");
     this.orderflowDao=system.getObject("db.orderflowDao");
  }
  //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213-----商标交易
  isCheckChannelArry(channel){
    var arr=["yzc"];
    if(arr.indexOf(channel) > -1){
      return true;
    }
    return false;
  }
  buildDate(date){
     var date = new Date(date);
     var time = Date.parse(date);
     return time;
  }
  //获取用户渠道
  async userChannel(obj){
    var openid = obj.openid;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==""||userInfo=="undefined"){
      result.code=-102;
      result.message="用户信息有误";
      return result;
    }
   var tUserInfo=JSON.parse(userInfo);
   var sql="SELECT channelName,channelCode,isEnabled,channelShopName FROM `p_channel` WHERE moreShop=1 OR (`deleted_at` IS NULL AND isPubed=1 AND id IN(SELECT b.`channel_id` FROM `p_userrole` AS a RIGHT JOIN `p_role_channel` AS b ON a.`role_id`=b.`role_id`"+
            " WHERE a.`user_id`=:user_id)) ORDER BY sort";
   var paras={user_id:tUserInfo.id};
   var channelList= await this.dao.customQuery(sql,paras);
   if(channelList==null&&channelList.length==0){
     result.message="暂无渠道列表";
     return result;
   }
   for (var i = 0; i < channelList.length; i++) {
       var tItem= channelList[i];
       if(tItem!=null){
         //返回的服务项目列表
         var channel_item={
             channel_name:tItem.channelName,
             channel_code:tItem.channelCode,
             is_enabled:tItem.isEnabled,
             channel_shop_name:tItem.channelShopName
         };
         result.data.push(channel_item);
       }
   }
   return result;
  }
  //操作渠道不支持多店的用户渠道店铺
  async opUserChannelShop(channelItem,onlyCode,result){
    //支持多店，0否，1是*************添加不支持多店的渠道服务项目列表*******************
    if(channelItem.moreShop==0){
      //不支持多店p_user_channel表中判断当前渠道是否存在，已存在则已经添加过产品
      var tmpUserChannel= await this.channelSve.getUserChannel(channelItem.id,null);
      if(tmpUserChannel==null||tmpUserChannel.length==0){
        //创建用户渠道产品信息
        return await this.addUserChannelShopServiceItem(channelItem.id,channelItem.channelCode,onlyCode,result);
      }
    }
    return result;
  }
  //添加用户渠道商铺服务项目信息、参数（channelId渠道id、channel_code渠道编码、onlyCode店铺唯一码、result返回信息）
  async addUserChannelShopServiceItem(channelId,channel_code,onlyCode,result){
      var self=this;
      return self.db.transaction(async function (t){
          //店铺号
          var item=await self.getShopItem(onlyCode);
          if(item==null){
            result.code=-301;
            result.message="onlyCode参数有误,店铺信息为空";
            return result;
          }
          var sql="SELECT b.`channel_id` FROM `p_userrole` AS a RIGHT JOIN `p_role_channel` AS b ON a.`role_id`=b.`role_id`"+
                   " WHERE a.`user_id`=:user_id and b.`channel_id`=:channel_id";
          var paras={user_id:item.user_id,channel_id:channelId};
          var channelList= await self.dao.customQuery(sql,paras);
          if(channelList==null&&channelList.length==0){
            result.code=-302;
            result.message="onlyCode暂无渠道权限";
            return result;
          }
          var serviceItemList=await self.servicesitemDao.model.findAll({where:{channelCode:channel_code},raw:true});
          if(serviceItemList==null&&serviceItemList.length==0){
            result.code=-303;
            result.message="渠道服务项目为空";
            return result;
          }
          //获取发票税率
          var tmpInvoiceTaxRate= await self.pconfigSve.getInvoiceTaxRate();
          //添加店铺对应的服务项目列表
          var shopServiceItemList=[];
          for (var i = 0; i < serviceItemList.length; i++) {
            var r= serviceItemList[i];
            if(r!=null){
              //店主提成金额
              var tInvoiceTaxRate=await self.setPushMoney(r.guidePrice,r.publicExpense,r.platformCost,r.platformProfitRatio,tmpInvoiceTaxRate,"platformWork");
              if(tInvoiceTaxRate>=0){
                //添加店铺对应的服务项目
                var shopServiceItem={
                  shop_id:item.id,
                  servicesitem_id:r.id,
                  servicesitem_code:r.code,
                  app_id:item.app_id,
                  user_id:item.user_id,
                  userName:item.userName,
                  onlyCode:item.onlyCode,
                  customTotalAmount:r.guidePrice,//指导价
                  profitRatioTypeName:"委托作业",//分润类型名称
                  profitRatioType:"platformWork",//分润类型
                  customHotline:r.hotline,//咨询电话
                  customNotes:r.notes,//备注信息
                  pushMoney:tInvoiceTaxRate,//提成金额
                  shopNum:item.shopNum,
                  itemType:r.itemType,
                  channelCode:r.channelCode,
                };
                shopServiceItemList.push(shopServiceItem);
              }
            }
          }
        await self.channelSve.addUserChannel(item.user_id,channelId,t);
        await self.shopserviceitemDao.model.bulkCreate(shopServiceItemList,{transaction:t});
        return result;
    });
  }
  //开店操作
  async opOpenShop(obj){
     var openid = obj.openid;
     var shopname = obj.shopname;
     var result={
        code: 1,
        message: "success",
        shopNum:"",
    	  data: []
     };
     if(openid==null||openid==""||openid=="undefined"){
       result.code=-101;
       result.message="openid参数有误";
       return result;
     }
     if(shopname==null||shopname==""||shopname=="undefined"){
       result.code=-102;
       result.message="shopname参数有误";
       return result;
     }
     if(shopname.length>10){
       result.code=-102;
       result.message="店铺名称过长，长度为10";
       return result;
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
       result.code=-103;
       result.message="用户信息有误";
       return result;
     }
    var tUserInfo=JSON.parse(userInfo);
    if(tUserInfo.isShop!=null&&tUserInfo.isShop==1){
      result.code=-110;
      result.message="外星人，您已经是店主了!";
      return result;
    }
    //获取发票税率
    var tmpInvoiceTaxRate= await this.pconfigSve.getInvoiceTaxRate();
    var self=this;
    return self.db.transaction(async function (t){
        //店铺号
        var tShopNum=await self.orderSve.getUidStr(5,10);
        tShopNum=tShopNum+""+tUserInfo.id;
        await self.userDao.updateByWhere({isShop:1,shopNum:tShopNum},{where:{id:tUserInfo.id}},t);
        //添加p_shop表数据
        var shopParam={
                name:shopname,
                headUrl:"https://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_421101541149027122201821657712220181102165506.jpg",//tUserInfo.headUrl,
                app_id:tUserInfo.app_id,
                user_id:tUserInfo.id,
                userName:tUserInfo.userName,
                onlyCode:tUserInfo.onlyCode,
                userMobile:tUserInfo.mobile,
                shopNum:tShopNum
              };
        var item=await self.dao.create(shopParam,t);
        item=item.get({plain:true});
        //操作多渠道的信息
        var channelList= await self.channelSve.getChannelList(t);
        if(channelList!=null&&channelList.length>0){
          for (var j = 0; j < channelList.length; j++) {
            var tChannelItem= channelList[j];
            if(tChannelItem!=null){
              await self.opOpenShopChannel(tUserInfo,tmpInvoiceTaxRate,tChannelItem.channelCode,tShopNum,t);
            }
          }
        }
       //清空用户缓存
       await self.cacheManager["AppletUserinfoCache"].del(openid);
       result.shopNum=tShopNum;
       return result;
    });
  }

  async opOpenShopChannel(tUserInfo,tmpInvoiceTaxRate,channel_code,tShopNum,t){
    var serviceItemList=await this.servicesitemDao.model.findAll({where:{channelCode:channel_code},raw:true,transaction:t});
    if(serviceItemList==null&&serviceItemList.length==0){
      return;
    }
    //添加店铺对应的服务项目列表
    var shopServiceItemList=[];
    for (var i = 0; i < serviceItemList.length; i++) {
      var r= serviceItemList[i];
      if(r!=null){
        //店主提成金额
        var tInvoiceTaxRate=await this.setPushMoney(r.guidePrice,r.publicExpense,r.platformCost,r.platformProfitRatio,tmpInvoiceTaxRate,"platformWork");
        if(tInvoiceTaxRate>=0){
          //添加店铺对应的服务项目
          var shopServiceItem={
            shop_id:tUserInfo.id,
            servicesitem_id:r.id,
            servicesitem_code:r.code,
            app_id:tUserInfo.app_id,
            user_id:tUserInfo.id,
            userName:tUserInfo.userName,
            onlyCode:tUserInfo.onlyCode,
            customTotalAmount:r.guidePrice,//指导价
            profitRatioTypeName:"委托作业",//分润类型名称
            profitRatioType:"platformWork",//分润类型
            customHotline:r.hotline,//咨询电话
            customNotes:r.notes,//备注信息
            pushMoney:tInvoiceTaxRate,//提成金额
            shopNum:tShopNum,
            itemType:r.itemType,
            channelCode:r.channelCode,
          };
          shopServiceItemList.push(shopServiceItem);
        }
      }
    }
   await this.shopserviceitemDao.model.bulkCreate(shopServiceItemList,{transaction:t});
  }
  //修改店铺信息
  async putShopInfo(obj){
     var openid = obj.openid;
     var shopname = obj.shop_name;
     var head_url = obj.head_url;
     var user_mobile = obj.user_mobile;
     var presentationUrl=obj.shop_presentationUrl;
     var result={
        code: 1,
        message: "success",
        shopNum:"",
        data: {}
     };
     if(openid==null||openid==""||openid=="undefined"){
       result.code=-101;
       result.message="openid参数有误";
       return result;
     }
     if(shopname==null||shopname==""||shopname=="undefined"){
       result.code=-102;
       result.message="shopname参数有误";
       return result;
     }
     if(shopname.length>10){
       result.code=-102;
       result.message="店铺名称过长，长度为10";
       return result;
     }
     if(head_url==null||head_url==""||head_url=="undefined"){
       result.code=-102;
       result.message="head_url参数有误";
       return result;
     }
     if(user_mobile==null||user_mobile==""||user_mobile=="undefined"){
       result.code=-102;
       result.message="user_mobile参数有误";
       return result;
     }
     if(presentationUrl==null||presentationUrl==""||presentationUrl=="undefined"){
       result.code=-102;
       result.message="presentationUrl参数有误参数有误";
       return result;
     }

     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
       result.code=-103;
       result.message="用户信息有误";
       return result;
     }
    var tUserInfo=JSON.parse(userInfo);
    if(tUserInfo.isShop!=null&&tUserInfo.isShop!=1){
      result.code=-104;
      result.message="你还不是店主，请您先开店";
      return result;
    }
    var shopInfo=await this.getShopItem(tUserInfo.onlyCode);
    if(shopInfo==null){
      result.code=-104;
      result.message="店铺信息为空";
      return result;
    }
    var customerObj={name:shopname,headUrl:head_url,userMobile:user_mobile,presentationUrl:presentationUrl};
    var putSqlWhere={where:{id:shopInfo.id}};
    await this.dao.updateByWhere(customerObj,putSqlWhere);
    result.data.shop_name=shopname;
    result.data.head_url=head_url;
    result.data.user_mobile=user_mobile;
    result.data.shop_num=shopInfo.shopNum;
    result.data.created_at=shopInfo.created_at;
    result.data.shop_presentationUrl=presentationUrl;
    return result;
  }
  //needh5获取相应产品信息列表
  async getServiceItemListForNeedh5(obj){
    var tOnlycode = obj.shopOnlyCode;
    var itemtype = obj.itemtype;
    var channel = obj.channel;
    //是否推荐
    var recommend = obj.recommend==null||obj.recommend==""||obj.recommend=="undefined"?0:obj.recommend;
    var result={
       code: 1,
       message: "success",
       data: []
    };

    if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
      result.code=-102;
      result.message="shopOnlyCode参数有误";
      return result;
    }
    if(itemtype==null||itemtype==""||itemtype=="undefined"){
      itemtype="all";
    }
    if(channel==null||channel==""||channel=="undefined"){
      channel="wssy";
    }
    var paras={onlyCode:tOnlycode,channelCode:channel};
    var sql="SELECT b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,b.`channelCode`,a.`onlyCode`,b.`code`,b.`name`,b.`shortDesc`,b.`mobileContentImg`,b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,"+
        "b.`publicExpense`,b.`platformCost`,b.`platformProfitRatio`,a.`customHotline`,b.`webPic`,b.`mobilePic`,"+
        "a.`customTotalAmount`,a.`profitRatioTypeName`,a.`profitRatioType`,a.`pushMoney`"+
        "FROM `h_shop_service_item` AS a,`cms_servicesitem` AS b"+
      " WHERE a.`servicesitem_id`=b.`id` and a.`deleted_at` IS NULL and b.`isPubed`=1 and a.`onlyCode`=:onlyCode and a.`channelCode`=:channelCode ";
      if(itemtype!="all"){
        sql=sql+" and b.`itemType`=:itemType";
        paras.itemType=itemtype;
      }
      if(recommend==1){
        //取得推荐列表信息
        sql=sql+" and b.`isRecommend`='1'";
      }
      sql=sql+" order by sort asc,b.`created_at` desc";
    var serviceItemList= await this.dao.customQuery(sql,paras);
    if(serviceItemList==null||serviceItemList.length==0){
      result.message="暂无服务项目列表";
      return result;
    }
    for (var i = 0; i < serviceItemList.length; i++) {
        var tItem= serviceItemList[i];
        if(tItem!=null){
          //返回的服务项目列表
          var service_item={
                 service_item:{
                    only_code:tItem.onlyCode,
                    code:tItem.code,
                    name:tItem.name,//名称
                    web_pic:tItem.webPic,
                    mobile_pic:tItem.mobilePic,
                    hotline:tItem.customHotline,//咨询电话
                    //h_shop_service_item表中信息
                    total_amount:tItem.customTotalAmount,//单价总额
                    channel_type:tItem.channelCode,//渠道编码
                    services_reduced_rate:tItem.servicesReducedRate/100,//服务的折扣率
                    is_negotiable:tItem.isNegotiable,//是否面议
                    is_seckill:tItem.isSeckill,//是否秒杀
                    seckill_end_time:tItem.seckillEndTime,//秒杀结束时间
                    answer_conent:tItem.answerConent,//问答
                    mobile_content_img:tItem.mobileContentImg//介绍
               }
          };
          result.data.push(service_item);
        }
    }
   return result;
  }
  //获取产品列表信息--usertype=1用户，usertype=2店主，recommend是否推荐（有值则是获取推荐列表）
  async getServiceItemList(obj){
      var openid = obj.openid;
      var tOnlycode = obj.onlycode;
      var usertype = obj.usertype;
      var itemtype = obj.itemtype;
      var channel = obj.channel;
      var pageSize=obj.page_size;
      //当前第几页,从1开始
      var currentPage=obj.current_page;
      if(pageSize==null||pageSize==""||pageSize=="undefined"){
        pageSize="";
      }
      if(currentPage==null||currentPage==""||currentPage=="undefined"){
        currentPage="";
      }
      //是否推荐
      var recommend = obj.recommend==null||obj.recommend==""||obj.recommend=="undefined"?0:obj.recommend;
      //搜索商标交易-商标大类信息
      var nclOneCodesArry = obj.ncl_one_codes==null||obj.ncl_one_codes==""||obj.ncl_one_codes=="undefined"?[]:obj.ncl_one_codes;
      //搜索商标交易-商标名称信息
      var tName = obj.name==null||obj.name==""||obj.name=="undefined"?"":obj.name;
      var result={
         code: 1,
         message: "success",
         data: []
      };
      if(itemtype==null||itemtype==""||itemtype=="undefined"){
        itemtype="all";
      }
      if(channel==null||channel==""||channel=="undefined"){
        channel="hhr";
      }
      if(openid==null||openid==""||openid=="undefined"){
        result.code=-101;
        result.message="openid参数有误";
        return result;
      }
      if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
        result.code=-102;
        result.message="onlycode参数有误";
        return result;
      }
      if(usertype==null||usertype==""||usertype=="undefined"){
        result.code=-103;
        result.message="usertype参数有误";
        return result;
      }
      if(usertype!=1&&usertype!=2){
        result.code=-104;
        result.message="usertype参数有误";
        return result;
      }
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
        result.code=-105;
        result.message="用户信息有误";
        return result;
      }
      //判断渠道
      var channelItem=await this.channelSve.getChannelItem(channel);
      if(channelItem==null){
        result.code=-106;
        result.message="渠道信息有误";
        return result;channelCode
      }
      //店主获取服务项目列表,对渠道的操作--usertype=1用户，usertype=2店主
      if(usertype==2){
        var tUserInfo=JSON.parse(userInfo);
        var opResult=await this.opUserChannelShop(channelItem,tOnlycode,result);
        if(opResult.code!=1){
          return opResult;
        }
      }
      var paras={onlyCode:tOnlycode,channelCode:channel};
      var sql="SELECT b.`sellStatus`,b.`sellStatusName`,b.`authorOnlyCode`,b.`priceRangeMin`,b.`priceRangeMax`,b.`nclOneCodes`,b.`tmExpirationDate`,"+
              "b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,b.`channelCode`,a.`onlyCode`,b.`code`,b.`name`,b.`shortDesc`,"+
              "b.`mobileContentImg`,b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,"+
              "b.`publicExpense`,b.`platformCost`,b.`platformProfitRatio`,a.`customHotline`,b.`webPic`,b.`mobilePic`,"+
              "a.`customTotalAmount`,a.`profitRatioType`,a.`pushMoney`"+
              "FROM `h_shop_service_item` AS a,`cms_servicesitem` AS b"+
        " WHERE a.`servicesitem_id`=b.`id` and b.`deleted_at` IS NULL and b.`isPubed`=1 and a.`onlyCode`=:onlyCode and a.`channelCode`=:channelCode ";

      //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
      //IE标（yzc）
      if(this.isCheckChannelArry(channel)){
        //,a.`profitRatioType`,a.`pushMoney`
        sql="SELECT b.`sellStatus`,b.`sellStatusName`,b.`authorOnlyCode`,b.`priceRangeMin`,b.`priceRangeMax`,b.`nclOneCodes`,b.`tmExpirationDate`,"+
                "b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,b.`channelCode`,b.`code`,b.`name`,b.`shortDesc`,"+
                "b.`mobileContentImg`,b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,"+
                "b.`publicExpense`,b.`platformCost`,b.`platformProfitRatio`,b.`hotline` AS `customHotline`,b.`webPic`,b.`mobilePic`,"+
                "b.`guidePrice` AS `customTotalAmount`"+
                " FROM `cms_servicesitem` AS b"+
          " WHERE b.`deleted_at` IS NULL and b.`isPubed`=1 and b.`channelCode`=:channelCode ";
          paras={channelCode:channel};
      }

      if(itemtype!="all"){
        sql=sql+" and b.`itemType`=:itemType";
        paras.itemType=itemtype;
      }
      if(recommend==1){
        //取得推荐列表信息
        sql=sql+" and b.`isRecommend`='1'";
      }
      //添加搜索商标名称条件
      if(tName!=""){
        sql=sql+" and b.`name` like '%"+tName+"%'";
      }
      //添加搜索商标大类条件
      if(nclOneCodesArry.length>0){
        sql=sql+" and b.`nclOneCodes` in("+nclOneCodesArry.join(',')+")";
      }
      sql=sql+" order by sort asc,b.`created_at` desc";

      if(pageSize!=""&&currentPage!=""){
        var tPageSize=Number(pageSize);
        var tCurrentPage=Number(currentPage);
        if(tCurrentPage<1){
          tCurrentPage=1;
        }
        if(tPageSize>50){
          tPageSize=50;
        }
        if(tPageSize<1){
          tPageSize=1;
        }
        sql=sql+" LIMIT "+tPageSize+" OFFSET "+(tCurrentPage - 1) * tPageSize;
      }

      var serviceItemList= await this.dao.customQuery(sql,paras);
      if(serviceItemList==null||serviceItemList.length==0){
        result.message="暂无服务项目列表";
        return result;
      }
      var self=this;
      var tInvoiceTaxRate= await this.pconfigSve.getInvoiceTaxRate();
      for (var i = 0; i < serviceItemList.length; i++) {
          var tItem= serviceItemList[i];
          if(tItem!=null){
            //返回的服务项目列表
            var service_item={
                   service_item:{
                      only_code:tOnlycode,//店铺唯一码
                      code:tItem.code,//编码channelCode
                      name:tItem.name,//名称
                      web_pic:tItem.webPic,//web端图片
                      mobile_pic:tItem.mobilePic,//移动端图片
                      channel_type:tItem.channelCode,//渠道编码
                      services_reduced_rate:tItem.servicesReducedRate/100,//服务的折扣率
                      is_negotiable:tItem.isNegotiable,//是否面议
                      is_seckill:tItem.isSeckill,//是否秒杀
                      seckill_end_time:tItem.seckillEndTime,//秒杀结束时间
                      //h_shop_service_item表中信息
                      total_amount:tItem.customTotalAmount,//单价总额
                      hotline:tItem.customHotline//咨询电话
                 }
            };
            if(usertype==2){
              service_item.service_item.platform_work_floor_price=tItem.platformWorkFloorPrice;//委托作业底价
              service_item.service_item.self_work_floor_price=tItem.selfWorkFloorPrice;//自助作业底价
              service_item.service_item.guide_price=tItem.guidePrice;//指导价

              //多店支持
              service_item.service_item.public_expense=tItem.publicExpense;//项目官费
              service_item.service_item.platform_cost=tItem.platformCost;//平台费用
              service_item.service_item.platform_profit_ratio=tItem.platformProfitRatio;//平台的分成比率
              service_item.service_item.invoice_ratio=tInvoiceTaxRate;//发票税率

              //h_shop_service_item表中信息====//不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
              if(!self.isCheckChannelArry(channel)){
                  service_item.service_item.profit_ratio_type=tItem.profitRatioType;//"platformWork":"委托作业","selfWork":"自助作业"
                  service_item.service_item.push_money=tItem.pushMoney;//提成金额
              }
            }
            //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
            if(self.isCheckChannelArry(channel)){
              service_item.service_item.sell_status=tItem.sellStatus;//销售状态-商标交易
              service_item.service_item.sell_statusName=tItem.sellStatusName;//销售状态名称-商标交易
              service_item.service_item.author_only_code=tItem.authorOnlyCode;//发布者唯一码-商标交易
              service_item.service_item.price_range_min=tItem.priceRangeMin;//价格区间最小值-商标交易
              service_item.service_item.price_range_max=tItem.priceRangeMax;//价格区间最大值-商标交易
              service_item.service_item.ncl_one_codes=tItem.nclOneCodes;//尼斯大类-商标交易
              service_item.service_item.tm_expiration_date=tItem.tmExpirationDate;//商标到期时间-商标交易
            }
            result.data.push(service_item);
          }
      }
     return result;
  }
  //获取产品信息--usertype=1用户，usertype=2店主
  async getServiceItemDetails(obj){
      var openid = obj.openid;
      var tOnlycode = obj.onlycode;
      var usertype = obj.usertype;
      var tCode = obj.code;
      var channel = obj.channel;
      var result={
         code: 1,
         message: "success",
         data: {}
      };
      if(channel==null||channel==""||channel=="undefined"){
        channel="hhr";
      }
      if(openid==null||openid==""||openid=="undefined"){
        result.code=-101;
        result.message="openid参数有误";
        return result;
      }
      if(channel=="hhr"){
        if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
          result.code=-102;
          result.message="onlycode参数有误";
          return result;
        }
      }
      if(usertype==null||usertype==""||usertype=="undefined"){
        result.code=-103;
        result.message="usertype参数有误";
        return result;
      }
      if(usertype!=1&&usertype!=2){
        result.code=-104;
        result.message="usertype参数有误";
        return result;
      }
      if(tCode==null||tCode==""||tCode=="undefined"){
        result.code=-105;
        result.message="code参数有误";
        return result;
      }
      var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
      if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
        result.code=-106;
        result.message="用户信息有误";
        return result;
      }
      //判断渠道
      var channelItem=this.channelSve.getChannelItem(channel);
      if(channelItem==null){
        result.code=-107;
        result.message="渠道信息有误";
        return result;
      }
      var paras={onlyCode:tOnlycode,code:tCode,channelCode:channel};
      var sql="SELECT b.`sellStatus`,b.`sellStatusName`,b.`authorOnlyCode`,b.`priceRangeMin`,b.`priceRangeMax`,b.`nclOneCodes`,b.`tmExpirationDate`,"+
              "b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,a.`onlyCode`,b.`channelCode`,b.`code`,b.`name`,b.`shortDesc`,"+
              "b.`mobileContentImg`,b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,b.`publicExpense`,b.`platformCost`,"+
              "b.`platformProfitRatio`,a.`customHotline`,a.`customTotalAmount`,a.`pushMoney`,b.`webPic`,b.`mobilePic`,a.`customTotalAmount`,a.`profitRatioTypeName`,"+
              "a.`profitRatioType`"+
              "FROM `h_shop_service_item` AS a,`cms_servicesitem` AS b"+
              " WHERE a.`servicesitem_id`=b.`id` and b.`deleted_at` IS NULL and b.`isPubed`=1 and a.`onlyCode`=:onlyCode and b.`code`=:code and a.`channelCode`=:channelCode ";
      //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
      //IE标（yzc）
      if(this.isCheckChannelArry(channel)){
        //,a.`profitRatioType`,a.`pushMoney`
        sql="SELECT b.`sellStatus`,b.`sellStatusName`,b.`authorOnlyCode`,b.`priceRangeMin`,b.`priceRangeMax`,b.`nclOneCodes`,b.`tmExpirationDate`,"+
                "b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,b.`channelCode`,b.`code`,b.`name`,b.`shortDesc`,"+
                "b.`mobileContentImg`,b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,"+
                "b.`publicExpense`,b.`platformCost`,b.`platformProfitRatio`,b.`hotline` AS `customHotline`,b.`webPic`,b.`mobilePic`,"+
                "b.`guidePrice` AS `customTotalAmount`"+
                " FROM `cms_servicesitem` AS b"+
          " WHERE b.`deleted_at` IS NULL and b.`isPubed`=1 and b.`code`=:code and b.`channelCode`=:channelCode ";
          paras={code:tCode,channelCode:channel};
      }
      var serviceItemList= await this.dao.customQuery(sql,paras);
      var resultTotal=serviceItemList.length;
      if(serviceItemList==null||resultTotal==0){
        result.message="暂无服务项目详情信息";
        return result;
      }
      var tItem=serviceItemList[0];
      //返回的服务项目列表
      result.data.only_code=tOnlycode;
      result.data.code=tItem.code;
      result.data.name=tItem.name;
      result.data.short_desc=tItem.shortDesc;
      result.data.web_pic=tItem.webPic;
      result.data.mobile_pic=tItem.mobilePic;
      result.data.mobile_content_img=tItem.mobileContentImg;
      result.data.answer_conent=tItem.answerConent;
      result.data.hotline=tItem.customHotline;
      //h_shop_service_item表中信息
      //自定义总额
      result.data.total_amount=tItem.customTotalAmount;
      result.data.channel_type=tItem.channelCode;//渠道编码
      result.data.services_reduced_rate=tItem.servicesReducedRate/100;//服务的折扣率
      result.data.is_negotiable=tItem.isNegotiable;//是否面议
      result.data.is_seckill=tItem.isSeckill;//是否秒杀
      result.data.seckill_end_time=tItem.seckillEndTime;//秒杀结束时间

      if(usertype==2){
        result.data.platform_work_floor_price=tItem.platformWorkFloorPrice;//委托作业底价
        result.data.self_work_floor_price=tItem.selfWorkFloorPrice;//自助作业底价
        result.data.guide_price=tItem.guidePrice;//指导价

        //支持多店
        result.data.public_expense=tItem.publicExpense;//项目官费
        result.data.platform_cost=tItem.platformCost;//平台费用
        result.data.platform_profit_ratio=tItem.platformProfitRatio;//平台的分成比率
        result.data.invoice_ratio=await this.pconfigSve.getInvoiceTaxRate();//发票税率
        //h_shop_service_item表中信息====//不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
        if(!this.isCheckChannelArry(channel)){
            //h_shop_service_item表中信息
            result.data.profit_ratio_type=tItem.profitRatioType;//"platformWork":"委托作业","selfWork":"自助作业"
            result.data.push_money=tItem.pushMoney;//提成金额
        }
      }
      //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
      if(this.isCheckChannelArry(channel)){
        result.data.sell_status=tItem.sellStatus;//销售状态-商标交易
        result.data.sell_statusName=tItem.sellStatusName;//销售状态名称-商标交易
        result.data.author_only_code=tItem.authorOnlyCode;//发布者唯一码-商标交易
        result.data.price_range_min=tItem.priceRangeMin;//价格区间最小值-商标交易
        result.data.price_range_max=tItem.priceRangeMax;//价格区间最大值-商标交易
        result.data.ncl_one_codes=tItem.nclOneCodes;//尼斯大类-商标交易
        result.data.tm_expiration_date=tItem.tmExpirationDate;//商标到期时间-商标交易
      }
      // //usertype=1用户，usertype=2店主,且channelItem支持多店
      // if(usertype==2&&channelItem.moreShop==1){
      //   result.data.public_expense=tItem.publicExpense;//项目官费
      //   result.data.platform_cost=tItem.platformCost;//平台费用
      //   result.data.platform_profit_ratio=tItem.platformProfitRatio;//平台的分成比率
      //   result.data.invoice_ratio=await this.pconfigSve.getInvoiceTaxRate();//发票税率
      //   //h_shop_service_item表中信息
      //   result.data.profit_ratio_type=tItem.profitRatioType;//"platformWork":"委托作业","selfWork":"自助作业"
      //   result.data.push_money=tItem.pushMoney;//提成金额
      //   result.data.services_reduced_rate=tItem.servicesReducedRate;//服务的折扣率
      //   result.data.is_negotiable=tItem.isNegotiable;//是否面议
      // }
      return result;
  }
  //获取用户的利润
  //参数:total_amount总额、public_expense项目官费、platform_cost平台费用、platform_profit_ratio平台的分成比率、invoice_ratio发票税率
  //profit_ratio_type分润类型，platformWork委托作业，selfWork自助作业
  async setPushMoney(total_amount,public_expense,platform_cost,platform_profit_ratio,invoice_ratio,profit_ratio_type){
      total_amount=parseFloat(total_amount);
      public_expense=parseFloat(public_expense);
      platform_cost=parseFloat(platform_cost);
      platform_profit_ratio=parseFloat(platform_profit_ratio);
      invoice_ratio=parseFloat(invoice_ratio);
      var tInvoiceTotal=total_amount*invoice_ratio/100;
      var sTotal=0;
      // console.log("profit_ratio_type-----------------------y111");
      // console.log(profit_ratio_type);
      // console.log("总额........"+total_amount);
      // console.log("官费------"+public_expense);
      // console.log("平台费------"+platform_cost);
      // console.log("发票税率------"+tInvoiceTotal);
      if(profit_ratio_type=="selfWork"){
        //自助作业底价：输入的价格必须大于自助作业底价，可获提成：输入金额-项目官费-平台费用-输入金额*发票税率
        sTotal= total_amount-public_expense-platform_cost-tInvoiceTotal;
      }
      else if(profit_ratio_type=="platformWork") {
        //委托作业：输入的价格必须大于委托作业底价，可获提成：(输入金额-项目官费-平台费用)*平台的分成比率
        if(platform_profit_ratio==0){
          sTotal= (total_amount-public_expense-platform_cost-tInvoiceTotal);
        }
        else if(platform_profit_ratio>0&&platform_profit_ratio<100) {
          sTotal= (total_amount-public_expense-platform_cost-tInvoiceTotal)*(100-platform_profit_ratio)/100;
        }
      }
      return parseFloat(sTotal);
  }
  //创建订单
  /*
   规则1：ordertype=2自主订单
      参数:
      {
    		"openid": "31008699",
    		"code": "10995",
    		"onlycode":"",
    		"num": 1,
        "ordertype":2
    	}
   规则2：ordertype=16代客下单
      参数:
      {
    		"openid": "31008699",
    		"code": "10995",
    		"onlycode":"",
    		"num": 1,
        "ordertype":16
        "customer_contact_info":
          {
          	"customer_type":""
          	"ent_name":""
          	"customer_contact":""
          	"mobile":""
          }
    	}
  */
  async createOrder(obj){
    var self=this;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    var openid = obj.openid;
    var tCode = obj.code;
    var tOnlycode = obj.onlycode;
    var num = obj.num;
    var payType = obj.pay_type;
    var channel = obj.channel;
    var offlinePayDocumentUrl =obj.offline_pay_document==null||obj.offline_pay_document==""||obj.offline_pay_document=="undefined"?null:obj.offline_pay_document;
    if(channel==null||channel==""||channel=="undefined"){
      channel="hhr";
    }
    //传递过来的订单总额（代客下单时由此值）
    var tTotalSum=obj.total_sum;
    if(tTotalSum==null||tTotalSum==""||tTotalSum=="undefined"){
      tTotalSum=0;
    }
    if(payType==null||payType==""||payType=="undefined"){
      payType="wx";
    }
    if(payType!="wx"&&payType!="offline"){
      result.code=-101;
      result.message="pay_type参数有误";
      return result;
    }
    if(payType=="offline"){
      if(offlinePayDocumentUrl==null){
        result.code=-102;
        result.message="offline_pay_document参数有误";
        return result;
      }
    }
    //订单类型,"2"自主订单、"16"代客下单
    var tOrderType = obj.ordertype;
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-103;
      result.message="openid参数有误";
      return result;
    }
    if(tCode==null||tCode==""||tCode=="undefined"){
      result.code=-104;
      result.message="code参数有误";
      return result;
    }
    if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
      result.code=-105;
      result.message="onlycode参数有误";
      return result;
    }
    if(num==null||num==""||num=="undefined"||Number(num)<=0){
      result.code=-106;
      result.message="num参数有误";
      return result;
    }
    if(tOrderType==null||tOrderType==""||tOrderType=="undefined"){
      result.code=-107;
      result.message="ordertype参数有误";
      return result;
    }
    if(tOrderType!="2"&&tOrderType!="16"){
      result.code=-108;
      result.message="ordertype参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-109;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    //判断渠道
    var channelItem=this.channelSve.getChannelItem(channel);
    if(channelItem==null){
      result.code=-110;
      result.message="渠道信息有误";
      return result;
    }
    //代客下单，联系人信息
    var customerContactInfo=null;
    //tOrderType：2用户下单，16代客下单
    if(tOrderType=="16"){
      if(tTotalSum<=0){
        result.code=-150;
        result.message="订单金额有误，请修改价格后进行重新下单";
        return result;
      }
      customerContactInfo=obj.customer_contact_info;
      if(customerContactInfo==null||customerContactInfo==""||customerContactInfo=="undefined"){
        result.code=-111;
        result.message="代客下单信息有误";
        return result;
      }
      if(customerContactInfo.customer_type!="ent"&&customerContactInfo.customer_type!="person"){
        result.code=-112;
        result.message="customer_type参数有误";
        return result;
      }
      if(customerContactInfo.customer_type=="ent"){
        if(customerContactInfo.ent_name==null||customerContactInfo.ent_name==""||customerContactInfo.ent_name=="undefined"){
          result.code=-113;
          result.message="企业名称不能为空";
          return result;
        }
      }
      if(customerContactInfo.customer_contact==null||customerContactInfo.customer_contact==""||customerContactInfo.customer_contact=="undefined"){
        result.code=-114;
        result.message="联系人不能为空";
        return result;
      }
      if(customerContactInfo.mobile==null||customerContactInfo.mobile==""||customerContactInfo.mobile=="undefined"){
        result.code=-115;
        result.message="手机号不能为空";
        return result;
      }
    }
    return this.db.transaction(async function (t){
        var createOrderNum=await self.orderSve.getCreateOrderNum();//====================订单号生成
        var sql="SELECT b.`isSeckill`,b.`seckillEndTime`,b.`servicesReducedRate`,b.`isNegotiable`,a.`onlyCode`,a.`shop_id`,a.`shopNum`,b.`itemType`,b.`channelCode`,b.`code`,b.`name`,b.`shortDesc`,b.`mobileContentImg`,"+
                "b.`answerConent`,b.`platformWorkFloorPrice`,b.`selfWorkFloorPrice`,b.`guidePrice`,b.`publicExpense`,b.`platformCost`,b.`platformProfitRatio`,"+
                "a.`customHotline`,b.`webPic`,b.`mobilePic`,a.`customTotalAmount`,a.`profitRatioTypeName`,a.`profitRatioType`,b.`nclOneCodesNum`,b.`serviceCharge`"+
                " FROM `h_shop_service_item` AS a,`cms_servicesitem` AS b"+
                " WHERE a.`servicesitem_id`=b.`id` and a.`onlyCode`=:onlyCode and b.`code`=:code and a.`channelCode`=:channelCode";
        var serviceItemList= await self.dao.customQuery(sql,{onlyCode:tOnlycode,code:tCode,channelCode:channel});
        if(serviceItemList==null||serviceItemList.length==0){
          result.code=-116;
          result.message="服务项目为空!";
          return result;
        }
        var tItem=serviceItemList[0];
        if(tOrderType=="2"&&tItem.isNegotiable==1){
          result.code=-117;
          result.message="亲，面议产品不能下单，请咨询服务人员";
          return result;
        }
        //判断是否是秒杀
        if(tItem.isSeckill==1){
          var t1=self.buildDate(tItem.seckillEndTime);
          var t2 = Date.now();
          var interval = (t1-t2);
          if(interval<0){
            result.code=-170;
            result.message="亲，产品秒杀时间已过";
            return result;
          }
        }
        if(tOrderType=="16"){
          var tOrderPrice=parseFloat(totalSum)/parseFloat(num);
          if(tItem.profitRatioType=="platformWork"){
            if(tOrderPrice<tItem.platformWorkFloorPrice){
              result.code=-150;
              result.message="订单金额信息有误，请修改价格后进行重新下单!";
              return result;
            }
          }
          else if(tItem.profitRatioType=="selfWork"){
            if(tOrderPrice<tItem.selfWorkFloorPrice){
              result.code=-150;
              result.message="订单金额信息有误，请修改价格后进行重新下单!!";
              return result;
            }
          }
        }
        //获取发票税率
        var tmpInvoiceTaxRate= await self.pconfigSve.getInvoiceTaxRate();
        //获取推荐人分成比率（如：用户扣除平台的分成最终的服务费为70，字段值30，则平台的利润为21=70*(30/100)，剩下的则为推荐用户服务费）
        var tmpReferrerProfitRatio= await self.pconfigSve.getReferrerProfitRatio();

        //平台的分成比率（如：服务费100，字段值30，则平台的利润为30=100*(30/100)，剩下的则为用户服务费）
        var platform_profitRatio=Number(tItem.platformProfitRatio);

        var sum_ncl_total_public_expense=Number(tItem.publicExpense)*Number(num);//官费总额
        var sum_ncl_service_charge=tItem.serviceCharge==0||tItem.serviceCharge==null?0:Number(tItem.serviceCharge)*Number(num);//服务费总额
        var total_platform_cost=Number(tItem.platformCost)*Number(num);//平台使用费总额
        //tOrderType：2用户下单，16代客下单
        var totalSum=tOrderType=="16"?parseFloat(tTotalSum):parseFloat(tItem.customTotalAmount)*Number(num);//总额（平台费用+服务费+官费+发票税费）,customTotalAmount为服务项目总价
        //是否有折扣率
        if(tItem.servicesReducedRate!=100){
          if(tItem.servicesReducedRate>100||tItem.servicesReducedRate<1){
            result.code=-160;
            result.message="折扣率信息有误!";
            return result;
          }
          totalSum=totalSum*tItem.servicesReducedRate/100;
        }
        var sum_invoice_taxes=totalSum*(tmpInvoiceTaxRate/100);//发票税费总额（订单总额*7%）
        var referrer_profit=0;//推荐人利润
        var platform_profit=0;//平台利润

        if(tItem.profitRatioType=="platformWork"){
          //委托作业(含税)：平台可获利润：(成单金额-项目官费-平台费用-成单金额*发票税率)*平台的分成比率/100
          platform_profit=(totalSum-sum_ncl_total_public_expense-total_platform_cost-sum_invoice_taxes)*platform_profitRatio/100;
        }
        //店主利润,来源为移动商城有此值，分润类型，platformWork委托作业，selfWork自助作业
        var shopkeeper_profit=await self.setPushMoney(totalSum,sum_ncl_total_public_expense,total_platform_cost,platform_profitRatio,tmpInvoiceTaxRate,tItem.profitRatioType);

        if(platform_profit<0){
          result.code=-150;
          result.message="订单金额信息有误，请修改价格后进行重新下单!!!";
          return result;
        }
        if(shopkeeper_profit<0){
          result.code=-150;
          result.message="订单金额信息有误，请修改价格后进行重新下单!!!!";
          return result;
        }
        //店铺信息
        var shopItem=await self.getShopItem(tOnlycode);
        //新建订单表--------------------开始--------------------------
        var orderObj={
                      userName:tUserInfo.userName,
                      orderNum:createOrderNum,
                      orderType:tOrderType,
                      app_id:tUserInfo.app_id,
                      user_id:tUserInfo.id,
                      onlyCode:tUserInfo.onlyCode,
                      nickName:tUserInfo.nickName,
                      customerType:customerContactInfo!=null?customerContactInfo.customer_type:null,//申请人类型
                      customerContact:customerContactInfo!=null?customerContactInfo.customer_contact:tUserInfo.userName,//联系人
                      customerMobile:customerContactInfo!=null?customerContactInfo.mobile:tUserInfo.mobile,//联系电话
                      applyName:customerContactInfo!=null&&customerContactInfo.customer_type=="ent"?customerContactInfo.ent_name:
                                customerContactInfo!=null?customerContactInfo.customer_contact:null,//申请人
                      remark:customerContactInfo!=null?customerContactInfo.remark:null,//订单备注
                      itemCode:tItem.code,
                      itemName:tItem.name,
                      itemType:tItem.itemType,
                      webPic:tItem.webPic,
                      mobilePic:tItem.mobilePic,
                      itemOrderNum:Number(num),
                      itemOrderConsumeNum:0,
                      nclOneCodesNum:tItem.nclOneCodesNum,
                      orderSourceType:"2",//订单来源类型，1PC，2移动商城，4渠道方
                      orderStatus:payType=="offline"?"64":"1",//订单状态，1未付款，2订单取消，4付款成功，8退款处理中，16已退款、32已提报、64待审核
                      profitRatioType:tItem.profitRatioType,//来源为移动商城有此值，分润类型，platformWork委托作业，selfWork自助作业
                      totalPublicExpense:sum_ncl_total_public_expense,//官费总额
                      totalServiceCharge:sum_ncl_service_charge,//服务费总额
                      totalPlatformCost:total_platform_cost,//平台费用总额
                      totalInvoiceTaxes:sum_invoice_taxes,//发票税费总额（订单总额*7%）
                      totalSum:totalSum,//订单总额（平台费用+服务费+官费+发票税费+个人利润+平台利润）
                      platformProfit:platform_profit,//平台利润
                      userProfit:0,//用户利润-移动商城为0

                      platformProfitRatio:platform_profitRatio,//平台的分成比率
                      referrerProfit:referrer_profit,//推荐人利润
                      referrerProfitRatio:tmpReferrerProfitRatio,//推荐人的分成比率
                      shopkeeperProfit:shopkeeper_profit,
                      shopOnlyCode:tOnlycode,
                      shopNum:shopItem==null?"":shopItem.shopNum,
                      customerNum:obj.customer_num==null||obj.customer_num==""||obj.customer_num=="undefined"?0:obj.customer_num,
                      channelCode:tItem.channelCode,
                      paymentPlatformType:payType,
                      offlinePayDocument:offlinePayDocumentUrl
                    };
        if(tItem.channelCode!="boss"){
          //推荐人分润
          if(tUserInfo.account.referrerOnlyCode!=null&&tUserInfo.account.referrerOnlyCode!=""){
            //首次下单 拥有推荐人 建立推荐人分润
             var o={unionId:tUserInfo.account.referrerOnlyCode}
             var user2 = await self.userDao.findOne(o);//推荐人信息
             user2=user2.dataValues;
             if(user2!=null){
               orderObj.referrerProfit=total_platform_cost*(tmpReferrerProfitRatio/100);//推荐人利润
               orderObj.referrerOnlyCode=tUserInfo.account.referrerOnlyCode;
               orderObj.referrerAppId=user2.app_id;
               orderObj.referrerUserId=user2.id;
               orderObj.referrerUserName=user2.userName;
               orderObj.referrerNickName=user2.nickName;
             }
           }
        }
        var orderInfo= await self.orderSve.dao.create(orderObj,t);

        var customerObj={order_id:orderInfo.id,orderNum:orderObj.orderNum,customerContact:customerContactInfo?customerContactInfo.customer_contact:tUserInfo.userName,
                         mobile:customerContactInfo?customerContactInfo.mobile:tUserInfo.mobile};
        var customer=await self.tmcustomerinfoDao.create(customerObj,t);//订单联系人

        if(payType=='offline'){
          var orderflowObj={app_id:tUserInfo.app_id,user_id:tUserInfo.id,userName:tUserInfo.userName,nickName:tUserInfo.nickName,
                            orderNum:orderObj.orderNum,opContent:"创建订单"};
          var orderflow = await self.orderflowDao.create(orderflowObj,t);//订单流程
        }
        orderInfo=orderInfo.get({plain:true});
        //新建订单表--------------------结束--------------------------
        result.data.order_num=createOrderNum;
        result.data.num=Number(num);
        result.data.create_time=orderInfo.created_at;
        result.data.total_sum=totalSum;
        result.data.code=tItem.code;
        result.data.name=tItem.name;
        result.data.web_pic=tItem.webPic;
        result.data.mobile_pic=tItem.mobilePic;
        result.data.only_code=tItem.onlyCode;
        return result;
    });
  }
  //获取客户订单列表信息--usertype=1用户，usertype=2店主
  async getOrderList(obj){
    var openid = obj.openid;
    var usertype = obj.usertype;
    //order_status all、'1'未付款、'2'已付款、'3'审核中
    var orderStatus=obj.order_status;
    var pageSize=obj.page_size;
    //当前第几页,从1开始
    var currentPage=obj.current_page;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(orderStatus==null||orderStatus==""||orderStatus=="undefined"){
      orderStatus="all";
    }
    if(pageSize==null||pageSize==""||pageSize=="undefined"){
      pageSize="";
    }
    if(currentPage==null||currentPage==""||currentPage=="undefined"){
      currentPage="";
    }
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(usertype==null||usertype==""||usertype=="undefined"){
      result.code=-102;
      result.message="usertype参数有误";
      return result;
    }
    if(usertype!=1&&usertype!=2){
      result.code=-103;
      result.message="usertype参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-104;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    var sqlWhere="";
    if(usertype==1){
      if(tUserInfo.mobile==null){
        result.code=-105;
        result.message="用户信息有误";
        return result;
      }
      //客户订单
      sqlWhere={where:{customerMobile:tUserInfo.mobile},attributes:["offlinePayDocument","channelCode","itemType","customerNum","orderNum","orderStatus","orderStatusName","itemName","webPic","orderType","orderTypeName","remark",
                    "mobilePic","totalSum","itemOrderNum","shopkeeperProfit","created_at","shopOnlyCode","shopNum","customerContact","customerMobile","invoiceApply"],order:[["created_at", 'desc']],raw:true};
    }else {
      if(tUserInfo.onlyCode==null){
        result.code=-106;
        result.message="用户信息有误";
        return result;
      }
      //店主订单
      sqlWhere={where:{shopOnlyCode:tUserInfo.onlyCode},attributes:["offlinePayDocument","channelCode","itemType","customerNum","orderNum","orderStatus","orderStatusName","itemName","webPic","orderType","orderTypeName","remark",
                    "mobilePic","totalSum","itemOrderNum","shopkeeperProfit","created_at","shopOnlyCode","shopNum","customerContact","customerMobile","invoiceApply"],order:[["created_at", 'desc']],raw:true};
    }
    if(orderStatus!="all"){
      if(orderStatus=="1"){
        //未付款
        sqlWhere.where.orderStatus=orderStatus;
      }
      else if(orderStatus=="3") {
        ////订单状态，1未付款，2订单取消，4付款成功，8退款处理中，16已退款、32已提报、64审核中
          sqlWhere.where.orderStatus="64";
      }
      else if(orderStatus=="2") {
        //已付款
          sqlWhere.where.orderStatus={[this.orderSve.dao.db.Op.and]:[{[this.orderSve.dao.db.Op.ne]:"1"},{[this.orderSve.dao.db.Op.ne]:"64"}]};
      }
    }
    if(pageSize!=""&&currentPage!=""){
      var tPageSize=Number(pageSize);
      var tCurrentPage=Number(currentPage);
      if(tCurrentPage<1){
        tCurrentPage=1;
      }
      if(tPageSize>50){
        tPageSize=50;
      }
      if(tPageSize<1){
        tPageSize=1;
      }
      sqlWhere.limit=tPageSize;
      sqlWhere.offset= (tCurrentPage - 1) * tPageSize;
    }
    var orderList=await this.orderSve.dao.model.findAll(sqlWhere);
    if(orderList==null||orderList.length==0){
      result.message="暂无订单信息";
      return result;
    }
    //usertype=1用户，usertype=2店主
    var self=this;
    for (var i = 0; i < orderList.length; i++) {
       var f=  orderList[i];
       if(f!=null){
         var shopItem=await self.getShopItem(f.shopOnlyCode);
         var tData={
           order_num:f.orderNum,
           code:f.itemCode,
           name:f.itemName,
           order_type_name:usertype==1?null:f.orderTypeName,
           order_type:usertype==1?null:f.orderType,
           order_status:f.orderStatus,
           order_status_name:f.orderStatusName,
           web_pic:f.webPic,
           mobile_pic:f.mobilePic,
           total_sum:f.totalSum,
           num:f.num,
           shopkeeper_profit:usertype==1?0:f.shopkeeperProfit,//店主利润
           created_at:f.created_at,
           shop_only_code:f.shopOnlyCode,
           shop_num:f.shopNum,
           customer_contact:f.customerContact,
           customer_mobile:f.customerMobile,
           remark:f.remark,
           shop_name:usertype==1?shopItem==null?null:shopItem.name:"",
           invoice_apply:f.invoiceApply,
           customer_num:f.customerNum,
           item_type:f.itemType,
           channel_type:f.channelCode,
           offline_pay_document:f.offlinePayDocument
         };
         result.data.push(tData);
       }
    }
    return result;
  }
  //获取客户订单列表信息--usertype=1用户，usertype=2店主
  async getOrderDetails(obj){
    var openid = obj.openid;
    var tOrderNum = obj.ordernum;
    var usertype = obj.usertype;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(tOrderNum==null||tOrderNum==""||tOrderNum=="undefined"){
      result.code=-102;
      result.message="tOrderNum参数有误";
      return result;
    }
    if(usertype==null||usertype==""||usertype=="undefined"){
      result.code=-103;
      result.message="usertype参数有误";
      return result;
    }
    if(usertype!=1&&usertype!=2){
      result.code=-104;
      result.message="usertype参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-105;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);

    var sqlWhere={where:{orderNum:tOrderNum},attributes:["offlinePayDocument","channelCode","itemType","customerNum","orderNum","orderStatus","orderStatusName","itemCode","itemName","webPic","remark","orderType","orderTypeName",
                    "mobilePic","totalSum","itemOrderNum","shopkeeperProfit","created_at","shopOnlyCode","shopNum","customerContact","customerMobile","profitRatioType","profitRatioTypeName"],raw:true};
    var orderItem=await this.orderSve.dao.model.findOne(sqlWhere);
    if(orderItem==null){
      result.message="暂无订单详情信息";
      return result;
    }
    var shopItem=await this.getShopItem(orderItem.shopOnlyCode);
    var shopServiceItem=await this.shopserviceitemDao.model.findOne({where:{onlyCode:orderItem.shopOnlyCode,servicesitem_code:orderItem.itemCode},attributes:["customHotline"],raw:true});
    //usertype=1用户，usertype=2店主
    result.data.order_num=orderItem.orderNum;
    result.data.order_type=usertype==1?null:orderItem.orderType;
    result.data.order_type_name=usertype==1?null:orderItem.orderTypeName
    result.data.order_status=orderItem.orderStatus;
    result.data.order_status_name=orderItem.orderStatusName;
    result.data.code=orderItem.itemCode;
    result.data.name=orderItem.itemName;
    result.data.web_pic=orderItem.webPic;
    result.data.mobile_pic=orderItem.mobilePic;
    result.data.total_sum=orderItem.totalSum;
    result.data.num=orderItem.num;
    result.data.shopkeeper_profit=usertype==1?0:orderItem.shopkeeperProfit;//店主利润
    result.data.profit_ratio_type_name=usertype==1?"":orderItem.profitRatioTypeName;//分润类型名称
    result.data.profit_ratio_type=usertype==1?"":orderItem.profitRatioType;//分润类型
    result.data.created_at=orderItem.created_at;
    result.data.shop_only_code=orderItem.shopOnlyCode;
    result.data.shop_num=orderItem.shopNum;
    result.data.customer_contact=usertype==1?"":orderItem.customerContact;
    result.data.customer_mobile=orderItem.customerMobile;
    result.data.remark=orderItem.remark;
    result.data.customer_num=orderItem.customerNum,//客户号
    result.data.item_type=orderItem.itemType,//产品类型
    result.data.channel_type=orderItem.channelCode,//产品渠道类型
    result.data.shop_name=usertype==1?shopItem==null?null:shopItem.name:"";
    result.data.shop_custom_hotline=usertype==1?shopServiceItem==null?null:shopServiceItem.customHotline:"";
    result.data.offline_pay_document=orderItem.offlinePayDocument;
    return result;
  }

  //获取店铺信息
  async getShopItem(tOnlycode,t){
    var shopSqlWhere={where:{onlyCode:tOnlycode},attributes:["id","name","headUrl","userMobile","shopNum","created_at","user_id","onlyCode","app_id","userName","presentationUrl"],raw:true};
    if(t!=null && t!='undefined'){
      shopSqlWhere.transaction=t;
    }
    return this.dao.model.findOne(shopSqlWhere);
  }
  //获取所有店铺信息
  async getShopList(t){
    var shopSqlWhere={attributes:["id","name","headUrl","userMobile","shopNum","created_at","user_id","onlyCode","app_id","userName","presentationUrl"],raw:true};
    if(t!=null && t!='undefined'){
      shopSqlWhere.transaction=t;
    }
    return this.dao.model.findAll(shopSqlWhere);
  }
  //获取店铺信息
  async getShopItemInfo(obj){
    var openid = obj.openid;
    var tOnlycode = obj.onlycode;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
      result.code=-102;
      result.message="onlycode参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-103;
      result.message="用户信息有误";
      return result;
    }
    var shopItem=await this.getShopItem(tOnlycode);
    console.log("--------------shopItem-----------");
    console.log(shopItem);
    if(shopItem==null){
      return result;
    }
    console.log("获取店铺数据shopItem");
    console.log(shopItem);
    if(shopItem.presentationUrl==null||shopItem.presentationUrl==""){
      shopItem.presentationUrl="http://gsb-zc.oss-cn-beijing.aliyuncs.com/201812071419czhd_aboutus.png";
    };
    result.data.shop_presentationUrl=shopItem.presentationUrl;
    result.data.shop_name=shopItem.name;
    result.data.head_url=shopItem.headUrl;
    result.data.user_mobile=shopItem.userMobile;
    result.data.shop_num=shopItem.shopNum;
    result.data.created_at=shopItem.created_at;
    return result;
  }
  //修改用户(user表)关注的店铺
  async putUserConcernCode(obj){
    var openid = obj.openid;
    var tOnlycode = obj.onlycode;
    var result={
       code: 1,
       message: "success",
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
      result.code=-102;
      result.message="onlycode参数有误";
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-103;
      result.message="用户信息有误";
      return result;
    }
     var tUserInfo=JSON.parse(userInfo);
     var customerObj={concernShopOnlyCode:tOnlycode};
     var putSqlWhere={where:{id:tUserInfo.id}};
     var customer=await this.userDao.updateByWhere(customerObj,putSqlWhere);
     //清空用户缓存
     await this.cacheManager["AppletUserinfoCache"].del(openid);
     return result;
  }
  //修改服务项价格
  async putServiceItem(obj){
     var openid = obj.openid;
     var code = obj.code;
     var tCustomTotalAmount = obj.total_sum;
     var tProfitRatioType = obj.profit_ratio_type;
     var tCustomHotline = obj.custom_hotline;
     var channel = obj.channel;
     var result={
        code: 1,
        message: "success"
     };
     if(channel==null||channel==""||channel=="undefined"){
       channel="hhr";
     }
     if(openid==null||openid==""||openid=="undefined"){
       result.code=-101;
       result.message="openid参数有误";
       return result;
     }
     if(code==null||code==""||code=="undefined"){
       result.code=-102;
       result.message="code参数有误";
       return result;
     }
     if(tCustomTotalAmount==null||tCustomTotalAmount==""||tCustomTotalAmount=="undefined"){
       result.code=-103;
       result.message="total_sum参数有误";
       return result;
     }
     if(tProfitRatioType==null||tProfitRatioType==""||tProfitRatioType=="undefined"){
       result.code=-104;
       result.message="profit_ratio_type参数有误";platform_profit_ratio
       return result;
     }
     if(tProfitRatioType!="platformWork"&&tProfitRatioType!="selfWork"){
       result.code=-105;
       result.message="profit_ratio_type参数有误";
       return result;
     }
     if(tCustomHotline==null||tCustomHotline==""||tCustomHotline=="undefined"){
       result.code=-106;
       result.message="custom_hotline参数有误";
       return result;
     }
     var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
     if(userInfo=="null"||userInfo==""){
       result.code=-107;
       result.message="用户信息有误";
       return result;
     }
     var tUserInfo=JSON.parse(userInfo);
     //获取发票税率
     var tmpInvoiceTaxRate= await this.pconfigSve.getInvoiceTaxRate();

     var self=this;
     return self.db.transaction(async function (t){
         var serviceItem= await self.servicesitemDao.model.findOne({where:{code:code},transaction:t,attributes:["serviceCharge","publicExpense","platformCost",
                              "platformProfitRatio","id","servicesReducedRate"],raw:true});
         if(serviceItem==null){
           result.code=-108;
           result.message="服务项目有误";
           return result;
         }
         if(Number(serviceItem.servicesReducedRate)!=100){
           result.code=-120;
           result.message="抱歉了亲，该产品正处于活动期，暂不支持价格修改";
           return result;
         }
         var shopServiceItem= await self.shopserviceitemDao.model.findOne({where:{onlyCode:tUserInfo.onlyCode,servicesitem_id:serviceItem.id,channelCode:channel},transaction:t,
                              attributes:["onlyCode","servicesitem_id"],raw:true});
        if(shopServiceItem==null){
          result.code=-109;
          result.message="店铺服务项目有误";
          return result;
        }
        //店主提成金额
        var tInvoiceTaxRate=await self.setPushMoney(tCustomTotalAmount,serviceItem.publicExpense,serviceItem.platformCost,serviceItem.platformProfitRatio,tmpInvoiceTaxRate,tProfitRatioType);
        // console.log("tInvoiceTaxRate-------------------------------------0001");
        // console.log(tInvoiceTaxRate);
        if(tInvoiceTaxRate<0){
          result.code=-110;
          result.message="输入金额有误";
          return result;
        }
        var customerObj={
                         customTotalAmount:tCustomTotalAmount,
                         profitRatioType:tProfitRatioType,
                         customHotline:tCustomHotline,
                         pushMoney:tInvoiceTaxRate
                       };
        var putSqlWhere={where:{onlyCode:shopServiceItem.onlyCode,servicesitem_id:shopServiceItem.servicesitem_id,channelCode:channel}};
        //修改店铺价格价格
        var customer=await self.shopserviceitemDao.updateByWhere(customerObj,putSqlWhere,t);
        return result;
     });
  }
}
module.exports=ShopService;
