package com.sifang.modules.customer.dao;


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

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

@Repository
public class CrmReasonForApplicationDao extends BaseDao<CrmReasonForApplication> {

    public List<Record> getApplicationList(LayuiPage page, Map<String, String> map){
        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT m.* FROM `crm_reason_for_application` m WHERE m.status='1' ");
        sb.append(getCondtion(map));
        sb.append(" ORDER BY m.create_time DESC  ");
        if(page != null){
            sb.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        }
        return Db.find(sb.toString());
    }

    public Long reasonForApplicationCount(Map<String, String> map){
        StringBuffer sb=new StringBuffer();
        sb.append(" select count(m.id) from `crm_reason_for_application` m WHERE m.status='1' ");
        sb.append(getCondtion(map));
        return Db.queryLong(sb.toString());
    }

    public String getCondtion(Map<String, String> map){
        StringBuffer sb=new StringBuffer();
        if (StringUtil.checkParamsValid(map.get("name"))) {
            sb.append(" and  m.name like '%"+map.get("name") +"%' ");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeSta"))) {
            sb.append(" and m.create_time >= '" + map.get("createTimeSta") + " 00:00:00' ");
        }
        if (StringUtil.checkParamsValid(map.get("createTimeEnd"))) {
            sb.append(" and m.create_time <= '" + map.get("createTimeEnd") + " 23:59:59' ");
        }
        return sb.toString();
    }

    public Boolean checkName(String name,String id){
        StringBuffer sb=new StringBuffer();
        sb.append("   SELECT COUNT(m.id) FROM `crm_reason_for_application` m WHERE m.status='1' AND m.name=? ");
        if(StringUtil.isNotBlank(id)){
            sb.append(" AND m.id<>'"+ id +"' ");
        }
        long count=Db.queryLong(sb.toString(),name);
        return count>0?true:false;
    }

    public List<Record> listreasonForApplication() {
        return Db.find("SELECT t.`id`, t.`name` FROM `crm_reason_for_application` t WHERE t.`status` = '1' ORDER BY t.`create_time` DESC ");
    }
}
