package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CrmAccountSet;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.stereotype.Repository;

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


@Repository
public class AccountSetDao extends BaseDao<CrmAccountSet> {

    public Record findByType(String type) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select *")
                .line("from crm_account_set")
                .line("where type=?", type);
        return Db.findFirst(builder.toString(), builder.params());
    }

    public Record getTraderVsAccount(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 CrmAccountSet getByType(String type){
        CrmAccountSet accountSet= getByHql("from CrmAccountSet where type =:p1 ", new Parameter(type));
        if(accountSet==null){
            accountSet=new CrmAccountSet();
            accountSet.setId(IdGen.uuid());
            accountSet.setProportion(BigDecimal.ZERO);
            accountSet.setType(type);
            accountSet.setCreateTime(new Date());
        }
        return accountSet;
    }

    public List<Record> getSetDetail(String type){
        List<Record> list=Db.find("   SELECT d.name,d.amount,d.range_tap,d.trader_id,d.capacity_ratio,d.capacity_multiple  FROM `crm_account_set_details` d " +
                "  LEFT JOIN `crm_account_set` s ON d.set_id=s.id " +
                "  WHERE s.type=? ",type);
        return list;
    }

    public List<Record> getAccountList(){
        List<Record> list=Db.find(" SELECT any_value(s.id) AS id,any_value(s.way) AS way,any_value(s.type)AS type,GROUP_CONCAT(s.content) AS content,any_value(s.proportion)AS proportion FROM `crm_account_set` s GROUP BY s.type");
        return list;
    }

}
