package com.sifang.modules.account.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.entity.CrmTraderSupportSettleDetails;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class CrmTraderSupportSettleDetailsDao extends BaseDao<CrmTraderSupportSettleDetails> {

    public void supportAccountListData(LayuiPage<Record> page, Map<String, String> map){
        //DATE_FORMAT(s.create_time,'%Y-%m-%d %H:%i:%s') AS createTime
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT s.id,s.number,s.type,s.relate_order_number,s.amount,s.trader_id,s.take_amount_unit, ");
        sqlBuilder.line("  s.take_amount_account,s.rate,t.name AS traderName,s.create_time,DATE_FORMAT(s.create_time,'%Y-%m-%d %H:%i:%s') AS createTime,relate_order_id   ");
        sqlBuilder.line(" FROM `crm_trader_support_settle_details` s LEFT JOIN  `crm_trader` t ON s.trader_id=t.id  ");
        sqlBuilder.line("  WHERE s.status='1' ");
        getCondition(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 = getSupportAccountListCount(map);
            page.setCount(count);
        }
        List<Record> list=Db.find(sqlBuilder.build(),sqlBuilder.params());
        page.setData(list);

    }


    public Long getSupportAccountListCount(Map<String,String> map){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line("  SELECT COUNT(s.id) FROM `crm_trader_support_settle_details` s ");
        sqlBuilder.line(" WHERE  s.status='1' ");
        getCondition(map,sqlBuilder);
        return Db.queryLong(sqlBuilder.build(), sqlBuilder.params());
    }

    public void getCondition(Map<String, String> map, SqlBuilder sf){
        if(StringUtil.isNotBlank(map.get("type"))){
            sf.line(" AND s.type = ? ", map.get("type"));
        }
        if(StringUtil.isNotBlank(map.get("createTimeSta"))) {
            sf.line("AND s.create_time >= ?", map.get("createTimeSta") + " 00:00:00");
        }
        if(StringUtil.isNotBlank(map.get("createTimeEnd"))) {
            sf.line("AND s.create_time <= ?", map.get("createTimeEnd") + " 23:59:59");
        }
        if (StringUtil.isNotBlank(map.get("traderId"))) {
            sf.inst(" AND s.trader_id in ", map.get("traderId").split(","));
        }
    }


}
