var system=require("../../system")
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
class ChannelmanageallotCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(ChannelmanageallotCtl));
     this.channelSve=system.getObject("service.channelSve");
     this.userSve=system.getObject("service.userSve");
   }
   async mysave(queryobj,qobj,req){
     try {
        console.log(qobj, "===========================");
        qobj.app_id = 7;
        let channel_id = qobj.channel_id;
        let mobile = qobj.mobile;
        let leaderMobile = qobj.leaderMobile;

        let id = qobj.id;
        let cma = null;
        if(id) {
          cma = this.service.findById(id);
        }

        // 渠道
        let channel = await this.channelSve.findById(channel_id);
        console.log(channel_id, "===========================");
        if(!channel) {
          return system.getErrResult2("渠道不存在");
        }

        // 负责人
        let owner = await this.userSve.findOne({app_id:qobj.app_id, mobile:mobile});
        if(!owner) {
          return system.getErrResult2("负责人未注册，请到公众号注册, 否则无法微信推送");
        }

        // 负责人领导
        let leader = await this.userSve.findOne({app_id:qobj.app_id, mobile:leaderMobile});
        if(!leader) {
          return system.getErrResult2("负责人领导未注册, 请到公众号注册, 否则无法微信推送");
        }

        qobj.channelCode = channel.channelCode || "";
        qobj.channelName = channel.channelName || "";
        qobj.channel_id = channel.id;

        qobj.user_id = owner.id;
        qobj.businessOwner = owner.userName || "";
        qobj.openId = owner.openId || "";
        qobj.email = owner.email || "";
        qobj.mobile = owner.mobile || "";

        qobj.leaderId = leader.id;
        qobj.leaderOpenId = leader.openId || "";

        if(cma) {
          await this.service.update(qobj);
          cma = await this.service.findById(id);
        } else {
          let obj = await this.service.findOne({chanceType:qobj.chanceType, channelCode:qobj.channelCode, user_id:owner.id});
          if(obj) {
            return system.getErrResult2("该手机号已经添加配置, 请不要重复添加");
          }
          qobj.weight = 1;
          cma = await this.service.create(qobj);
        }
        await this.cacheManager["ChannelManageAllotCache"].delAllCache();
        console.log(cma, "--------------------------queryobj---------------");
        return system.getResult2(cma);
     } catch (e) {
        console.log("-----------------------------e");
        console.log(e);
     }
     return system.getResult2(null);
   }
}
module.exports=ChannelmanageallotCtl;
