package com.iamberry.rent.service.rebate;

import java.util.List;
import java.util.Map;

import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.tools.PayUtil;
import com.iamberry.wechat.tools.ResponseJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.rent.face.rebate.OrderRebateService;
import com.iamberry.rent.service.machine.mapper.MachineMapper;
import com.iamberry.rent.service.order.mapper.RentOrderMapper;
import com.iamberry.rent.service.order.mapper.ServiceCouponMapper;
import com.iamberry.rent.service.rebate.mapper.OrderRebateMapper;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.core.entity.rent.MachineInfo;
import com.iamberry.wechat.core.entity.rent.PledgeCouponInfo;
import com.iamberry.wechat.core.entity.rent.RebateRecord;
import com.iamberry.wechat.core.entity.rent.RebateType;
import com.iamberry.wechat.core.entity.rent.RentOrder;
import com.iamberry.wechat.core.entity.rent.RentOrderDTO;
import com.iamberry.wechat.core.entity.rent.RentOrderItem;
import com.iamberry.wechat.core.entity.rent.RentOrderItemDTO;
import com.iamberry.wechat.core.entity.rent.RentTypeInfo;
import com.iamberry.wechat.core.entity.rent.ServiceCouponInfo;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.relationship.WdRelationService;

/**
 * @author Administrator
 */
@Service
public class OrderRebateServiceImpl implements OrderRebateService{
	
	@Autowired
	private OrderRebateMapper orderRebateMapper;
	@Autowired
	private MemberService memberService;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private WdRelationService wdRelationService;
	@Autowired
	private OrderRebateService orderRebateService;
	@Autowired
	private RentOrderMapper rentOrderMapper;
	@Autowired
	private MachineMapper machineMapper;
	@Autowired
	private ServiceCouponMapper serviceCouponMapper;
	
	@Override
	public RentTypeInfo getRebateType(RentTypeInfo rentTypeInfo) {
		// TODO Auto-generated method stub
		return orderRebateMapper.getRebateType(rentTypeInfo);
	}

	@Override
	public boolean saveRentOrderRebate(String rentOrderId, String openId) {
		// TODO Auto-generated method stub
		
		//获取用户信息
		Member member = memberService.getMemberByUserOpenId(openId);
		if (member == null) {
			logger.error(this, "--saveRentOrderRebate--:" + openId + "没有查到对应的用户信息");
			return false;
		}
		//如果来源为2，则上线是微代理
		if (member.getUserResType() != null && member.getUserResType().intValue() == 2) {
			WdRelation wdRelation = wdRelationService.getWdRelationByOpenid(openId);
			if (wdRelation == null) {
				logger.error(this, "--saveRentOrderRebate--:" + openId + "用户关系有误");
				return false;
			}
			int userId = wdRelation.getWdFirst();
			//根据上级id查询上级用户信息
			Member resMember = memberService.getMemberByUserId(userId);
			if (resMember == null) {
				logger.error(this, "--saveRentOrderRebate--:userId=" + userId + ",没有查到对应的用户信息");
				return false;
			}
			RentOrderDTO rentOrder = new RentOrderDTO();
			rentOrder.setRentOpenid(resMember.getUserOpenid());
			rentOrder.setRentStatus(5);
			MachineInfo machineInfo = new MachineInfo();
			machineInfo.setMachineOpenid(resMember.getUserOpenid());
			machineInfo.setMachineInitState(1);
			//查询订单集合
			List<RentOrderDTO> orderList = rentOrderMapper.listRentOrder(rentOrder);
			//如果该上线没有租赁该商品或已退款，则不返利
			if (orderList == null || orderList.size() == 0) {
				logger.error(this, "--saveRentOrderRebate--:userId=" + userId + "没有租赁该商品或已退款，所以不返利");
				return true;
			}
			//用来存放被激活的机器数量
			int rentNum = 0;
			//如果租赁了该商品，则循环对比，是否有押金，如果有则返利模式为1，如果没有，返利模式则为2
			int type = 0;
			for (RentOrderDTO order : orderList) {
				if (order.getOrderItemList() == null || order.getOrderItemList().size() == 0) {
					logger.error(this, "--saveRentOrderRebate--:userId=" + userId + "有订单没有订单项");
					return false;
				}
				for (RentOrderItemDTO item : order.getOrderItemList()) {
					if (item.getRentDeposit() != null && item.getRentDeposit().intValue() > 0) {
						type = order.getRentTypeId().intValue();
					}
					if (item.getItemCodeState().intValue() == 2) {
						rentNum++;
					}
				}
			}
			//如果该值为0，则表示没有激活的机器，因而不参与返利
			if (rentNum == 0) {
				logger.error(this, "--saveRentOrderRebate--:userId=" + userId + "租赁订单商品没有被激活，不返利");
				return true;
			}
			//目前为止，2和3只是租赁方式不同，但返利相同，所以暂定为2
			if (type == 0 ) {
				type = 2;
			}
			//封装返利信息，查询之前返利的数量
			RebateRecord rebateRecord = new RebateRecord();
			rebateRecord.setRecordOpenid(resMember.getUserOpenid());
			rebateRecord.setRecordStatus(5);
			//查询之前返利的数量
			List<RebateRecord> rebateList = orderRebateMapper.listRebateRecord(rebateRecord);
			//之前返利数量 + 1 = 这次返利该查询的返利层级
			int rebateLevel = rebateList.size() + 1;
			orderRebateService.saveRebateRecord(rentOrderId, type, openId, resMember.getUserOpenid(), rebateLevel);
		}
		return true;
	}
	
