package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CrmAcceptingReportDetail;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CrmAcceptingReportDetailDao extends BaseDao<CrmAcceptingReportDetail> {

    public List<CrmAcceptingReportDetail> findByEntryId(String entryId) {
        return find("from CrmAcceptingReportDetail where entryId = :p1", new Parameter(entryId));
    }

    public CrmAcceptingReportDetail findByEntryIdAndProjectId(String entryId, String projectId) {
        return getByHql("from CrmAcceptingReportDetail where entryId = :p1 and projectId = :p2", new Parameter(entryId,projectId));
    }

    public boolean deleteReportDetailByEntryId(String entryId){
        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT INTO `crm_accepting_report_detail_del` ")
                .append(" SELECT *, NOW() ")
                .append(" FROM `crm_accepting_report_detail` d ")
                .append(" WHERE d.`entry_id` =:entry_id");
        Query query = getSession().createSQLQuery(sql.toString());
        query.setParameter("entry_id", entryId);
        int update = query.executeUpdate();
        if (update < 1) {
            return false;
        }

        SQLQuery deleteQuery = getSession().createSQLQuery("DELETE FROM crm_accepting_report_detail WHERE entry_id=:id");
        deleteQuery.setParameter("id", entryId);
        int executed = deleteQuery.executeUpdate();
        return executed > 0;
    }

    public Record findDataByEntryIdAndProjectId(String entryId, String projectId){
        StringBuffer sb=new StringBuffer();
        sb.append("  SELECT * from crm_accepting_report_detail where entry_id = ? and project_id = ?");
        return Db.findFirst(sb.toString(),entryId,projectId);
    }

}
