const system=require("../../system");
const ServiceBase=require("../sve.base");
class ChannelmanageallotService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ChannelmanageallotService));
     this.channelSve=system.getObject("service.channelSve");
     this.businesschanceSve=system.getObject("service.businesschanceSve");
     this.businessallotSve=system.getObject("service.businessallotSve");
     this.wxSve=system.getObject("service.wxSve");
  }
  //获取启用的渠道分配管理用户列表
  async findAllList(){
      return this.dao.model.findAll({where:{isEnabled:1,isOrderReceiving:1},raw:true});
  }
  //商机第一次分配（状态为待服务）
  async businessOneAllot(wechatUrl){
    var self=this;
    var result={
       code: 1,
       message: "success",
       data: null
    };
    var all_channelManageList=await self.findAllList();
    if(!all_channelManageList || all_channelManageList.length==0){
      result.message="渠道分配管理用户信息为空";
      return result;
    }
    var channelList=await this.channelSve.getAllChannel();
    if(!channelList || channelList.length==0){
      result.message="渠道信息为空";
      return result;
    }
    var sql="SELECT t1.* FROM `h_business_chance` t1 WHERE NOT EXISTS "+
            " (SELECT 1 FROM `c_business_allot` t2 WHERE t2.`status` IN ('1', '2', '8', '16') AND t1.`id` = t2.`businesschance_id`)";
    //渠道商机列表===============================================
    var businessList= await self.dao.customQuery(sql,null);
    if(!businessList || businessList.length==0){
      result.message="要分配商机列表为空";
      return result;
    }
    var addList=[];
    var msmNoticeList=[];//短信通知列表
    var wechatNoticeList=[]//微信通知列表
    for (var i = 0; i < businessList.length; i++) {
        var tItem= businessList[i];
        if(tItem==null){
          continue;
        }

        // 查退回的用户id upd by wk
        let giveupIds = await this.businessallotSve.dao.model.findAll({where:{businesschance_id:tItem.id, status : "4"},attributes:["channelmanageallot_id"], raw:true});
        let notInIds = [];
        if(giveupIds && giveupIds.length > 0) {
          for(let giveupItem of giveupIds) {
            notInIds.push(giveupItem.channelmanageallot_id);
          }
        }
        var tsql="SELECT * FROM c_channel_manage_allot WHERE chanceType =:chanceType AND channelCode=:channelCode AND isOrderReceiving = 1 AND isEnabled = 1 ";
        if(notInIds.length > 0) {
          tsql = tsql + " AND id NOT IN (" + notInIds.join(",") + ") ";
        }
        tsql = tsql + " ORDER BY allotCount ASC LIMIT 1 ";
        // upd by wk end

        var tParam={chanceType:tItem.chanceType,channelCode:tItem.channelCode}
        //渠道商机列表===============================================
        var allotUser= await self.dao.customQuery(tsql,tParam);
        if(!allotUser || allotUser.length==0){
          //目前渠道没有分配任何人员进行接单
          // //msm短信消息模板
          // var msmParam={
          //   mobile:13381139519,
          //   message:"尊敬的领导，客户于"+(new Date()).Format("yyyy-MM-dd")+"发布了新的【"+tItem.serviceItem_name+
          //           "】商机，目前还没有安排接单人员，请及时安排接单人员进行接单！"
          // }
          // msmNoticeList.push(msmParam);

          //获取渠道名称
          var channelName="";
          var channelItemList=channelList.filter(function(item){
            return item.channelCode==tItem.channelCode;
          });
          if(channelItemList.length>0){
            channelName=channelItemList[0].channelName;
          }
          channelName=channelName!=""?"，属于【"+channelName+"】渠道":"";
          //微信消息模板
          var wechatParam={
              url:wechatUrl,
              first:"领导您好，您有新的商机",
              keyword1:"新增【"+tItem.serviceItem_name+"】的商机"+channelName+"，目前还没有安排接单人员，请及时安排接单人员进行接单！",
              keyword2:"待接单",
              openid:"ozFDk0xaXbXK4CCN1F-Kl9HOQmd0"
          }
          var ttsql="SELECT * FROM c_channel_manage_allot WHERE chanceType =:chanceType AND channelCode=:channelCode AND isEnabled = 1 AND isOrderReceiving = 0 ORDER BY allotCount ASC LIMIT 1"
          var tallotUser= await self.dao.customQuery(ttsql,tParam);
          if(tallotUser && tallotUser.length>0){
            wechatParam.keyword1="新增【"+tItem.serviceItem_name+"】的商机"+channelName+"，目前安排的接单人员："+tallotUser[0].businessOwner+"已拒绝接单，请及时安排接单人员进行接单！";
          }
          wechatNoticeList.push(wechatParam);
          continue;
        }
        //处理分工信息
        await self.setOneReceivingUserInfo(addList,msmNoticeList,wechatNoticeList,allotUser[0],tItem,wechatUrl);
    }
    if(wechatNoticeList.length>0){
      //微信处理
      var data=null;
      for (var i = 0; i < wechatNoticeList.length; i++) {
        var wechatItem=wechatNoticeList[i];
        data={
          first:wechatItem.first,
          keyword1:{value:wechatItem.keyword1},
          keyword2:{value:wechatItem.keyword2}
        }
        self.wxSve.sendTmplMsg(wechatItem.openid,"VeqWpbYKzdVvtcJoa5JGcWWK_Hl7qoHCxk25KhIxklo",wechatItem.url,data,null);
      }
    }

    // if(msmNoticeList.length>0){
    //   //短信处理
    //   var smsClient=system.getObject("util.smsClient");
    //   for (var i = 0; i < msmNoticeList.length; i++) {
    //     var smsItem=msmNoticeList[i];
    //     smsClient.sendMsg(smsItem.mobile,smsItem.message);
    //   }
    // }
    if(addList.length==0){
      result.message="暂时没有要分配的工单";
      return result;
    }
    //处理db及通知
    if(addList.length>0){
      await self.businessallotSve.dao.model.bulkCreate(addList);
    }

    return result;
  }
  async setOneReceivingUserInfo(addList,msmNoticeList,wechatNoticeList,onevalidUser,tItem,wechatUrl){
    //获取已经分工的信息列表，状态为待接单
    var param={
      app_id:onevalidUser.app_id,
      user_id:onevalidUser.user_id,
      notifyCount:1,
      status:'1',
      mobile:onevalidUser.mobile,//接单人手机号
      chanceType:tItem.chanceType,
      serviceItem_code:tItem.serviceItem_code,
      serviceItem_name:tItem.serviceItem_name,
      publisherName:tItem.publisherName,
      publisherMobile:tItem.publisherMobile,
      publisherNotes:tItem.notes,
      channelmanageallot_id:onevalidUser.id,
      businesschance_id:tItem.id,
      channelCode:tItem.channelCode,
      city:tItem.city,
      province:tItem.province
    };
    // //msm短信消息模板
    // var msmParam={
    //   mobile:onevalidUser.mobile,
    //   message:"亲爱的知产合伙人，你的客户于"+(new Date()).Format("yyyy-MM-dd")+"发布了新的【"+
    //                        tItem.serviceItem_name+"】商机，亲，赶紧登录创知厚德服务号进行接单！"
    // }
    // msmNoticeList.push(msmParam);
    //微信消息模板
    var wechatParam={
        url:wechatUrl,
        first:"您有新的商机，请登录查看",
        keyword1:"新增【"+tItem.serviceItem_name+"】的商机，请及时接单",
        keyword2:"待接单",
        openid:onevalidUser.openId
    }
    wechatNoticeList.push(wechatParam);
    //新增
    addList.push(param);
    //修改分配次数
    var tAllotCount=Number(onevalidUser.allotCount || 0)+ Number(onevalidUser.weight || 1);
    var putParam={allotCount:tAllotCount}
    await this.dao.model.update(putParam, {where:{id:onevalidUser.id}});
  }

  async incrAllotCount(id, weight) {
    return this.dao.incrAllotCount(id, weight);
  }
}
module.exports=ChannelmanageallotService;
