package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CrmEntryCombinerBoxGroup;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import org.springframework.stereotype.Repository;

@Repository
public class CrmEntryCombinerBoxGroupDao extends BaseDao<CrmEntryCombinerBoxGroup> {


    public Record getEntryCombinerBoxSet(String entryId){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT IFNULL(bg.total_count,d.total_count)AS total_count,bg.group_number,bg.group_name,bg.already_into_count,d.type,d.serial_number,d.box_group_id ,d.status ");
        sb.append(" FROM `crm_entry_combiner_box_group_detail` d  LEFT JOIN `crm_entry_combiner_box_group` bg  ON bg.id=d.`box_group_id`  ");
        sb.append("  WHERE d.entry_id=?  ");
        return Db.findFirst(sb.toString(),entryId);
    }

    //获取一户多站的汇流组  租户分类: 1.个人 2.单位
    public Record getOneToAnyBoxSet(String idCode,String regnoCode,String traderId,String tenantType){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT bg.total_count,bg.group_number,bg.group_name,bg.already_into_count,bg.id FROM `crm_entry_combiner_box_group` bg  ");
        sb.append(" WHERE  bg.total_count>bg.already_into_count AND bg.`trader_id`=? ");
        if("1".equals(tenantType)){
             sb.append(" and bg.id_code='"+idCode+"' ");
        }else{
             sb.append("  and bg.regno_code='"+regnoCode+"' ");
        }
        return Db.findFirst(sb.toString(),traderId);
    }


    public CrmEntryCombinerBoxGroup getByGroupNumber(String groupNumber){
        return getByHql("FROM CrmEntryCombinerBoxGroup WHERE groupNumber = :p1", new Parameter(groupNumber));
    }

    public Record getEntryBoxGroup(String entryId){
         StringBuilder sb=new StringBuilder();
         sb.append(" SELECT d.type,d.box_group_id,d.entry_id,d.total_count,d.serial_number,g.group_number,g.group_name,g.already_into_count,g.already_incoming_count,g.total_count,g.id as groupId ");
         sb.append("  FROM `crm_entry_combiner_box_group_detail` d  ");
         sb.append("  LEFT JOIN `crm_entry_combiner_box_group` g ON g.id=d.box_group_id ");
         sb.append("  WHERE d.entry_id=? and d.status<>'0' ");
         return Db.findFirst(sb.toString(),entryId);
    }

    public Long getSamBoxGroupNumber(String groupNumber){
        String sql="  SELECT COUNT(id) FROM crm_entry_combiner_box_group WHERE group_number=? ";
        return Db.queryLong(sql,groupNumber);
    }
}
