const system=require("../../system");
const ServiceBase=require("../sve.base");
class ChannelService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ChannelService));
  }
  //获取渠道信息
  async getChannelItem(channel_code){
    return this.dao.model.findOne({where:{channelCode:channel_code,isPubed:1},raw:true});
  }
  //获取渠道信息
  async getChannelItemById(channel_id){
    return this.dao.model.findOne({where:{id:channel_id,isPubed:1},raw:true});
  }
  //获取渠道可以多店信息
  async getChannelList(t){
    return this.dao.model.findAll({where:{moreShop:1},raw:true,transaction:t});
  }
  async getAllChannel(){
      return this.dao.model.findAll({where:{isPubed:1},raw:true});
  }
  async findAllChannel(){
    try {
        var result= await this.dao.model.findAll({where:{isPubed:1},raw:true});
        if (result == null || result.length == 0) {
            return {code:0,msg:"没有信息",data:null};
        }else {
            return {code:1,msg:"操作成功",data:result};
        }
    }catch (e) {
        return {code:-1,msg:"操作失败",data:null};
    }
  }
  //判断渠道不支持多店，且渠道是否已经创建了产品中间表
  async getUserChannel(channelId,userId){
    var sql="SELECT user_id FROM `p_user_channel` WHERE `channel_id`=:channel_id";
    var paras={channel_id:channelId};
    if(userId!=null&&userId!=""&&userId!="undefined"){
       sql=sql+" and `user_id`=:user_id";
       paras.user_id=userId;
    }
    return this.dao.customQuery(sql,paras);
  }
  //判断渠道不支持多店，且渠道是否已经创建了产品中间表
  async addUserChannel(userId,channelId,t){
    var paras={user_id:userId,channel_id:channelId};
    var sql="INSERT INTO `zc`.`p_user_channel` (`created_at`,`updated_at`,`version`,`user_id`,`channel_id`)"+
            " VALUES (NOW(),NOW(),0,"+userId+","+channelId+")";
    return this.dao.customExecAddOrPutSql(sql,null,t);
  }

  //获取接入渠道的渠道列表数据
  async getChannelCooperationList(){
    var bussinessAllotChannel=await self.pconfigSve.getBussinessAllotChannelConfig();
    var tList=bussinessAllotChannel.spilt(',');
    if(tList==null||tList.length==0){
      return null;
    }
    var tArray=[];
    for (var i = 0; i < tList.length; i++) {
      var c=tList[i];
      if(c!=null&&c!=""){
        tArray.push(c);
      }
    }
    var sqlWhere={where:{isPubed:1,channelCode:{[this.dao.db.Op.in]:tArray}}};
    return this.dao.findAll(sqlWhere);
  }
}
module.exports=ChannelService;
