package com.sifang.modules.customer.dao;

import com.jfinal.plugin.activerecord.Db;
import com.sifang.modules.customer.entity.CrmCustomerYxCondition;
import com.sifang.modules.sys.common.persistence.BaseDao;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CrmCustomerYxConditionDao extends BaseDao<CrmCustomerYxCondition> {

    /**
     * 清除当前项目下的方案物料明细信息
     */
    public CrmCustomerYxCondition addYxCondition(String id, String name,String mobile,String idCode,
                               String preaudit,String authorization,String signFlowId,String partnerId,String filingType) {
        CrmCustomerYxCondition one = new CrmCustomerYxCondition();
        one.setId(id);
        one.setName(name);
        one.setMobile(mobile);
        one.setIdCode(idCode);
        one.setPreaudit(preaudit);
        one.setAuthorization(authorization);
        one.setSignFlowId(signFlowId);
        one.setPartnerId(partnerId);
        one.setFilingType(filingType);
        save(one);
        return one;
    }

    public CrmCustomerYxCondition findCustomerYxCondition(String idCode,String partnerId) {
        String sql = "from CrmCustomerYxCondition WHERE idCode =:p1 and partner_id=:p2";
        Query query = getSession().createQuery(sql);
        query.setParameter("p1", idCode);
        query.setParameter("p2", partnerId);
        List list = query.list();
        if (list.size() > 0) {
            return (CrmCustomerYxCondition) list.get(0);
        } else {
            return null;
        }
    }
    public CrmCustomerYxCondition findCustomerYxCondition(String idCode,String partnerId,String filingType) {
        String sql = "from CrmCustomerYxCondition WHERE idCode =:p1 and partner_id=:p2 and filingType=:p3";
        Query query = getSession().createQuery(sql);
        query.setParameter("p1", idCode);
        query.setParameter("p2", partnerId);
        query.setParameter("p3", filingType);
        List list = query.list();
        if (list.size() > 0) {
            return (CrmCustomerYxCondition) list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 删除预审记录
     */
    public boolean updateToDelete(String id) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO crm_customer_yx_condition_del ");
        sb.append("SELECT a.id, a.name, a.`mobile`, a.`id_code`, a.`authorization`, a.`preaudit`, ");
        sb.append("a.`preaudit_reason`, a.`sign_flow_id`, a.`tenant_code`, a.`authorization_contract_path`, NOW() ");
        sb.append("FROM crm_customer_yx_condition a ");
        sb.append("WHERE a.id = ? ");
        Db.update(sb.toString(), id);
        SQLQuery sqlQuery = getSession().createSQLQuery("DELETE FROM crm_customer_yx_condition where id = :id  ");
        sqlQuery.setParameter("id", id);
        int cou = sqlQuery.executeUpdate();
        return cou > 0;
    }

}
