package com.sifang.modules.sunshine.SystemSetting.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSubconractorSettlementScheme;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

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

@Repository
public class SubconractorSettlementSchemeDao extends BaseDao<CrmSubconractorSettlementScheme> {

    public Record findByProjectId(String projectId, String traderId, Date ysDate) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select a.*")
                .line("from crm_subconractor_settlement_scheme a")
                .line("INNER JOIN crm_subconractor_settlement_scheme_apply b ON b.id = a.apply_id")
                .line("where a.status<>'0' and a.status<>'3' and find_in_set(?, a.project_ids) ", projectId)
                .line("AND (find_in_set(?, a.trader_ids) OR a.trader_ids IS NULL)", traderId);
        if(ysDate!=null){
            String day= DateUtils.formatDate(ysDate,"yyyy-MM-dd");
            String dayTime=DateUtils.formatDateTime(ysDate);
            sb.line(" AND a.create_time<=?  ",day)
                    .line(" AND ((a.status in ('1','4') AND  a.end_time>=?)  ",day)
                    .line(" OR (a.status='2' AND a.cancel_time>=? ))",dayTime);
        }
        sb.line("ORDER BY b.finish_time desc");
        return Db.findFirst(sb.build(), sb.params());
    }

    public Long getMaxVersion(){
        return Db.queryColumn("SELECT IFNULL(max(version),0) from crm_subconractor_settlement_scheme ");
    }

    public List<Record> getAllList(LayuiPage page, Map<String, String> map){
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT a.id,a.number, a.name, a.type, a.amount, a.enable_time,a.project_ids,a.project_names,a.apply_id,");
        sb.line("a.end_time,a.create_time,b.finish_time,a.status,");
        sb.line("ifnull(a.cancel_time,a.end_time) AS cancel_time");
        sb.line(" FROM `crm_subconractor_settlement_scheme` a ");
        sb.line(" INNER JOIN crm_subconractor_settlement_scheme_apply b ON b.id = a.apply_id");
        sb.line(" where a.status != '0' ");
        queryCondition(sb, map);
        sb.line(" order by a.enable_time desc, a.id desc ");
        sb.line(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        return Db.find(sb.build(), sb.params());
    }

    public long queryDataCount(Map<String, String> map) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select count(1) ");
        sb.line("FROM `crm_subconractor_settlement_scheme` a ");
        sb.line("INNER JOIN crm_subconractor_settlement_scheme_apply b ON b.id = a.apply_id");
        sb.line(" where a.status != '0'   ");
        queryCondition(sb, map);
        return Db.queryLong(sb.build(), sb.params());
    }

    public String queryCondition(SqlBuilder sb, Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return "";
        }
        if (StringUtils.isNotBlank(map.get("name"))) {
            sb.like(" and a.name like ? ", map.get("name").trim());
        }
        if (StringUtils.isNotBlank(map.get("type"))) {
            sb.line(" and a.type = ? ", map.get("type"));
        }
        if (StringUtils.isNotBlank(map.get("projectId"))) {
            sb.like(" and a.project_ids like ? ", map.get("projectId"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            sb.line(" and a.status = ? ", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("number"))) {
            sb.like(" and a.number like ? ", map.get("number").trim());
        }
        return sb.toString();
    }

    public void deleteShame(String applyId){
        SQLQuery sqlQuery = getSession().createSQLQuery("DELETE FROM crm_subconractor_settlement_scheme WHERE apply_id =:applyId");
        sqlQuery.setParameter("applyId", applyId);
        sqlQuery.executeUpdate();
    }

    public List<CrmSubconractorSettlementScheme> getCrmSubconractorSettlementSchemeList(){
        return find("FROM CrmSubconractorSettlementScheme WHERE status = '1' ");
    }

    public Long getSchemeByRepeat(String name, Date createTime, Date cancelTime, String projectIds) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("SELECT count(1) FROM crm_subconractor_settlement_scheme s WHERE s.name = ? and   s.project_ids = ? ", name,projectIds );
        sb.line("and  DATEDIFF(s.create_time, ? )  <= 0 and DATEDIFF(s.cancel_time, ? )  >= 0 and status = '1' " ,cancelTime,createTime);
        return Db.queryLong(sb.build(), sb.params());
    }
}
