package com.palmnest.dao.estateserve.impl;

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

import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.ui.ModelMap;

import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.dao.estateserve.RechargeWebDao;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.model.estateserve.Product;
import com.palmnest.model.estateserve.Recharge;
import com.palmnest.service.wechat.RechargeManager;

/**
 * 充值数据实现类
 *
 * @author xiemin
 */
@Repository("rechargeWebDao")
public class RechargeWebDaoImpl extends GenericDaoHibernate<Recharge, Integer>
		implements RechargeWebDao {
	private static Logger LOG = LoggerFactory.getLogger(RechargeWebDaoImpl.class);

	public RechargeWebDaoImpl() {
		super(Recharge.class);
	}

	@Autowired
	RechargeManager rechargeManager;

	@SuppressWarnings("unchecked")
	@Override
	public Pagenation<Map<String, String>> queryRechargeList(ModelMap modelMap) throws Exception {
		List<Map<String, String>> list = new ArrayList<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 r.id,r.mobile,r.status,r.price,r.type,date_format(r.recharTime,'%Y-%m-%d %H:%i:%s') recharTime,r.wxUserId,r.msgid,r.transactionId,r.payStatus,p.productPrice,r.outTradeNo,org.name oname,v.name vname,r.channelCode,r.amount," +
					"date_format(r.createTime,'%Y-%m-%d %H:%i:%s') createTime,p.productName,p.province,p.carrieroperator,p.id productId,r.refundStatus,date_format(r.refundTime,'%Y-%m-%d %H:%i:%s') refundTime from tb_recharge r left join tb_product " +
					"p on p.id = r.productId left join tb_organization org on org.id = r.organizationId left join tb_virtualarchitecture v on v.id = r.virtualId where r.isEnabled = 1 and r.payStatus <> -1 and r.status <> -1");
			if (null != modelMap.get("mobile") && !modelMap.get("mobile").equals("")) {
				sbf.append(" and r.mobile = ").append(modelMap.get("mobile"));
				sbf.append(" or p.productName = ").append(modelMap.get("mobile"));
				sbf.append(" or r.transactionId = ").append(modelMap.get("mobile"));
				sbf.append(" or r.outTradeNo = ").append(modelMap.get("mobile"));
			}
			if (null != modelMap.get("type") && !modelMap.get("type").equals("")) {
				sbf.append(" and r.type = '").append(modelMap.get("type") + "'");
			}
			if (null != modelMap.get("productName") && !modelMap.get("productName").equals("")) {
				sbf.append(" and p.productName = '").append(modelMap.get("productName") + "'");
			}
			if (null != modelMap.get("wxUserId") && !modelMap.get("wxUserId").equals("")) {
				sbf.append(" and r.wxUserId = ").append(modelMap.get("wxUserId"));
			}
			if (null != modelMap.get("id") && !modelMap.get("id").equals("")) {
				sbf.append(" and r.id = ").append(modelMap.get("id"));
			}
			if (null != modelMap.get("carrieroperator") && !modelMap.get("carrieroperator").equals("")) {
				sbf.append(" and p.carrieroperator = '").append(modelMap.get("carrieroperator") + "'");
			}
			if (null != modelMap.get("province") && !modelMap.get("province").equals("")) {
				sbf.append(" and p.province = ").append(modelMap.get("province"));
			}
			if (null != modelMap.get("status") && !modelMap.get("status").equals("")) {
				sbf.append(" and r.status = ").append(modelMap.get("status"));
			}
			if (null != modelMap.get("payStatus") && !modelMap.get("payStatus").equals("")) {
				sbf.append(" and r.payStatus = ").append(modelMap.get("payStatus"));
			}
			if (null != modelMap.get("startTime") && !modelMap.get("startTime").equals("")) {
				sbf.append(" and r.createTime >= '").append(modelMap.get("startTime") + "'");
			}
			if (null != modelMap.get("endTime") && !modelMap.get("endTime").equals("")) {
				sbf.append(" and r.createTime <= '").append(modelMap.get("endTime") + "'");
			}

			sbf.append(" order by r.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();
			return new Pagenation<Map<String, String>>(list, pageNo, count, pageSize);
		} catch (Exception e) {
			LOG.error("queryRechargeList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagenation<Map<String, String>> queryProductList(ModelMap modelMap) throws Exception {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {
			//isEnabled:0 维护，1正常
			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 p.id,p.province,p.productName,p.type,p.realPrice,p.carrieroperator,p.productPrice,p.upDiscount,p.discount,date_format(p.createTime,'%Y-%m-%d %H:%i:%s') createTime,p.isEnabled,p.code,pc.serviceCode,p.checkPrice from tb_product p" +
					" left join tb_product_categories pc on pc.serviceCode = p.type where 1 = 1");
			if (null != modelMap.get("province") && !modelMap.get("province").equals("")) {
				sbf.append(" and p.province like '%").append(modelMap.get("province") + "%'");
			}
			if (null != modelMap.get("carrieroperator") && !modelMap.get("carrieroperator").equals("")) {
				sbf.append(" and p.carrieroperator like '%").append(modelMap.get("carrieroperator") + "%'");
			}
			if (null != modelMap.get("startTime") && !modelMap.get("startTime").equals("")) {
				sbf.append(" and p.createTime >= '").append(modelMap.get("startTime") + "'");
			}
			if (null != modelMap.get("endTime") && !modelMap.get("endTime").equals("")) {
				sbf.append(" and p.createTime <= '").append(modelMap.get("endTime") + "'");
			}
			if (null != modelMap.get("type") && !modelMap.get("type").equals("")) {
				sbf.append(" and p.type = '").append(modelMap.get("type") + "'");
			}

			sbf.append(" order by p.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();
			return new Pagenation<Map<String, String>>(list, pageNo, count, pageSize);
		} catch (Exception e) {
			LOG.error("queryProductList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@Override
	public int addProduct(Product pro) throws Exception {
		try {
			getSession().save(pro);
			return pro.getId();
		} catch (Exception e) {
			LOG.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@Override
	public int updateProduct(Map<String, String> map) throws Exception {
		try {
			//all:0 单个，1：全部
//        	if(null != map.get("id") && !map.get("id").equals("") && map.get("all").equals("0")){
//        		Product pr = new Product();
//        		pr = rechargeManager.findProductById(Integer.valueOf(map.get("id")));
//        		//上浮折扣率+运营商折扣率
//        		BigDecimal upDiscount=new BigDecimal(map.get("upDiscount"));
//        		BigDecimal discount=new BigDecimal(map.get("discount"));
//        		BigDecimal productPrice=new BigDecimal(map.get("productPrice"));
//        		double price=productPrice.multiply(upDiscount.add(discount)).doubleValue();
//    			pr.setRealPrice(BigDecimal.valueOf(price));
//        		pr.setUpDiscount(BigDecimal.valueOf(Double.valueOf(map.get("upDiscount"))));
//        		pr.setProductPrice(BigDecimal.valueOf(Double.valueOf(map.get("productPrice"))));
//        		pr.setDiscount(BigDecimal.valueOf(Double.valueOf(map.get("discount"))));
//        		pr.setIsEnabled(map.get("isEnabled"));
//        		
//        		getSession().update(pr);
//        		return pr.getId();
//        	}else{
			BigDecimal upDiscount = new BigDecimal(map.get("upDiscount"));
			BigDecimal discount = new BigDecimal(map.get("discount"));
			BigDecimal productPrice = new BigDecimal(map.get("productPrice"));
			double price = productPrice.multiply(upDiscount.add(discount)).doubleValue();
			StringBuffer sb = new StringBuffer();
			sb = sb.append("update tb_product as a set a.isEnabled =").append(map.get("isEnabled"))
					.append(",a.realPrice = ").append(price).append(",a.upDiscount=").append(upDiscount)
					.append(",a.productPrice=").append(productPrice).append(",a.discount=").append(discount)
					.append(" where a.id=").append(map.get("id"));

			Query query = getSession().createSQLQuery(sb.toString());
			return query.executeUpdate();
//        	}
		} catch (Exception e) {
			LOG.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@Override
	public int updateAvailable(Map<String, String> map) throws Exception {
		try {
			StringBuffer sb = new StringBuffer();
			sb = sb.append("update tb_product as a set a.isEnabled =").append(map.get("status"))
					.append(" where a.id=").append(map.get("id"));
			Query query = getSession().createSQLQuery(sb.toString());
			return query.executeUpdate();
		} catch (Exception e) {
			LOG.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, String>> findProduct(String serviceCode, String type) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		StringBuffer sbf = new StringBuffer();
		try {
			sbf.append("select p.id,p.code,p.checkPrice,p.productPrice from tb_product p left join tb_product_categories pc on pc.serviceCode = p.type where pc.serviceCode = '").append(serviceCode).append("' and p.type='").append(type + "'");
			Query query = getSession().createSQLQuery(sbf.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			list = query.list();
		} catch (Exception e) {
			LOG.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return list;
	}
}
