const system=require("../../system");
const ServiceBase=require("../sve.base");
class BusinessallotService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(BusinessallotService));

     this.userDao = system.getObject("db.userDao");
     this.businesschanceDao=system.getObject("db.businesschanceDao");
     this.channelmanageallotDao = system.getObject("db.channelmanageallotDao");
     this.smsClient=system.getObject("util.smsClient");

     this.weight = {
       receipt : -0.05,
       giveup : 0.3,
       success : -0.1,
       failue : 0.05
     };
  }
  //获取某种类型下所有工单列表(参数tChanceType业务类型)
  async getChannelAllotBusiness(){
    return this.dao.model.findAll({where:{status:'1'},raw:true,attributes:["id","businesschance_id","channelmanageallot_id"]});
  }
  async getItemBybusinesschanceId(businesschanceId){
    return this.dao.model.findOne({where:{businesschance_id:businesschanceId},raw:true,attributes:["id","businesschance_id","channelmanageallot_id"]});
  }
  async getItemById(id){
    return this.dao.model.findOne({where:{id:id},attributes:["id","businesschance_id","channelmanageallot_id","user_id","channelCode"]
                                  ,include:{model:this.db.models.businesschance,attributes:["id","channelProfitRatio","profitType","channelProfit","platformProfit"]}});
  }
  async receipt(id, userId) {
    let self = this;
    // 查用户
    var businessallot = await super.findById(id);
    if(businessallot.user_id != userId) {
      return -1;
    }
    // 商机表
    return this.db.transaction(async function (t){
        // 更新派工态
        await self.dao.model.update({status:"2", accept_at:new Date()}, {where:{id:id}, transaction:t});
        // 更新商机状态
        await self.businesschanceDao.model.update({chanceStatus:"2"}, {where:{id:businessallot.businesschance_id}});
        // 更新接单状态
        await self.channelmanageallotDao.model.update({isOrderReceiving: 1,isAllocation:"1"}, {where:{id:businessallot.channelmanageallot_id}});
        await self.channelmanageallotDao.incrAllotCount(businessallot.channelmanageallot_id, self.weight.receipt)
        return 1;
    });
  }

  async giveup(id, userId, reason) {
    let self = this;
    // 查用户
    var businessallot = await super.findById(id);
    if(businessallot.user_id != userId) {
      return -1;
    }

    businessallot.status = "4";
    businessallot.notes = reason || "";
    businessallot.save();

    let cma = await this.channelmanageallotDao.findById(businessallot.channelmanageallot_id);

    if(cma && /^1[23456789]\d{9}$/.test(cma.leaderMobile)) {
      var now = (new Date()).Format("MM-dd hh:mm");
      let msg = cma.businessOwner + "于" + now + " 放弃商机 " + cma.chanceTypeName + ",原因为：" + businessallot.notes + "，请知悉";
      console.log(cma.leaderMobile, msg);
      this.smsClient.sendMsg(cma.leaderMobile, msg);
    }

    await this.channelmanageallotDao.incrAllotCount(businessallot.channelmanageallot_id, this.weight.giveup)
    return 1;
  }

  //成功修改,opType操作类型 add第一次点击成功、put在完成中点击成功
  async success(id, userId, money, reason,opType) {
    let self = this;
    // 查用户
    var businessallot = await self.getItemById(id);
    if(businessallot.user_id != userId) {
      return -1;
    }
    var channelProfit=0;
    var platformProfit=0;

    var businesschance=businessallot.businesschance;
    if(money>0){
      if(businesschance && businesschance!="undefined"){
        channelProfit= parseFloat(businesschance.channelProfit || 0);
        //渠道利润类型:1: 比例分成, 2: 每单分成
        if(businesschance.profitType==1 && businesschance.channelProfitRatio!=null && businesschance.channelProfitRatio!=""){
          channelProfit=money*(businesschance.channelProfitRatio/100);
        }
      }
      platformProfit=money-channelProfit;
    }
    // 商机表
    return this.db.transaction(async function (t){
        // 更新派工态
        await self.dao.model.update({status:"8"}, {where:{id:id}, transaction:t});
        var putField={chanceStatus:"4",disposeNotes: (reason || ""),totalSum:money,platformProfit:platformProfit,channelProfit:channelProfit};
        // 更新商机状态
        await self.businesschanceDao.model.update(putField, {where:{id:businessallot.businesschance_id}, transaction:t});
        //更新派单算法
        await self.channelmanageallotDao.incrAllotCount(businessallot.channelmanageallot_id, self.weight.success);
        return 1;
    });

  }

  async failue(id, userId, reason) {
    let self = this;
    // 查用户
    var businessallot = await super.findById(id);
    if(businessallot.user_id != userId) {
      return -1;
    }

    // 商机表
    return this.db.transaction(async function (t){
        // 更新派工态
        await self.dao.model.update({status:"16", notes : (reason || "") }, {where:{id:id}, transaction:t});
        // 更新商机状态
        await self.businesschanceDao.model.update({chanceStatus:"8",disposeNotes: (reason || "")}, {where:{id:businessallot.businesschance_id}});

        await self.channelmanageallotDao.incrAllotCount(businessallot.channelmanageallot_id, self.weight.failue);
        return 1;
    });
  }

}
module.exports=BusinessallotService;
