const system=require("../../system");
const ServiceBase=require("../sve.base");
class ServicesitemService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ServicesitemService));
     this.pconfsve=system.getObject("service.pconfigSve");
     this.channelSve=system.getObject("service.channelSve");
     this.shopserviceitemSve=system.getObject("service.shopserviceitemSve");
     this.shopSve=system.getObject("service.shopSve");
  }
  async findByChannelcode(obj){
    console.log("-----------Sve----------------findByChannelcode-------------");
    var result=await this.dao.model.findAll({where:{channelCode:obj.channelcode,isPubed:1},attributes:["name","shortDesc","code"],order:[["sort","asc"]]});
    return result;
  }
  async findAll(obj) {
    return this.dao.model.findAll({where:obj,raw:true,order:[["sort","asc"]]});
  }
  async findService5(queryobj,qobj){
    return this.dao.findService5();
  }
  async findOneByCode(code){
    return this.dao.findOneByCode(code);
  }
  async create(qobj){
    qobj.authorOnlyCode=qobj.onlyCode;
    //检查code的唯一性
    var checkone=await this.dao.model.findOne({where:{code:qobj.code}});
    if(checkone){
      throw new Error("编码重复了......");
    }
    if(qobj.codepath.indexOf("tmstock")>=0){
      //设置默认渠道
      qobj.channel_id=4;
      qobj.channelCode="yzc";
      qobj.isNegotiable="1";
      return super.create(qobj);
    }else{
      var serviceCharge=qobj.serviceCharge;
      var publicExpense=qobj.publicExpense;
      var platformCost=qobj.platformCost;
      //获取配置的发票税率
      var p=await this.pconfsve.getInvoiceTaxRate();

      // var s=(serviceCharge+publicExpense+platformCost)/((100-p)/100);
      // var c=Math.round(publicExpense+platformCost)/((100-p)/100);
      //新的算法---by20190306
      var tmpS=serviceCharge+publicExpense+platformCost;
      var s=tmpS+tmpS*p/100;
      var tmpC=publicExpense+platformCost;
      var c=tmpC+tmpC*p/100;
      if(qobj.platformWorkFloorPrice!=s){
         qobj.platformWorkFloorPrice=s;
      }
      if(qobj.guidePrice<qobj.platformWorkFloorPrice){
        qobj.guidePrice=qobj.platformWorkFloorPrice;
      }
      qobj.selfWorkFloorPrice=c;
      var channel=await this.channelSve.getChannelItemById(qobj.channel_id);
      qobj.channelCode=channel.channelCode;
      return super.create(qobj);
    }
  }
  async update(qobj,tm=null){
    qobj.authorOnlyCode=qobj.onlyCode;
    if(qobj.codepath.indexOf("tmstock")<0){
      var serviceCharge=qobj.serviceCharge;
      var publicExpense=qobj.publicExpense;
      var platformCost=qobj.platformCost;
      var p=await this.pconfsve.getInvoiceTaxRate();

      // var s=(serviceCharge+publicExpense+platformCost)/((100-p)/100);
      // var c=Math.round(publicExpense+platformCost)/((100-p)/100);
      //新的算法---by20190306
      var tmpS=serviceCharge+publicExpense+platformCost;
      var s=tmpS+tmpS*p/100;
      var tmpC=publicExpense+platformCost;
      var c=tmpC+tmpC*p/100;

      if(qobj.platformWorkFloorPrice!=s){
         qobj.platformWorkFloorPrice=s;
      }
      if(qobj.guidePrice<qobj.platformWorkFloorPrice){
        qobj.guidePrice=qobj.platformWorkFloorPrice;
      }
      qobj.selfWorkFloorPrice=c;
      var channel=await this.channelSve.getChannelItemById(qobj.channel_id);
      qobj.channelCode=channel.channelCode;
      return this.dao.update(qobj,tm);
    }else{
      var putData={
        id: qobj.id,
        itemType:qobj.itemType,
        code:qobj.code,
        name:qobj.name,
        shortDesc:qobj.shortDesc,
        mobilePic:qobj.mobilePic,
        hotline: qobj.hotline,
        sort: qobj.sort,
        isRecommend:qobj.isRecommend,
        nclOneCodes:qobj.nclOneCodes,
        authorName: qobj.authorName,
        authorMobile: qobj.authorMobile,
        priceRangeMin: qobj.priceRangeMin,
        priceRangeMax: qobj.priceRangeMax,
        tmExpirationDate: qobj.tmExpirationDate,
        applyName: qobj.applyName,
        opOnlyCode: qobj.onlyCode
        // authorOnlyCode: 'testunionid',
      }
      return this.dao.update(putData,tm);
    }
  }

  async copyServiceItemData(obj,loginOnlyCode){
    console.log("tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt");
    console.log(obj);
    var channel = obj.channel;
    var ids = obj.ids;
    var result={
       code: 1,
       message: "复制成功",
       data:""
    };
    if(channel==null||channel==""||channel=="undefined"){
      result.code=-101;
      result.message="channel参数有误";
      return result;
    }
    if(ids==null||ids==""||ids=="undefined"||ids.length==0){
      result.code=-102;
      result.message="ids参数有误";
      return result;
    }
    var channelItem=await this.channelSve.getChannelItem(channel);
    if(channelItem==null){
      result.code=-103;
      result.message="没有查询到要复制的渠道信息";
      return result;
    }
    var self=this;
    var list=await self.dao.model.findAll({where:{id:{[self.dao.db.Op.in]:ids}},raw:true});
    if(!list||list.length==0){
      result.message="要导入的数据源为空";
      return result;
    }
    var addData=[];
    for (var i = 0; i < list.length; i++) {
      var tItem=list[i];
      if(tItem!=null){
        tItem.channel_id=channelItem.id;
        tItem.channelCode=channel;
        tItem.code=channel+"_"+tItem.code;
        tItem.opOnlyCode=loginOnlyCode;
        tItem.id=null;
        tItem.created_at=null;
        tItem.updated_at=null;
        addData.push(tItem);
      }
    }
    if(addData.length>0){
       self.dao.model.bulkCreate(addData);
    }
    return result;
  }

  //获取渠道商标交易列表
  async getServicesItemList(obj){
    var openid = obj.openid;
    var channel = obj.channel==null||obj.channel==""||obj.channel=="undefined"?"yzc":obj.channel;
    var tSellStatus = obj.sell_status==null||obj.sell_status==""||obj.sell_status=="undefined"?"all":obj.sell_status;
    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 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==null||userInfo=="undefined"){
      result.code=-102;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    var sqlWhere={where:{authorOnlyCode:tUserInfo.onlyCode,channelCode:channel},
      attributes:["code","name","mobilePic","sellStatus","sellStatusName","nclOneCodes","isPubed","hotline","created_at"],
      raw:true,order:[["created_at","desc"],["sort","asc"]]};
    if(tSellStatus!="all"&&tSellStatus!="0"){
      sqlWhere.where.sellStatus=tSellStatus;
    }
    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 list= await this.dao.model.findAll(sqlWhere);
    if(list==null||list.length==0){
      result.message="暂无服务项目列表";
      return result;
    }
    for (var i = 0; i < list.length; i++) {
        var tItem= list[i];
        if(tItem!=null){
          //返回的服务项目列表
          var service_item={
                code:tItem.code,//商标号
                name:tItem.name,//商标名称
                mobile_pic:tItem.mobilePic,//商标图片
                sell_status:tItem.sellStatus,//销售状态
                sell_statusName:tItem.sellStatusName,//销售状态名称
                ncl_one_codes:tItem.nclOneCodes,//尼斯大类
                is_pubed:tItem.isPubed,//上架状态0下架、1为上架
                hotline:tItem.hotline,//热线咨询电话
                created_at:tItem.created_at
          };
          result.data.push(service_item);
        }
    }
     return result;
  }
  async getServicesItemDetail(obj){
    var openid = obj.openid;
    var tCode = obj.code;
    var channel = obj.channel==null||obj.channel==""||obj.channel=="undefined"?"yzc":obj.channel;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(tCode==null||tCode==""||tCode=="undefined"){
      result.code=-102;
      result.message="code参数有误";
      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 list=await this.dao.model.findAll({where:{authorOnlyCode:tUserInfo.onlyCode,channelCode:channel,code:tCode},
      attributes:["code","name","mobilePic","sellStatus","sellStatusName","nclOneCodes","isPubed","hotline","created_at",
                  "authorName","authorMobile","tmExpirationDate","shortDesc","priceRangeMin","priceRangeMax"],raw:true});
    if(list==null||list.length==0){
      result.message="暂无服务项目列表";
      return result;
    }
    for (var i = 0; i < list.length; i++) {
        var tItem= list[i];
        if(tItem!=null){
          //返回的服务项目列表
          var service_item={
            code:tItem.code,//商标号
            name:tItem.name,//商标名称
            mobile_pic:tItem.mobilePic,//商标图片
            sell_status:tItem.sellStatus,//销售状态
            sell_statusName:tItem.sellStatusName,//销售状态名称
            ncl_one_codes:tItem.nclOneCodes,//尼斯大类
            is_pubed:tItem.isPubed,//上架状态0下架、1为上架
            hotline:tItem.hotline,//热线咨询电话
            created_at:tItem.created_at,
            author_name:tItem.authorName,//发布者
            author_mobile:tItem.authorMobile,//发布者电话
            tm_expiration_date:tItem.tmExpirationDate,//到期时间
            short_desc:tItem.shortDesc,//商标简介
            price_range_min:tItem.priceRangeMin,//价格区间最小值
            price_range_max:tItem.priceRangeMax//价格区间最大值
          };
          result.data.push(service_item);
        }
    }
     return result;
  }
  //添加商标交易
  async addServicesitem(obj){
    var self=this;
    var code = obj.code;
    var name = obj.name;
    var mobilePic = obj.mobile_pic;
    var nclOneCodes = obj.nclOne_codes;
    var authorName = obj.author_name;
    var authorMobile = obj.author_mobile;
    var tmExpirationDate =obj.tm_expiration_date==null||obj.tm_expiration_date==""||obj.tm_expiration_date=="undefined"?"":obj.tm_expiration_date;
    var shortDesc =obj.short_desc==null||obj.short_desc==""||obj.short_desc=="undefined"?"":obj.short_desc;
    // var priceRangeMin =obj.price_range_min==null||obj.price_range_min==""||obj.price_range_min=="undefined"?"":obj.price_range_min;
    var priceRangeMax =obj.price_range_max==null||obj.price_range_max==""||obj.price_range_max=="undefined"?"":obj.price_range_max;
    var channel = obj.channel==null||obj.channel==""||obj.channel=="undefined"?"yzc":obj.channel;
    var openid = obj.openid;
    var tOnlycode = obj.onlycode;
    //接口外调用传递
    var tItemType=obj.item_type==null||obj.item_type==""||obj.item_type=="undefined"?"ip":obj.item_type;
    var result={
       code: 1,
       message: "success",
       data: null
    };
    if(code==null||code==""||code=="undefined"){
      result.code=-101;
      result.message="code参数有误";
      return result;
    }
    if(name==null||name==""||name=="undefined"){
      result.code=-102;
      result.message="name参数有误";
      return result;
    }
    if(mobilePic==null||mobilePic==""||mobilePic=="undefined"){
      result.code=-103;
      result.message="mobilePic参数有误";
      return result;
    }
    if(nclOneCodes==null||nclOneCodes==""||nclOneCodes=="undefined"){
      result.code=-104;
      result.message="nclOneCodes参数有误";
      return result;
    }
    if(authorName==null||authorName==""||authorName=="undefined"){
      result.code=-105;
      result.message="authorName参数有误";
      return result;
    }
    if(authorMobile==null||authorMobile==""||authorMobile=="undefined"){
      result.code=-106;
      result.message="authorMobile参数有误";
      return result;
    }
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-107;
      result.message="openid参数有误";
      return result;
    }
    if(tOnlycode==null||tOnlycode==""||tOnlycode=="undefined"){
      result.code=-108;
      result.message="onlycode参数有误";
      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 channelItem=await this.channelSve.getChannelItem(channel);
    if(channelItem==null){
      result.code=-110;
      result.message="channel渠道信息有误";
      return result;
    }
    var shopItem=await this.shopSve.getShopItem(tOnlycode);
    if(shopItem==null){
      result.code=-111;
      result.message="onlycode店铺信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    var addObj={
      code:code,
      name:name,
      mobilePic:mobilePic,
      nclOneCodes:nclOneCodes,
      authorName:authorName,
      authorMobile:authorMobile,
      tmExpirationDate:tmExpirationDate,
      shortDesc:shortDesc,
      // priceRangeMin:priceRangeMin,
      priceRangeMax:priceRangeMax,
      channelCode:channel,//渠道
      authorOnlyCode:tUserInfo.onlyCode,//发布者唯一码
      hotline:shopItem.userMobile,
      itemType:tItemType
    };
    return self.db.transaction(async function (t){
      var item=await self.findOne({code:code},t);
      if(item&&item!=null){
        if(tUserInfo.onlyCode!=item.authorOnlyCode){
          result.code=-115;
          result.message="无权限修改，请检查信息";
          return result;
        }
        addObj.id=item.id;
        await self.dao.update(addObj,t);
        result.message="修改成功";
      }
      else {
        var addItem=await self.dao.create(addObj,t);
        //不采用中间表方案，采用cms_servicesitem一张表方案_by20181213
        // addItem=addItem.get({plain:true});
        // self.shopserviceitemSve.opTmTradeShopReplenish(addItem,result);
        result.message="发布成功";
      }
      return result;
    })
  }
}
module.exports=ServicesitemService;
