package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CustomerRentVariableDao;
import com.sifang.modules.customer.entity.CustomerRentVariable;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerRentVariableService {
    @Autowired
    private CustomerRentVariableDao customerRentVariableDao;

    /**
     * 保存项目租金信息
     */
    public void saveEntryComponent(String entryId, String projectId) {
        List<CustomerRentVariable> crvList = new ArrayList<>();
        List<Record> prvList = customerRentVariableDao.getPRVList(projectId);
        for (Record prv : prvList) {
            CustomerRentVariable crv = new CustomerRentVariable();
            crv.setEntryId(entryId);
            crv.setStage(prv.getInt("stage"));
            crv.setStartYear(prv.getInt("start_year"));
            crv.setEndYear(prv.getInt("end_year"));
            crv.setUnitPrice(prv.getBigDecimal("unit_price"));
            crvList.add(crv);
        }
        customerRentVariableDao.save(crvList);
    }

    //删除旧的租金信息
    public void deleteRentVariable(String entryId){
        SQLQuery sqlQuery = customerRentVariableDao.getSession().createSQLQuery("DELETE FROM crm_customer_rent_variable WHERE entry_id= :entryId ");
        sqlQuery.setParameter("entryId", entryId);
        sqlQuery.executeUpdate();
    }

    public List<Record> getRentVariableList(String projectId) {
        return Db.find("SELECT stage,MIN(start_year) as start_year,MAX(end_year) as end_year,unit_price FROM crm_project_rent_variable WHERE project_id=? AND status = '0'  GROUP BY unit_price order by stage asc limit 2",projectId);
    }


    public List<Record> getRentVariableListByProjectIds(List<String> projectIds) {
        return Db.find("SELECT stage,MIN(start_year) as start_year,MAX(end_year) as end_year,unit_price,project_id FROM crm_project_rent_variable WHERE project_id in ("+ StringUtil.joinInSql(projectIds) +") AND status = '0' GROUP BY project_id,unit_price order by project_id asc ");
    }

}
