var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const logCtl=system.getObject("web.oplogCtl");
class ChannelCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(ChannelCtl));

     this.wxSve = system.getObject("service.wxSve");
   }
   async findAllChannel(obj,req){
     var self=this;
     var result=await this.service.findAllChannel();
     result.data.sort(self.keysort('id',true));
     return result;
   }
   async getChannelItem(qobj,obj,req){
     var channel=await this.service.getChannelItem(obj.channelcode);
     if(channel==""||channel==null||channel=="undefined"){
       return {code:-1,msg:"该渠道尚未建立"};
     }else{
       return {code:1,msg:"success",data:channel.channelName}
     }
   }

   async create(queryobj,qobj,req){
     if(req && req.session && req.session.app){
       qobj.app_id=req.session.app.id;
       qobj.onlyCode=req.session.user.unionId;
       if(req.codepath){
         qobj.codepath=req.codepath;
       }
     }

     if(!qobj.iconLink) {
       qobj.iconLink = "https://boss.gongsibao.com/needhtml5?channelcode=" + qobj.channelCode;
     }
     if(qobj.iconLink) {
       qobj.qrcodeurl = "http://boss.gongsibao.com/api/qc?detailLink=" + qobj.iconLink;
     }

     var rd=await this.service.create(qobj);
     return system.getResult2(rd,null);
   }

   async update(queryobj,qobj,req){
     if(req && req.session && req.session.user){
       qobj.onlyCode=req.session.user.unionId;
     }
     if(req.codepath){
       qobj.codepath=req.codepath;
     }

     if(!qobj.iconLink) {
       qobj.iconLink = "https://boss.gongsibao.com/needhtml5?channelcode=" + qobj.channelCode;
     }

     if(qobj.iconLink) {
       qobj.qrcodeurl = "http://boss.gongsibao.com/api/qc?detailLink=" + qobj.iconLink;
     }
     var rd=await this.service.update(qobj);
     return system.getResult2(rd,null);
   }
   /**
     * 排序有倒序 对数组中的对象，按对象的key进行sortType排序
     * @param key 数组中的对象为object,按object中的key进行排序
     * @param sortType true为降序；false为升序
     */
   keysort(key,sortType) {
        return function(a,b){
            return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
        }
    }
}
module.exports=ChannelCtl;