	/**
	 * 
	 * @param rentOrderId	返利订单id
	 * @param type		返利类型id
	 * @param openId	返利人
	 * @param resOpenId	被返利人
	 * @param rebateLevel	返利层级
	 * @return
	 */
	@Override
	public boolean saveRebateRecord(String rentOrderId, int type, String openId, String resOpenId, int rebateLevel) {
		//封装返利类型
		RebateType rebateType = new RebateType();
		rebateType.setRebateLevel(rebateLevel);
		rebateType.setRebateTypeId(type);
		rebateType.setRebateStatus(1);
		//根据层次，返利类型查询这次返利该返的内容
		RebateType rebate = orderRebateMapper.getOneRebateType(rebateType);
		
		//封装返利信息，查询之前返利的数量
		RebateRecord record = new RebateRecord();
		record.setRecordOpenid(resOpenId);
		record.setRecordRentOpenid(openId);
		record.setRecordStatus(5);
		//查询该购买人是否之前就给该上线返利过，如果有，则不再返利
		List<RebateRecord> rebateRecordList = orderRebateMapper.listRebateRecord(record);
		//将查询的数据保存到待返利表中
		RebateRecord rebateRecord = new RebateRecord();
		rebateRecord.setRecordOrderId(rentOrderId);
		rebateRecord.setRecordOpenid(resOpenId);
		rebateRecord.setRecordRentOpenid(openId);
		rebateRecord.setRecordTypeId(type);
		//如果为空，则该数据不返利
		if (rebate == null || (rebateRecordList != null && rebateRecordList.size() > 0)) {
			logger.error(this, "--saveRebateRecord--:openId=" + openId + "因返利层次超出或已经给"+resOpenId+"返利，所以不再返利");
			return true;
		} else {
			//获取返利标识，确定该返利的东西
			int identify = rebate.getRebateIdentify();
			switch (identify) {
			case 1:
				rebateRecord.setRecordIdentify(1);
				rebateRecord.setRecordMoney(rebate.getRebateMoney());
				rebateRecord.setRecordStatus(2);
				break;
			case 2:
				rebateRecord.setRecordIdentify(2);
				rebateRecord.setRecordStatus(3);
				ServiceCouponInfo couponInfo = new ServiceCouponInfo();
				couponInfo.setServiceName("服务费抵扣券");
				couponInfo.setServiceMoney(rebate.getRebateDeductionMoney());
				couponInfo.setServiceOpenId(resOpenId);
				couponInfo.setServiceStatus(1);
				serviceCouponMapper.saveServiceCoupon(couponInfo);
				rebateRecord.setRecordDeductionId(couponInfo.getServiceId());
				break;
			case 3:
				rebateRecord.setRecordIdentify(3);
				rebateRecord.setRecordStatus(3);
				PledgeCouponInfo pledgeCouponInfo = new PledgeCouponInfo();
				pledgeCouponInfo.setPledgeName("押金提取券");
				pledgeCouponInfo.setPledgeOpenId(resOpenId);
				pledgeCouponInfo.setPledgeMoney(rebate.getRebateReplaceMoney());
				pledgeCouponInfo.setPledgeStatus(1);
				serviceCouponMapper.savePledgeCoupon(pledgeCouponInfo);
				rebateRecord.setRecordReplaceId(pledgeCouponInfo.getPledgeId());
				break;
			}
			int recordNum = orderRebateMapper.saveRebateRecord(rebateRecord);
			if (recordNum > 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	@Override
	public Map<String, Object> listPayRebate(int pageSize, int pageNO, boolean isPageTotal) {
		Map<String, Object> result = new java.util.HashMap<String, Object>(pageSize);
		// 组织分页数据
		PaperBean paperBean = new PaperBean();
		paperBean.setPaperData(pageNO, pageSize);

		// 查询
		List<RebateRecord> list = orderRebateMapper.listPayRebate(paperBean.getMinNum(), paperBean.getMaxNum());
		if (isPageTotal) result.put("pageTotal", PaperBean.justPaperCount(orderRebateMapper.countPayRebate(), pageSize));
		result.put("list", list);

		return result;
	}

	@Override
	public ResponseJson transPay(Integer id) {

		RebateRecord rebateRecord = orderRebateMapper.get(id);
		if (rebateRecord.getRecordMoney() == null || rebateRecord.getRecordIdentify() != 1 || rebateRecord.getRecordStatus() != 2) {
			// 返利记录有误，不支持现金返利
			return new ResponseJson(500, "SUCCESS", 200);
		}

		// 提前修改数据状态,防止并发，但是无法撤回转账,在此就需要获取行锁，到事务提交时释放
		Integer count = orderRebateMapper.updateRebate(id);
		if (count == null || count <= 0) {
			return new ResponseJson(404, "ERROR", 200);
		}

		ResponseJson res = PayUtil.transferPay(rebateRecord.getRecordOpenid(), rebateRecord.getRecordOrderId(), rebateRecord.getRecordMoney(), "订单返利");
		if (res.getReturnCode() == 200 && res.getResultCode() == 200) {
			return res;
		}
		throw new RuntimeException();
	}

	@Override
	public List<RentTypeInfo> listRebateType(RentTypeInfo rentTypeInfo) {
		// TODO Auto-generated method stub
		return orderRebateMapper.listRebateType(rentTypeInfo);
	}
}
