package com.github.wxiaoqi.security.admin.biz;

import cn.hutool.core.map.MapUtil;
import com.github.wxiaoqi.security.admin.entity.BaseUserMember;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.entity.MemberShareCountRecord;
import com.github.wxiaoqi.security.admin.entity.MemberShareRecord;
import com.github.wxiaoqi.security.admin.mapper.BaseUserMemberLevelMapper;
import com.github.wxiaoqi.security.admin.mapper.MemberShareRecordMapper;
import com.github.wxiaoqi.security.admin.util.DateUtils;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.entity.OrderMemberDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员分成记录
 *
 * @author jiaoruizhen
 * @email jiaoruizhen@126.com
 * @date 2020-11-03 11:12:15
 */
@Service
@Slf4j
public class MemberShareRecordBiz extends BaseBiz<MemberShareRecordMapper, MemberShareRecord> {

	@Autowired
	MemberShareCountRecordBiz memberShareCountRecordBiz;
	@Autowired
	BaseUserMemberBiz baseUserMemberBiz;
	@Autowired
	BaseUserMemberLevelMapper  baseUserMemberLevelMapper;
	/**
	 * 根据订单号查询分成记录
	 * 每个订单有且只有一条记录
	 * @param no
	 * @return
	 */
	public MemberShareRecord getOneByOrderNo(String no) {
		Example example = new Example(MemberShareRecord.class);
		example.createCriteria().andEqualTo("orderNo", no);
		return mapper.selectOneByExample(example);
	}

	/**
	 * 新增或者编辑会员分成记录
	 * @param memberShareRecord
	 */
	public void addUpdate(MemberShareRecord memberShareRecord) {
		if (memberShareRecord != null) {
			MemberShareRecord old = getOneByOrderNo(memberShareRecord.getOrderNo());
			if (old == null) {
				insertSelectiveRe(memberShareRecord);
				updateAllLevelInfo(memberShareRecord);
			} else {
				if (StringUtils.isNotBlank(memberShareRecord.getMemberIds())) {
					old.setMemberIds(memberShareRecord.getMemberIds());
				}
				if (memberShareRecord.getMemberNum() != null) {
					old.setMemberNum(memberShareRecord.getMemberNum());
				}
				if (memberShareRecord.getAmount() != null) {
					old.setAmount(memberShareRecord.getAmount());
				}
				updateSelectiveByIdRe(old);
				updateAllLevelInfo(old);
			}
		}
		generateData();
	}

	/**
	 * 查看某一用户分成记录明细
	 * @return
	 */
	public ObjectRestResponse<List<MemberShareRecord>> getAllRecord(Long userId) {
		Example example = new Example(MemberShareRecord.class);
		example.createCriteria().andLike("memberIds", "%," + userId + ",%");
		return ObjectRestResponse.succ(mapper.selectByExample(example));
	}

	/**
	 * 更新相同会员等级的分成信息
	 * @param memberShareRecord
	 */
	public void updateAllLevelInfo(MemberShareRecord memberShareRecord) {
		if (memberShareRecord != null && memberShareRecord.getMemberLevel() != null) {
			List<MemberShareRecord> list = getAllByLevel(memberShareRecord.getMemberLevel());
			if (list != null && list.size() > 0) {
				list.parallelStream().forEach(record -> {
					if (StringUtils.isNotBlank(memberShareRecord.getMemberIds())) {
						record.setMemberIds(memberShareRecord.getMemberIds());
					}
					if (memberShareRecord.getMemberNum() != null) {
						record.setMemberNum(memberShareRecord.getMemberNum());
					}
					if (memberShareRecord.getAmount() != null) {
						record.setAmount(memberShareRecord.getAmount());
					}
					updateSelectiveByIdRe(record);
				});
			}
		}
	}

	/**
	 * 获取同级别的所有分成记录
	 * @param level
	 * @return
	 */
	private List<MemberShareRecord> getAllByLevel(Integer level) {
		Example example = new Example(MemberShareRecord.class);
		example.createCriteria().andEqualTo("memberLevel", level);
		return mapper.selectByExample(example);
	}

	/**
	 * 根据日期查询所有分成记录
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	private List<MemberShareRecord> getAllByDate(Long startDate, Long endDate) {
		Example example = new Example(MemberShareRecord.class);
		example.createCriteria().andBetween("payTime", startDate, endDate);
		return mapper.selectByExample(example);
	}

	/**
	 * 统计分成信息
	 */
	public  void generateData() {
		DateTime dateTime = DateTime.now().minusMonths(1);
		Long startDate = DateUtils.getStartOfDay(dateTime.toDate());
		Long endDate = DateUtils.getEndOfDay(dateTime.toDate());
		List<MemberShareRecord> list = getAllByDate(startDate, endDate);
		if (list != null && list.size() > 0) {
			Map<Integer, List<MemberShareRecord>> groupedMap =
					list.stream().collect(Collectors.groupingBy(MemberShareRecord::getMemberLevel));
			if (MapUtil.isNotEmpty(groupedMap)) {
				for (Map.Entry<Integer, List<MemberShareRecord>> entry : groupedMap.entrySet()) {
					Integer level = entry.getKey();
					List<MemberShareRecord> memberShareRecordList = entry.getValue();
					generateDataByUser(memberShareRecordList, level, dateTime);
				}
			}
		}
	}


