package com.palmnest.dao.estateserve.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.Pages;
import com.palmnest.dao.estateserve.ServicePackBasicsDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.estateserve.DepositItemInformationForm;

/**
 * 服务项管理实现DAO
 *
 * @author xiemin
 */
@Repository("servicePackBasicsDao")
public class ServicePackBasicsDaoImpl extends GenericDaoHibernate<DepositItemInformationForm, Integer>
		implements ServicePackBasicsDao {
	private Logger LOG = Logger.getLogger(ServicePackBasicsDaoImpl.class);

	public ServicePackBasicsDaoImpl() {
		super(DepositItemInformationForm.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pages<Map<String, String>> queryServicePackBasicsList(ModelMap modelMap) throws Exception {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Pages<Map<String, String>> page = new Pages<Map<String, String>>();
		try {
			int pageNo = Integer.valueOf(String.valueOf(modelMap.get("pageNo")));
			int pageSize = Integer.valueOf(String.valueOf(modelMap.get("pageSize")));
			StringBuffer sbf = new StringBuffer();
			sbf.append("select dif.id,dif.name,date_format(dif.createTime,'%Y-%m-%d %H:%i:%s') createTime,dif.price,dif.serviceTypeInfoId,st.serviceName")
					.append(" from tb_depositItem_information_form dif left join tb_serviceTypeInfo st on st.id = spb.serviceTypeInfoId where dif.isEnabled = 1");
			if (null != modelMap.get("name") && !modelMap.get("name").equals("")) {
				sbf.append(" and dif.name like '%").append(modelMap.get("name") + "%'");
			}
			if (null != modelMap.get("startTime") && !modelMap.get("startTime").equals("")) {
				sbf.append(" and dif.createTime >= '").append(modelMap.get("startTime") + "'");
			}
			if (null != modelMap.get("endTime") && !modelMap.get("endTime").equals("")) {
				sbf.append(" and dif.createTime <= '").append(modelMap.get("endTime") + "'");
			}
			if (null != modelMap.get("serviceTypeInfoId") && !modelMap.get("serviceTypeInfoId").equals("")) {
				sbf.append(" and dif.serviceTypeInfoId = '").append(modelMap.get("serviceTypeInfoId") + "'");
			}

			sbf.append(" order by dif.createTime desc ");
			Query query = getSession().createSQLQuery(sbf.toString());
			int count = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list().size();
			list = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).list();
			page.setPageList(list);
			page.setTotalCount(count);
			page.setCurPage(pageNo);
			page.setPageSize(pageSize);
			return page;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	@Override
	public int addServicePackBasics(Map<String, String> map) throws Exception {
		DepositItemInformationForm sp = new DepositItemInformationForm();
		try {
			if (null != map.get("id") && !map.get("id").equals("")) {
				sp = this.get(Integer.valueOf(map.get("id")));
			}
			sp.setDeposName(map.get("name"));
			sp.setServiceTypeInfoId(Integer.valueOf(map.get("serviceId")));
			sp.setPrice(BigDecimal.valueOf(Integer.valueOf(map.get("price"))));
			sp.setIsEnabled(ElementConstant.YESORNO_1);
			sp.setCreator(map.get("adminName"));
			if (null != map.get("id") && !map.get("id").equals("")) {
				sp.setModifyTime(new Date());
				sp.setModifier(map.get("adminName"));
				getSession().update(sp);
			} else {
				sp.setCreateTime(new Date());
				getSession().save(sp);
			}
			return sp.getId();
		} catch (Exception e) {
			LOG.info("addServicePack：" + e.getCause() + e.getMessage());
			throw new Exception("系统异常");
		}
	}

	@Override
	public int deleteServicePackBasics(Integer id, String isEnabled) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb = sb.append("update tb_depositItem_information_form as a set a.isEnabled =").append(isEnabled).append(" where a.id=").append(id);
		int result = -1;
		try {
			Query query = getSession().createSQLQuery(sb.toString());
			result = query.executeUpdate();
		} catch (Exception e) {
			LOG.info("deleteServicePackBasics：" + e.getCause() + e.getMessage());
			throw new Exception(e);
		}
		return result;
	}

	@Override
	public String findByName(String name) throws Exception {
		String sql = "select name from tb_depositItem_information_form where name = '" + name + "'";
		Object result = "";
		try {
			Query query = getSession().createSQLQuery(sql);
			result = query.uniqueResult();

			if (null != result && !result.equals("")) {
				return result.toString();
			}
		} catch (Exception e) {
			LOG.info("findByName：" + e.getCause() + e.getMessage());
			throw new Exception(e);
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> findDetails(int id) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		try {
			StringBuffer sbf = new StringBuffer();
			sbf.append("select dif.id,dif.name,date_format(dif.createTime,'%Y-%m-%d %H:%i:%s') createTime,dif.price,dif.serviceTypeInfoId,st.serviceName")
					.append(" from tb_depositItem_information_form dif left join tb_serviceTypeInfo st on st.id = spb.serviceTypeInfoId where dif.isEnabled = 1").append(" and spb.id = ").append(Integer.valueOf(id));
			Query query = getSession().createSQLQuery(sbf.toString());
			map = (Map<String, String>) query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).uniqueResult();
		} catch (Exception e) {
			throw new Exception(e);
		}
		return map;
	}
}
