package com.palmnest.dao.estateserve.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.Page;
import com.palmnest.dao.estateserve.StaffDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.Staff;
import com.palmnest.model.StaffRelationBuild;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve Staff objects.
 *
 * @author yubing
 */
@Repository("staffDao")
public class StaffDaoImpl extends GenericDaoHibernate<Staff, Integer> implements StaffDao {

	public StaffDaoImpl() {
		super(Staff.class);
	}

	@Override
	public Page queryStaffList(int pageNo, int pageSize, String whereSQL) {
		StringBuffer strSQL = new StringBuffer("SELECT DISTINCT(t1.id) id,t1.`name`,t1.staffNo,t1.userMobile,t1.position,t1.`status`,t1.createTime,c.`name` as companyName,d.`name` as deptName");
		strSQL.append(" FROM tb_staff t1");
		strSQL.append(" INNER JOIN tb_company c on t1.companyId=c.ID");
		strSQL.append(" INNER JOIN tb_dept d on t1.deptId=d.ID");
		strSQL.append(" INNER JOIN tr_staff_org t2 ON t1.ID = t2.staffId");
		strSQL.append(" WHERE t1.isEnabled='1'");
		strSQL.append(whereSQL);
		strSQL.append(" order by t1.createTime desc");
		return pagedQueryByJdbcTemplate(strSQL.toString(), pageNo, pageSize);
	}

	@Override
	public Staff getStaffByStaffNoOrStaffId(String staffNo, String staffId) {
		String strHQL = "";
		if (StringUtils.isNotEmpty(staffId)) {
			strHQL = "from Staff where staffNo='" + staffNo + "' and id!=" + staffId;
		} else {
			strHQL = "from Staff where staffNo='" + staffNo + "'";
		}
		List<Staff> list = getSession().createQuery(strHQL).list();
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<StaffRelationBuild> getStaffRelationBuildList(int staffId) {
		String strHQL = "from StaffRelationBuild where staffId=?";
		return getSession().createQuery(strHQL).setInteger(0, staffId).list();
	}

	@Override
	public void deleteStaffRelation(int staffId) {
		String strSQL1 = "delete from tr_staff_build where staffid=" + staffId;
		String strSQL2 = "delete from tr_staff_org where staffid=" + staffId;
		getSession().createSQLQuery(strSQL1).executeUpdate();
		getSession().createSQLQuery(strSQL2).executeUpdate();
	}

	@Override
	public Page queryStaffListByOrganization(int pageNo, int pageSize,
											 String whereSQL, String organizationId) {
		StringBuffer strSQL = new StringBuffer("SELECT t1.id,t1.`name`,t1.staffNo,t1.userMobile");
		strSQL.append(" FROM tb_staff t1");
		strSQL.append(" INNER JOIN tr_staff_org t2 ON t1.ID = t2.staffId");
		strSQL.append(" WHERE t2.organizationId =" + organizationId + " and t1.isEnabled='1'");
		strSQL.append(whereSQL);
		return pagedQueryByJdbcTemplate(strSQL.toString(), pageNo, pageSize);
	}
}