	private  void generateDataByUser(List<MemberShareRecord> memberShareRecordList, Integer level, DateTime dateTime) {
		if (memberShareRecordList != null) {
			Map<Long, BigDecimal> amountMap = new HashMap<>();
			memberShareRecordList.parallelStream().forEach(memberShareRecord -> {
				if (StringUtils.isNotBlank(memberShareRecord.getMemberIds())) {
					String[] arr = memberShareRecord.getMemberIds().split(",");
					if (arr != null) {
						for (String id : arr) {
							if (StringUtils.isNotBlank(id)) {
								Long userId = Long.parseLong(id);
								if (amountMap.get(userId) != null) {
									amountMap.put(userId, amountMap.get(userId).add(memberShareRecord.getAmount()));
								} else {
									amountMap.put(userId, memberShareRecord.getAmount());
								}
							}
						}
					}
				}
			});

			if (MapUtil.isNotEmpty(amountMap)) {
				List<MemberShareCountRecord> memberShareCountRecordList = new ArrayList<>();
				for (Map.Entry<Long, BigDecimal> entry : amountMap.entrySet()) {
					MemberShareCountRecord memberShareCountRecord = new MemberShareCountRecord();
					memberShareCountRecord.setUserId(entry.getKey());
					memberShareCountRecord.setAmount(entry.getValue());
					memberShareCountRecord.setMemberLevel(level);
					memberShareCountRecord.setCountMonth(dateTime.toString("yyyy-MM"));
					memberShareCountRecord.setCrtTime(System.currentTimeMillis());
					memberShareCountRecord.setUpdTime(System.currentTimeMillis());
					memberShareCountRecordList.add(memberShareCountRecord);
				}

				if (memberShareCountRecordList.size() > 0) {
					memberShareCountRecordBiz.batchSave(memberShareCountRecordList);
				}

			}

		}
	}

	/**
	 * 接收会员订单支付成功后处理
	 * @param orderMemberDetail
	 */
	public void generateMemberShareQueue(OrderMemberDetail orderMemberDetail) {
		if (orderMemberDetail != null) {
			log.info("会员订单信息: {}", orderMemberDetail);
			Example example = new Example(BaseUserMemberLevel.class);
			example.createCriteria().andEqualTo("isdel", 0).andEqualTo("isShare", 1);
			example.orderBy("level");
			List<BaseUserMemberLevel> baseUserMemberLevelList = baseUserMemberLevelMapper.selectByExample(example);
			if (baseUserMemberLevelList != null && baseUserMemberLevelList.size() > 0) {
				//如果购买会员是分成会员低一级会员以及分成会员，才参与分成
				if (orderMemberDetail.getMemberLevel().compareTo(baseUserMemberLevelList.get(0).getLevel() - 1) >= 0) {
					//所有分成会员都需要新增一条记录
					for (BaseUserMemberLevel baseUserMemberLevel : baseUserMemberLevelList) {
						List<BaseUserMember> baseUserMemberList = baseUserMemberBiz.selectList(new BaseUserMember(){{setIsDel(0); setMemberLevel(orderMemberDetail.getMemberLevel());}});
						if (baseUserMemberList != null && baseUserMemberList.size() > 0) {
							List<Integer> userIds = baseUserMemberList.stream().map(BaseUserMember::getUserId).collect(Collectors.toList());
							if (userIds != null && userIds.size() > 0) {
								MemberShareRecord memberShareRecord = new MemberShareRecord();
								memberShareRecord.setOrderNo(orderMemberDetail.getBaseOrder().getNo());
								memberShareRecord.setPayTime(orderMemberDetail.getBaseOrder().getPayTime());
								memberShareRecord.setOrderAmount(orderMemberDetail.getBaseOrder().getOrderAmount());
								memberShareRecord.setMemberLevel(orderMemberDetail.getMemberLevel());
								memberShareRecord.setMemberLevelId(orderMemberDetail.getMemberLevelId());
								memberShareRecord.setUserId(orderMemberDetail.getBaseOrder().getUserId().longValue());
								memberShareRecord.setOrderTime(orderMemberDetail.getCrtTime());
								memberShareRecord.setTotalAmount(baseUserMemberLevel.getShareAmount());
								memberShareRecord.setMemberNum(userIds.size());
								memberShareRecord.setAmount(baseUserMemberLevel.getShareAmount().divide(new BigDecimal(userIds.size()).setScale(2, BigDecimal.ROUND_HALF_UP)));
								StringBuilder stringBuilder = new StringBuilder();
								userIds.parallelStream().forEach(id -> {
									stringBuilder.append(",");
									stringBuilder.append(id);
									stringBuilder.append(",");
								});
								memberShareRecord.setMemberIds(stringBuilder.toString());
								addUpdate(memberShareRecord);
							}
						}
					}
				}
				}
			}
	}

}