const system=require("../../system");
const ServiceBase=require("../sve.base");
class ServiceTypeService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ServiceTypeService));
     this.channelDao=system.getObject("db.channelDao");
  }
  async getListByPid(params){
    var channel_code=params.channel_code||"";
    var p_id=params.p_id||"";
    var whereObj={where:{isEnabled:1},attributes:["id","name","level","pid"],raw:true};
    if(channel_code && channel_code!="undefined"){
      whereObj.where.channelCode=channel_code;
    }
    if(p_id && p_id!="undefined"){
      whereObj.where.pid=p_id;
    }else {
      whereObj.where.pid=0;
    }
    var list= await this.dao.model.findAll(whereObj);
    return {
         code: 1,
         message: "success",
         data: list
      };
  }
  async getItemById(params){
    var id=params.id||"";
    var whereObj={where:{isEnabled:1},attributes:["id","name","level","pid"],raw:true};
    if(id && id!="undefined"){
      whereObj.where.id=id;
    }
    var list= await this.dao.model.findOne(whereObj);
    return {
         code: 1,
         message: "success",
         data: item
      };
  }
  async getListByName(params){
    var channel_code=params.channel_code||"";
    var name=params.name||"";
    var whereObj={where:{isEnabled:1},attributes:["id","name","level","pid"],raw:true};

    if(channel_code && channel_code!="undefined"){
      whereObj.where.channelCode=channel_code;
    }
    if(name && name!="undefined"){
      whereObj.where.pid={[this.db.Op.gt]:0};
      whereObj.where.name={[this.db.Op.like]:"%"+name+"%"};
    }else {
      whereObj.where.pid=0;
    }
    var list= await this.dao.model.findAll(whereObj);
    return {
         code: 1,
         message: "success",
         data: list
      };
  }

  async createOrEdit(params){
    var tCode = params.code || "";
    var tChannelCode = params.channelCode || "";
    var st = null;
    if(tCode && tChannelCode) {
      var channel=await this.channelDao.model.findOne({where:{channelCode:tChannelCode,isPubed:1},raw:true});
      if(tChannelCode==null){
        return {
             code: -101,
             message: "参数channelCode信息有误",
             data: {}
          };
      }
      params.channel_id=channel.id;
      params.pid=params.pid!=-1 && params.pid>0?params.pid:0;
      st = await super.findOne({code:tCode});
      if(st){
        st.pid=params.pid;
        st.channelCode=tChannelCode;
        st.name=params.name;
        st.save();
      }
      else {
        await this.create(params);
      }
    }
    return {
         code: 1,
         message: "success",
         data: {}
      };
  }

}
module.exports=ServiceTypeService;
