package com.sifang.modules.account.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.taskdispatch.constant.ReviewDispatchConst;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public class TraderAccountDao extends BaseDao<CrmTraderAccount> {

    public int addSettleAmount(String traderId, BigDecimal settleAmount) {
        return Db.update("update crm_trader_account set settle_amount=settle_amount+? where trader_id=?", settleAmount, traderId);
    }

    public int addBasicQuotaAmountBalance(String traderId, BigDecimal amount) {
        return Db.update("update crm_trader_account set basic_quota_amount_balance=basic_quota_amount_balance+? where trader_id=?", amount, traderId);
    }

    public int addMaxQuotaAmountBalance(String traderId, BigDecimal amount) {
        return Db.update("update crm_trader_account set max_quota_amount_balance=max_quota_amount_balance+? where trader_id=?", amount, traderId);
    }

    public int addMaxQuotaAmountBalanceAll(String traderId, BigDecimal amount) {
        return Db.update("update crm_trader_account set basic_quota_amount_balance=basic_quota_amount_balance+?,max_quota_amount_balance=max_quota_amount_balance+? where trader_id=?",amount, amount, traderId);
    }


    /**
     * 查询代理商账户信息
     */
    public CrmTraderAccount findByTraderId(String traderId) {
        return getByHql("FROM CrmTraderAccount WHERE trader_id = :p1", new Parameter(traderId));
    }

    /**
     * 账户列表
     */
    public List<Record> listTraderAccount(Map<String, String> queryParams, LayuiPage page) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.name as traderName, t.contacts, t.telephone, concat(t.province, t.city, t.area, t.address) as traderAddress,a.bzj_amount")
                .line(" ,TRUNCATE((a.bzj_amount),2) as bzjAmount,TRUNCATE((a.bond_amount_limit),2) as bondAmountLimit ")
                .line(" ,CAST(a.bzj_amount + a.yk_bzj_amount AS DECIMAL(10,2)) as bzjSum ")
                .line(", a.basic_quota_amount, a.basic_quota_amount_bzj, a.basic_quota_amount_balance, a.bond_amount_limit ")
                .line(", a.max_quota_amount, a.max_quota_amount_bzj, a.max_quota_amount_balance")
                .line(", a.settle_amount, a.settle_amount_ysjs, a.qa_amount, a.qa_amount_usable, a.qa_amount_freeze, a.qa_amount_incdec,a.settle_deduction_amount ")
                .line(" ,a.bond_amount_limit,a.trader_id");
        if("1".equals(queryParams.get("formType"))){   //授信账号页面
            builder.line(" , \n" +
                    " IF((SELECT COUNT(o.id) FROM `crm_supply_material_deliver_order`  o WHERE o.trader_id=t.id  and  o.type in('1','2') and status not in('0','10') and order_examine_status <> '0' ) <> 0, (SELECT COUNT(o.id) FROM `crm_supply_material_deliver_order`  o WHERE o.trader_id=t.id  and  o.type in('1','2','4') and status not in('0','8','10') and order_examine_status in ('1','3') ),CAST(a.yk_deliver_total_capacity AS UNSIGNED)) as ifOne   ");  //判断是否是首发授信额
            builder.line(" ,TRUNCATE((IFNULL(c.deliverTotalAmount,0)),2) as deliverTotalAmount,(TRUNCATE((IFNULL(b.yazTotalCapacity,0)*1.5),2 )) as yazTotalCapacity");
            builder.line(" ,(TRUNCATE((IFNULL(b.ybwTotalCapacity,0)*1.5),2)) as ybwTotalCapacity,   ");
            builder.line(" a.yk_bzj_amount, a.yk_deliver_total_capacity, a.yk_yaz_total_capacity , a.yk_ybw_total_capacity ,a.yk_tkl_total_capacity ");
            builder.line(" from crm_trader_account a ");
            builder.line(" left join (SELECT SUM(CASE WHEN e.material_fix_flag='1' THEN r.capacity ELSE 0 END) AS yazTotalCapacity, ");
            builder.line("  SUM(CASE WHEN e.first_generation_time is not null THEN r.capacity ELSE 0 END) AS ybwTotalCapacity,e.distributor_id ");
            builder.line("  FROM `crm_accepting_report` r LEFT JOIN `crm_customer_entry` e ON e.receiving_report_id=r.id  ");
            builder.line(" WHERE e.material_fix_flag='1'  AND e.status<>'b' GROUP BY e.distributor_id) as b on b.distributor_id =a.trader_id ");
            builder.line(" left join ( SELECT SUM(IFNULL(o.predict_amount,0)) AS deliverTotalAmount,o.trader_id FROM `crm_supply_material_deliver_order` o ");
            builder.line(" WHERE o.type in('1','2','4')  AND o.order_examine_status in ('1','3') AND o.status not in ('0','8','10') GROUP BY o.trader_id  ) as c on c.trader_id =a.trader_id");
            builder.line("left join crm_trader t on a.trader_id=t.id");
            builder.line("where 1=1");
            appendListTraderCondition(builder, queryParams);
            builder.limit(page.getPage(), page.getLimit());
            return Db.find(builder.build(), builder.params());
        }else{
            builder.line(", IFNULL(dk.dk_amount,0)as dk_amount, IFNULL(kc.kc_amount,0)as kc_amount ");
        }

        builder.line("from crm_trader_account a")
                .line("left join crm_trader t on a.trader_id=t.id")
                .line("LEFT JOIN ( SELECT sum( amount ) AS dk_amount, trader_id FROM crm_bond_apply WHERE STATUS = 3 AND adjust_type = 1 ) AS dk ON dk.trader_id = a.trader_id ")
                .line("LEFT JOIN ( SELECT sum( amount ) AS kc_amount, trader_id FROM crm_bond_apply WHERE STATUS = 3 AND adjust_type = 2 ) AS kc ON kc.trader_id = a.trader_id")
                .line("where 1=1");
        appendListTraderCondition(builder, queryParams);
        builder.limit(page.getPage(), page.getLimit());
        return Db.find(builder.build(), builder.params());
    }

    public Long countTraderAccount(Map<String, String> queryParams) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select count(1)")
                .line("from crm_trader_account a")
                .line("left join crm_trader t on a.trader_id=t.id")
                .line("where 1=1");
        appendListTraderCondition(builder, queryParams);
        return Db.queryLong(builder.build(), builder.params());
    }

    private void appendListTraderCondition(SqlBuilder builder, Map<String, String> queryParams){
        if (StringUtil.checkParamValid(queryParams.get("traderName"))) {
            builder.like("and t.name like ?", queryParams.get("traderName").trim());
        }
        if (StringUtil.checkParamValid(queryParams.get("traderIds"))) {
            builder.inst("and a.trader_id in ", queryParams.get("traderIds").split(","));
        }
        if (StringUtil.checkParamValid(queryParams.get("traderId"))) {
            builder.line(" and a.trader_id = ? ",queryParams.get("traderId"));
        }
    }

    //获取代理商的账户
    public CrmTraderAccount getAccountByTraderId(String traderId){
        CrmTraderAccount account=findByTraderId(traderId);
        if(account==null){
            account=new CrmTraderAccount();
            account.setTraderId(traderId);
            account.setCreateTime(new Date());
        }
        return account;
    }

    public Record getXsByTraderVsAccount(String traderId,String type){
        String sql=" SELECT d.amount FROM `crm_account_set` s " +
                "    LEFT JOIN `crm_account_set_details` d ON s.id=d.set_id " +
                "    WHERE s.type=? AND ((range_tap='2' AND FIND_IN_SET(?,d.trader_id)) OR d.range_tap='1') ORDER BY d.range_tap DESC LIMIT 1 ";
        return Db.findFirst(sql,type,traderId);
    }

    public Record getBondDetail(String traderId){
        StringBuffer sb=new StringBuffer();
        sb.append("  SELECT IFNULL(SUM(CASE WHEN a.adjust_type='1' THEN a.amount ELSE 0 END ),0 )AS dkAmount , ");
        sb.append("  IFNULL(SUM(CASE WHEN a.adjust_type='2' THEN a.amount ELSE 0 END ),0) AS kkAmount , ");
        sb.append(" IFNULL(SUM(CASE WHEN a.adjust_type='3' THEN a.amount ELSE 0 END ),0) AS tkAmount,  ");
        sb.append(" IFNULL(SUM(CASE WHEN a.adjust_type='4' THEN a.amount ELSE 0 END ),0) AS jsdkAmount  ");
        sb.append("  FROM  `crm_bond_apply` a WHERE a.trader_id=? ");
        return Db.findFirst(sb.toString(),traderId);
    }


    public void djsAccountChangeList(LayuiPage<Record> page, Map<String, String> map){
      SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" SELECT a.*,d.name as departmentName,DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime  ");
        sqlBuilder.line(" ,t.name AS traderName,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime " );
        sqlBuilder.line("  from ( SELECT a.id,a.apply_number,a.department_id,a.trader_id,'-1' AS adjust_type,a.out_cash AS amount, a.create_time,a.create_name,a.remarks,a.finish_time,'' AS power_station_code ");
        sqlBuilder.line("  FROM `crm_cash_out_apply` a WHERE a.status='3' and a.obj_type='0' ");
        sqlBuilder.line(" UNION ALL ");
        sqlBuilder.line("  SELECT  a.id,a.apply_number,a.department_id,a.trader_id,a.adjust_type,a.amount, a.create_time,a.create_name,a.remarks,a.finish_time,e.power_station_code ");
        sqlBuilder.line("  FROM crm_settlement_amount_adjustment_apply a  LEFT JOIN crm_customer_entry e ON e.id=a.entry_id WHERE a.status='3') as a ");
        sqlBuilder.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sqlBuilder.line(" LEFT JOIN `crm_department` d  on d.id=a.department_id");
        sqlBuilder.line(" where 1=1 ");
        getConditionMap(map, sqlBuilder);
        sqlBuilder.line("  ORDER BY create_time DESC");
        if (page != null) {
            sqlBuilder.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = getDjsAccountChangeCount(map);
            page.setCount(count);
        }
        List<Record> list = Db.find(sqlBuilder.build(), sqlBuilder.params());
        page.setData(list);
    }

    public Long getDjsAccountChangeCount(Map<String, String> map){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" SELECT count(a.id) from ( SELECT a.id,a.trader_id,a.apply_number,'-1' AS adjust_type ,a.create_time,a.finish_time ");
        sqlBuilder.line("  FROM `crm_cash_out_apply` a WHERE a.status='3' and a.obj_type='0' ");
        sqlBuilder.line(" UNION ALL ");
        sqlBuilder.line("  SELECT  a.id ,a.trader_id,a.apply_number,a.adjust_type,a.create_time,a.finish_time ");
        sqlBuilder.line("  FROM crm_settlement_amount_adjustment_apply a WHERE a.status='3') as a ");
        sqlBuilder.line(" where 1=1 ");
        getConditionMap(map, sqlBuilder);
        return Db.queryLong(sqlBuilder.build(), sqlBuilder.params());
    }

    public void getConditionMap(Map<String, String> map, SqlBuilder sf) {
        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("traderId"))) {
            sf.inst(" AND a.trader_id in ", map.get("traderId").split(","));
        }
        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("applyNumber"))) {
            sf.like(" AND a.apply_number LIKE ? ", map.get("applyNumber"));
        }

        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("adjustType"))) {  // 0：启动，1：禁用
            sf.line(" AND a.adjust_type = ? ", map.get("adjustType"));
        }

        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("createTimeSta"))) {
            sf.line("AND a.create_time >= ?", map.get("createTimeSta") + " 00:00:00");
        }
        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("createTimeEnd"))) {
            sf.line("AND a.create_time <= ?", map.get("createTimeEnd") + " 23:59:59");
        }
        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("finishTimeMin"))) {
            sf.line("AND a.finish_time >= ?", map.get("finishTimeMin") + " 00:00:00");
        }
        if (com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.isNotBlank(map.get("finishTimeMax"))) {
            sf.line("AND a.finish_time <= ?", map.get("finishTimeMax") + " 23:59:59");
        }

    }

    public void zbjAccountChangeLst(LayuiPage<Record> page, Map<String, String> map){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" SELECT a.*,d.name as departmentName,DATE_FORMAT(a.finish_time,'%Y-%m-%d %H:%i:%s')AS finishTime  ");
        sqlBuilder.line(" ,t.name AS traderName,DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s')AS createTime " );
        sqlBuilder.line("  from ( SELECT a.id,a.apply_number,a.department_id,a.trader_id,'-1' AS adjust_type,a.out_cash AS amount, a.create_time,a.create_name,a.remarks,a.finish_time  ");
        sqlBuilder.line("  FROM `crm_cash_out_apply` a WHERE a.status='3' and a.obj_type='1' ");
        sqlBuilder.line(" UNION ALL ");
        sqlBuilder.line("  SELECT  a.id,a.apply_number,a.department_id,a.trader_id,a.adjust_type,a.amount, a.create_time,a.create_name,a.remarks,a.finish_time ");
        sqlBuilder.line("  FROM crm_warranty_deposit_adjustment_apply a WHERE a.status='3') as a ");
        sqlBuilder.line(" LEFT JOIN `crm_trader` t ON a.trader_id=t.id ");
        sqlBuilder.line(" LEFT JOIN `crm_department` d  on d.id=a.department_id");
        sqlBuilder.line(" where 1=1 ");
        getConditionMap(map, sqlBuilder);
        sqlBuilder.line("  ORDER BY create_time DESC");
        if (page != null) {
            sqlBuilder.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
            Long count = zbjAccountChangeCount(map);
            page.setCount(count);
        }
        List<Record> list = Db.find(sqlBuilder.build(), sqlBuilder.params());
        page.setData(list);
    }

    public Long zbjAccountChangeCount(Map<String, String> map){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" SELECT count(a.id) from ( SELECT a.id,a.trader_id,a.apply_number,'-1' AS adjust_type ,a.create_time,a.finish_time ");
        sqlBuilder.line("  FROM `crm_cash_out_apply` a WHERE a.status='3' and a.obj_type='1' ");
        sqlBuilder.line(" UNION ALL ");
        sqlBuilder.line("  SELECT  a.id ,a.trader_id,a.apply_number,a.adjust_type,a.create_time,a.finish_time ");
        sqlBuilder.line("  FROM crm_warranty_deposit_adjustment_apply a WHERE a.status='3') as a ");
        sqlBuilder.line(" where 1=1 ");
        getConditionMap(map, sqlBuilder);
        return Db.queryLong(sqlBuilder.build(), sqlBuilder.params());
    }

    public Record countLimit(String traderId){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" SELECT IFNULL(t.bond_amount_limit,0) as bond_amount_limit,IFNULL(t.bzj_amount,0) as bzj_amount ,IFNULL(t.yk_bzj_amount,0) as ykBzjAmount ");
        sqlBuilder.line(" ,(SELECT SUM(CASE WHEN e.actual_capacity=0 THEN e.design_capacity ELSE e.actual_capacity END)  AS totalCapacity ");
        sqlBuilder.line("   FROM `crm_customer_entry` e   ");
        sqlBuilder.line("  WHERE e.distributor_id=? AND e.design_audit_flag in ('6','8','9') AND e.status<>'b' ) AS totalCapacity",traderId);
        sqlBuilder.line(" FROM `crm_trader_account` t WHERE t.`trader_id`=? ",traderId);
        return Db.findFirst(sqlBuilder.build(),sqlBuilder.params());
    }

    public Record countLimitTwo(String traderId){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT  IFNULL(t.bond_amount_limit,0) as bond_amount_limit,IFNULL(t.bzj_amount,0) as bzj_amount,(TRUNCATE((IFNULL(b.yazTotalCapacity,0)*1.5/10000),2)) as yazTotalCapacity ");
        sqlBuilder.line(" ,(TRUNCATE((IFNULL(b.ybwTotalCapacity,0)*1.5/10000),2)) as ybwTotalCapacity,IFNULL(c.deliverTotalAmount,0) as  deliverTotalAmount");
        sqlBuilder.line("   ,IFNULL(b.ybwTotalCapacity,0)*1.5 AS ybwTotalCapacity1,IFNULL(b.yazTotalCapacity,0)*1.5  AS yazTotalCapacity1 ,IFNULL(t.yk_bzj_amount,0) as ykBzjAmount, ");
        sqlBuilder.line("   \t IFNULL(t.yk_deliver_total_capacity,0) as yk_deliverTotalCapacity ,IFNULL(t.yk_yaz_total_capacity,0) as ykYazTotalCapacity ,IFNULL(t.yk_ybw_total_capacity,0) as ykYbwTotalCapacity ,IFNULL(t.yk_tkl_total_capacity,0) as ykTklTotalCapacity  ");
        sqlBuilder.line("  FROM   `crm_trader_account` t  ");
        sqlBuilder.line(" JOIN   (SELECT SUM(CASE WHEN e.material_fix_flag='1' THEN r.capacity ELSE 0 END) AS yazTotalCapacity, ");
        sqlBuilder.line("  SUM(CASE WHEN e.first_generation_time is not null THEN r.capacity ELSE 0 END) AS ybwTotalCapacity,e.distributor_id ");
        sqlBuilder.line(" FROM `crm_accepting_report` r LEFT JOIN `crm_customer_entry` e ON e.receiving_report_id=r.id  ");
        sqlBuilder.line("  WHERE e.material_fix_flag='1'  AND e.status<>'b' AND e.distributor_id=? ) AS b  ",traderId);
        sqlBuilder.line(" JOIN ( SELECT SUM(IFNULL(o.predict_amount,0)) AS deliverTotalAmount,o.trader_id FROM `crm_supply_material_deliver_order` o ");
        sqlBuilder.line("  WHERE o.type in ('1','2','4') AND o.order_examine_status in ('1','3')  AND o.status not in ('0','8','10') AND o.trader_id=?  )AS c  ",traderId);
        sqlBuilder.line("  WHERE t.`trader_id`=? ",traderId);
        return Db.findFirst(sqlBuilder.build(),sqlBuilder.params());
    }

    public Record getEdSetRecord(String traderId,String type){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("   SELECT d.amount,d.capacity_ratio,d.capacity_multiple,s.type  FROM `crm_account_set` s  ");
        sqlBuilder.line("  LEFT JOIN `crm_account_set_details` d ON s.id=d.set_id  ");
        sqlBuilder.line("  WHERE s.type=? ",type);
        sqlBuilder.line("  AND (d.range_tap='1' OR(d.range_tap='2' AND FIND_IN_SET(?,d.trader_id))) ORDER BY d.range_tap DESC LIMIT 1 ",traderId);
        return Db.findFirst(sqlBuilder.build(),sqlBuilder.params());
    }

    public int editAmount(String traderId,String type,String amount){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("update crm_trader_account");
        // type 1 友夸初始保证金余额  2 友夸初始已发货金额 3 友夸初始已安装金额 4 友夸初始已并网金额 5 友夸初始阶段踏勘量金额
        if (type.equals("1")){
            sqlBuilder.line(" set yk_bzj_amount = ?",amount);
        }else if (type.equals("2")){
            sqlBuilder.line(" set yk_deliver_total_capacity = ?",amount);
        }else if (type.equals("3")){
            sqlBuilder.line(" set yk_yaz_total_capacity = ?",amount);
        }else if (type.equals("4")){
            sqlBuilder.line(" set yk_ybw_total_capacity = ?",amount);
        }else if (type.equals("5")){
            sqlBuilder.line(" set yk_tkl_total_capacity = ?",amount);
        }
        sqlBuilder.line("where trader_id = ?",traderId);
        return Db.update(sqlBuilder.build(),sqlBuilder.params());
    }


    public List<Record> getListForExportExcel(Map<String,String> queryParams){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select t.name as traderName, t.contacts, t.telephone, concat(t.province, t.city, t.area, t.address) as traderAddress,a.bzj_amount")
                .line(" ,TRUNCATE((a.bzj_amount),2) as bzjAmount,TRUNCATE((a.bond_amount_limit),2) as bondAmountLimit ")
                .line(", a.basic_quota_amount, a.basic_quota_amount_bzj, a.basic_quota_amount_balance, a.bond_amount_limit ")
                .line(", a.max_quota_amount, a.max_quota_amount_bzj, a.max_quota_amount_balance")
                .line(", a.settle_amount, a.settle_amount_ysjs, a.qa_amount, a.qa_amount_usable, a.qa_amount_freeze, a.qa_amount_incdec,a.settle_deduction_amount ")
                .line(" ,a.bond_amount_limit,a.trader_id ");
            builder.line(" , \n" +
                    " IF((SELECT COUNT(o.id) FROM `crm_supply_material_deliver_order`  o WHERE o.trader_id=t.id  and  o.type in('1','2') and status not in('0','10') and order_examine_status <> '0' ) <> 0, (SELECT COUNT(o.id) FROM `crm_supply_material_deliver_order`  o WHERE o.trader_id=t.id  and  o.type in('1','2','4') and status not in('0','8','10') and order_examine_status in ('1','3') ),CAST(a.yk_deliver_total_capacity AS UNSIGNED)) as ifOne   ");  //判断是否是首发授信额
            builder.line(" ,TRUNCATE((IFNULL(c.deliverTotalAmount,0)),2) as deliverTotalAmount,(TRUNCATE((IFNULL(b.yazTotalCapacity,0)*1.5),2 )) as yazTotalCapacity");
            builder.line(" ,(TRUNCATE((IFNULL(b.ybwTotalCapacity,0)*1.5),2)) as ybwTotalCapacity,   ");
            builder.line(" a.yk_bzj_amount, a.yk_deliver_total_capacity, a.yk_yaz_total_capacity , a.yk_ybw_total_capacity ,a.yk_tkl_total_capacity ");
            builder.line(" from crm_trader_account a ");
            builder.line(" left join (SELECT SUM(CASE WHEN e.material_fix_flag='1' THEN r.capacity ELSE 0 END) AS yazTotalCapacity, ");
            builder.line("  SUM(CASE WHEN e.first_generation_time is not null THEN r.capacity ELSE 0 END) AS ybwTotalCapacity,e.distributor_id ");
            builder.line("  FROM `crm_accepting_report` r LEFT JOIN `crm_customer_entry` e ON e.receiving_report_id=r.id  ");
            builder.line(" WHERE e.material_fix_flag='1'  AND e.status<>'b' GROUP BY e.distributor_id) as b on b.distributor_id =a.trader_id ");
            builder.line(" left join ( SELECT SUM(IFNULL(o.predict_amount,0)) AS deliverTotalAmount,o.trader_id FROM `crm_supply_material_deliver_order` o ");
            builder.line(" WHERE o.type in('1','2','4')  AND o.order_examine_status in ('1','3') AND o.status not in ('0','8','10') GROUP BY o.trader_id  ) as c on c.trader_id =a.trader_id");
            builder.line("left join crm_trader t on a.trader_id=t.id");
            builder.line("where 1=1");
            appendListTraderCondition(builder, queryParams);
            return Db.find(builder.build(), builder.params());
    }
    public  int updateBasicQuotaAmountBalance(BigDecimal balance,String id){
        SqlBuilder sb = new SqlBuilder()
                .line(" update crm_trader_account set basic_quota_amount_balance = basic_quota_amount_balance + :balance ")
                .line(" where id=:id ");
        SQLQuery query = getSession().createSQLQuery(sb.build());
        query.setParameter("balance", balance);
        query.setParameter("id", id);
        return query.executeUpdate();
    }

    public  int updateAccountSettleAmount(BigDecimal settleAmount,BigDecimal settleAmountYsjs ,BigDecimal settleRewardsPunishAmount,String id){
        SqlBuilder sb = new SqlBuilder()
                .line(" update crm_trader_account set settle_amount = settle_amount + :settleAmount ,settle_amount_ysjs = settle_amount_ysjs + :settleAmountYsjs ,settle_rewards_punish_amount = settle_rewards_punish_amount - :settleRewardsPunishAmount ")
                .line(" where id=:id ");
        SQLQuery query = getSession().createSQLQuery(sb.build());
        query.setParameter("settleAmount", settleAmount);
        query.setParameter("settleAmountYsjs", settleAmountYsjs);
        query.setParameter("settleRewardsPunishAmount", settleRewardsPunishAmount);
        query.setParameter("id", id);
        return query.executeUpdate();
    }

}
