package com.palmnest.dao.wechat.impl;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.dao.hibernate.GenericDaoHibernate;
import com.palmnest.dao.wechat.RechargeDao;
import com.palmnest.model.estateserve.Product;
import com.palmnest.model.estateserve.Recharge;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.*;

/**
 * 充值数据实现类
 *
 * @author xiemin
 */
@Slf4j
@Repository("rechargeDao")
public class RechargeDaoImpl extends GenericDaoHibernate<Recharge, Integer> implements RechargeDao {


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

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> findProduct(String province, String carrieroperator, String type, String isEnabled) {
		List<Product> list = new ArrayList<Product>();
		StringBuffer  sbf  = new StringBuffer();
		try {
			sbf.append("select * from tb_product where carrieroperator like '%").append(carrieroperator).append("%' and type='").append(type + "'");
			if ("0".equals(type)) {
				sbf.append(" and province='").append(province + "'");
			}
			if (null != isEnabled && !isEnabled.equals("")) {
				sbf.append(" and isEnabled=").append(isEnabled);
			}
			Query query = getSession().createSQLQuery(sbf.toString()).addEntity(Product.class);
			list = query.list();
		} catch (Exception e) {
			log.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return list;
	}

	@Override
	public int addRecharge(Map<String, String> map) throws Exception {
		Recharge re = new Recharge();
		try {
			if (null != map.get("rechargeId") && !map.get("rechargeId").equals("")) {
				re = this.get(Integer.valueOf(map.get("rechargeId")));
				re.setStatus(map.get("status"));
				re.setPayStatus(map.get("payStatus"));
				getSession().update(re);
			} else {
				re.setStatus("-1");//初始充值状态
				re.setPayStatus("-1");//未支付
				re.setType(map.get("type"));
				re.setOutTradeNo(map.get("outTradeNo"));
				re.setDevelopId(map.get("developId"));
				re.setOpenId(map.get("openId"));
				//通过openid找组织id
				if (null != map.get("organizationId") && !map.get("organizationId").equals("")) {
					re.setOrganizationId(map.get("organizationId"));
				}
				if (null != map.get("virtualArchitectureId") && !map.get("virtualArchitectureId").equals("")) {
					re.setVirtualId(map.get("virtualArchitectureId"));
				}
				if (null != map.get("number") && !map.get("number").equals("")) {
					re.setAmount(Integer.parseInt(map.get("number")));
				}
				re.setPrice(BigDecimal.valueOf(Double.valueOf(map.get("totalFee"))));
				re.setProductId(Integer.valueOf(map.get("productId")));
				re.setChannelCode(map.get("channelCode"));
				re.setIsEnabled(ElementConstant.YESORNO_1);
				re.setMobile(map.get("mobile"));
				re.setPayType(map.get("payWay"));
				re.setCreateTime(DateUtils.getDate(new Date(), DateUtils.YYYY_MM_DD_MM_HH_SS));
				re.setCreator(map.get("mobile"));
				getSession().save(re);
			}
			return re.getId();
		} catch (Exception e) {
			log.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> findProductById(int productId) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		StringBuffer        sbf = new StringBuffer();
//		sbf.append("select * from tb_product where id = ").append(productId);
		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 p.id = ").append(productId);

		try {
			Query query = getSession().createSQLQuery(sbf.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			map = (Map<String, String>) query.uniqueResult();
		} catch (Exception e) {
			log.error("findProductById occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
		return map;
	}

	@Override
	public Recharge findRechargeByOrdId(String ordId) throws Exception {
		Recharge     re  = new Recharge();
		StringBuffer sbf = new StringBuffer();
		sbf.append("select * from tb_recharge where outTradeNo = '").append(ordId + "'");

		try {
			Query query = getSession().createSQLQuery(sbf.toString()).addEntity(Recharge.class);
			re = (Recharge) query.uniqueResult();
		} catch (Exception e) {
			log.error("findRechargeByOrdId occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
		return re;
	}

	@Override
	public Recharge findRecharge(String id) throws Exception {
		Recharge     re  = new Recharge();
		StringBuffer sbf = new StringBuffer();
		sbf.append("select * from tb_recharge where id = ").append(id);

		try {
			Query query = getSession().createSQLQuery(sbf.toString()).addEntity(Recharge.class);
			re = (Recharge) query.uniqueResult();
		} catch (Exception e) {
			log.error("findRecharge occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			throw new Exception(e);
		}
		return re;
	}

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

	@Override
	public int updateRechargeOrdId(String ordId, int ststus) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb = sb.append("update tb_recharge as a set a.status =").append(ststus).append(" where a.outTradeNo='").append(ordId + "'");
		int result = -1;
		try {
			Query query = getSession().createSQLQuery(sb.toString());
			result = query.executeUpdate();
		} catch (Exception e) {
			log.info("updateRecharge：" + e.getCause() + e.getMessage());
			throw new Exception(e);
		}
		return result;
	}

	@Override
	public int updateRecharge(Recharge re) throws Exception {
		int result = -1;
		try {
			StringBuffer sb = new StringBuffer();
			sb = sb.append("update tb_recharge as a set a.status =").append(re.getStatus())
					.append(",a.transactionId=").append(re.getTransactionId());
			if (null != re.getPayStatus() && !re.getPayStatus().equals("")) {
				sb.append(",a.payStatus=").append(re.getPayStatus());
			}
			if (null != re.getRechargeDesc() && !re.getRechargeDesc().equals("")) {
				sb.append(",a.rechargeDesc='").append(re.getRechargeDesc() + "'");
			}
			if (null != re.getRecharTime() && !re.getRecharTime().equals("")) {
				sb.append(",a.recharTime='").append(re.getRecharTime() + "'");
			}
			sb.append(",a.wxUserId=").append(re.getWxUserId()).append(" where a.id=").append(re.getId());
			log.info("SQL:" + sb.toString());
			Query query = getSession().createSQLQuery(sb.toString());
			result = query.executeUpdate();
			return result;
		} catch (Exception e) {
			log.info("updateRecharge：" + e.getCause() + e.getMessage());
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getRechareByCreateTime(String openId, String dateTime, String endTime)
			throws Exception {
		String strSQL = "SELECT  DATE_FORMAT(createTime,'%Y-%m') createTime from tb_recharge where `status`!='-1'"
				+ " and openId='" + openId + "' and DATE_FORMAT(createTime,'%Y-%m') >= " + dateTime + " <= " + endTime + " GROUP BY DATE_FORMAT(createTime,'%Y-%m') ORDER BY DATE_FORMAT(createTime,'%Y-%m') DESC";
		return this.getJdbcTemplate().queryForList(strSQL);
	}

	@Override
	public List<Map<String, Object>> getRechareRecordList(String createTime,
														  String openId) throws Exception {
		String strSQL = "SELECT if(t1.amount is null,1,t1.amount) amount,t3.`name`,t3.iconUrl,t1.id,t2.carrieroperator,DATE_FORMAT(t1.createTime,'%Y-%m-%d') createTime,DATE_FORMAT(t1.createTime,'%m-%d') createTimes,t2.productName,t1.price,t1.mobile,t1.`status`,t2.type from tb_recharge t1"
				+ " LEFT JOIN tb_product t2 on t2.id=t1.productId "
				+ " LEFT JOIN tb_product_categories t3 on t2.type=t3.serviceCode and t3.isEnabled=1"
				+ " where t1.`status`!='-1' and t1.openId='" + openId + "' AND DATE_FORMAT(t1.createTime,'%Y-%m')='" + createTime + "'"
				+ " ORDER BY t1.createTime DESC";
		return this.getJdbcTemplate().queryForList(strSQL);
	}

	@Override
	public List<Map<String, Object>> getRechareRecordInfo(Integer id) {
		String strSQL = "SELECT if(t1.amount is null,1,t1.amount) amount,t3.`name`,t3.iconUrl,t1.refundStatus,t1.`status`,t1.mobile,t2.carrieroperator,DATE_FORMAT(t1.createTime,'%Y-%m-%d %H:%i:%s') createTime,t1.outTradeNo,t2.productName,t2.type,t1.price from tb_recharge t1"
				+ " INNER JOIN tb_product t2 on t1.productId=t2.id  "
				+ " LEFT JOIN tb_product_categories t3 on t1.type=t3.serviceCode and t3.isEnabled=1"
				+ " where t1.id=" + id;
		return this.getJdbcTemplate().queryForList(strSQL);
	}

	@Override
	public List<Recharge> getNoOrgRechargeList(String month) {
		String strHQL = "from Recharge where (status='0' or status='1') and createTime like '" + month + "%' and organizationId is null and isEnabled='1'";
		return getSession().createQuery(strHQL).list();
	}
}
