package com.xxfc.platform.activity.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.dto.RegisterQueueDTO;
import com.github.wxiaoqi.security.admin.entity.MyWalletDetail;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant;
import com.xxfc.platform.activity.config.RedissonLock;
import com.xxfc.platform.activity.dto.ApLogDTO;
import com.xxfc.platform.activity.entity.*;
import com.xxfc.platform.activity.mapper.ActivityPopularizeMapper;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

/**
 * 推广活动（邀请有礼）
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-05 15:23:04
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ActivityPopularizeBiz extends BaseBiz<ActivityPopularizeMapper, ActivityPopularize> {

	@Autowired
	ActivityPopularizeRelationBiz relationBiz;

	@Autowired
	ActivityPopularizeBiz popularizeBiz;

	@Autowired
	ActivityPopularizeUserBiz popularizeUserBiz;

	@Autowired
	ActivityPopularizeLogBiz popularizeLogBiz;

	@Autowired
	ActivityPopularizeItemBiz activityPopularizeItemBiz;

	private final RedissonLock redissonLock;


	@Autowired
	UserFeign userFeign;

	@Autowired
	MQSenderFeign mqSenderFeign;

	public static final String POPULARIZE_0101 = "0101";

	public static final String PREFIX = "P";

	public static final Integer INVITE_ITEMID = 3;

	public void handleRegister(RegisterQueueDTO registerQueueDTO) {
		log.info("活动码注册成功：registerQueueDTO = {}", registerQueueDTO.toString());
		if (StringUtils.isNotBlank(registerQueueDTO.getInParamDTO().getActivityCode())) {
			String activityCode = registerQueueDTO.getInParamDTO().getActivityCode().replace(PREFIX, "").replace("p", "");
			AppUserDTO appUserDTO = userFeign.userDetailById(registerQueueDTO.getAppUserId()).getData();
			//获取活动code,并且注册来源是app 并且 非普通登录
			if (!RegisterQueueDTO.SIGN_LOGIN.equals(registerQueueDTO.getSign()) && StringUtils.isNotBlank(activityCode)) {
				//查询出活动
				ActivityPopularize activityPopularize = popularizeBiz.selectOne(new ActivityPopularize() {{
					setCode(activityCode);
				}});
				log.info("活动邀请注册：activityPopularize = {}", activityPopularize.toString());
				if (activityPopularize != null) {
					String lockKey = String.format("%s%d%d", registerQueueDTO.getInParamDTO().getActivityCode(), appUserDTO.getInviterAccount(), activityPopularize.getId());
					RLock rLock = redissonLock.getRLock(lockKey);
					try {
						boolean isSuccess = rLock.tryLock(5, 5, TimeUnit.SECONDS);
						if (isSuccess) {
							log.info("1, {}", System.currentTimeMillis());
							Thread.sleep(1000);
							log.info("2, {}", System.currentTimeMillis());
							List<ActivityPopularizeItem> activityPopularizeItems = activityPopularizeItemBiz.selectByPopularizeId(activityPopularize.getId());
							ActivityPopularizeItem activityPopularizeItem = activityPopularizeItems.get(activityPopularizeItems.size() - 1);
							Date now = DateUtil.date();
							Date start = DateUtil.date(activityPopularize.getStartTime());
							Date end = DateUtil.date(activityPopularize.getEndTime());

							//判断是否活动超时
							if (now.before(start) || now.after(end)) {
								log.error("不在活动范围内 入参Json：" + JSONUtil.toJsonStr(registerQueueDTO));
								//已完成，设置为活动结束
								activityPopularize.setStatus(1);
								popularizeBiz.updateSelectiveByIdRe(activityPopularize);
								return;
							}

							Integer majorUserId = Integer.valueOf(appUserDTO.getInviterAccount());
							ActivityPopularizeRelation activityPopularizeRelation = new ActivityPopularizeRelation() {{
								setMajorUserId(majorUserId);
								setPopularizeId(activityPopularize.getId());
							}};

							//新增第几个邀请人和邀请金额字段
							Integer num = relationBiz.getByUserIdAndPopularizeId(activityPopularizeRelation);

							double amount = 0;
							JSONObject jsonObject = JSONObject.parseObject(activityPopularizeItem.getDetail());
							if (jsonObject != null && StringUtils.isNotBlank(jsonObject.getString("detail"))) {
								JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("detail"));
								if (jsonArray != null) {
									JSONObject jsonObject1 = jsonArray.getJSONObject(num - 1);
									if (jsonObject1 != null) {
										double amountString = jsonObject1.getDouble("amount");
										amount = amount + amountString;
									}
								}
							}
							double a = amount;
							//添加活动关系
							relationBiz.insertSelective(new ActivityPopularizeRelation() {{
								setPopularizeId(activityPopularize.getId());
								setMajorUserId(majorUserId);
								setMinorUserId(appUserDTO.getUserid());
								setNum(num);
								setAmount(new BigDecimal(a));
							}});

							ApLogDTO apLogDTO = popularizeLogBiz.selectOneApLogDTO(new ActivityPopularizeLog() {{
								setUserId(majorUserId);
								setItemId(activityPopularizeItem.getId());
							}});

							//生成任务项
							if (null == apLogDTO) {
								popularizeLogBiz.insertSelectiveRe(new ActivityPopularizeLog() {{
									setItemId(activityPopularizeItem.getId());
									setUserId(majorUserId);
									setStatus(SYS_FALSE);
									setPopularizeId(activityPopularize.getId());
								}});
							}

							//查出majorUser参与活动信息
							ActivityPopularizeUser activityPopularizeUser = popularizeUserBiz.selectOne(new ActivityPopularizeUser() {{
								setUserId(majorUserId);
								setPopularizeId(activityPopularize.getId());
							}});
							double currentProgress = activityPopularizeUser.getCurrentProgress().doubleValue();
							log.info("用户原活动进度：currentProgress = {}", currentProgress);
							currentProgress += Double.parseDouble(a + "");
							BigDecimal bigDecimal = new BigDecimal(currentProgress);
							log.info("用户现活动进度：newCurrentProgress = {}", currentProgress);
							//修改当前进度
							activityPopularizeUser.setCurrentProgress(bigDecimal);
							popularizeUserBiz.updateSelectiveById(activityPopularizeUser);
							//任务没有完成 加锁

							if (!SYS_TRUE.equals(activityPopularizeUser.getStatus())) {
//                AwardDTO awardDTO = JSONUtil.toBean(activityPopularize.getValue(), AwardDTO.class);
								//检查是否满足奖励
								Long limitNumber = popularizeUserBiz.selectCount(new ActivityPopularizeUser() {{
									setPopularizeId(activityPopularize.getId());
									setCurrentProgress(new BigDecimal("50"));
								}});
								Long userNumber = relationBiz.selectCount(new ActivityPopularizeRelation() {{
									setMajorUserId(majorUserId);
									setPopularizeId(activityPopularize.getId());
								}});
								if (limitNumber >= activityPopularize.getNumLimit()) {
									//已完成，设置为活动结束
									activityPopularize.setStatus(1);
									popularizeBiz.updateSelectiveByIdRe(activityPopularize);
									return ;
								}
								if ( userNumber >= 10 &&  limitNumber < activityPopularize.getNumLimit()) {
									apLogDTO.setStatus(SYS_TRUE);
									popularizeLogBiz.updateSelectiveById(BeanUtil.toBean(apLogDTO, ActivityPopularizeLog.class));
									activityPopularizeUser.setStatus(SYS_TRUE);
									popularizeUserBiz.updateSelectiveById(activityPopularizeUser);

									mqSenderFeign.sendMessage(RabbitConstant.ADMIN_TOPIC, RabbitConstant.KEY_WALLET_ADD, JSONUtil.toJsonStr(new MyWalletDetail() {{
										setAmount(new BigDecimal("50"));
										setSource(SOURCE_ACTIVITY);
										setUserId(majorUserId);
										setActivityId(activityPopularize.getId());
										setActivityName(activityPopularize.getName());
										setType(TYPE_POPULARIZE);
										setItype(ITYPE_IN);
									}}));
								}
							}
						} else {

							// 获取锁失败
							log.info("tryLock fail, key = [{}]", lockKey);
						}
					} catch (InterruptedException e) {
						log.error("tryLock fail, key = [{}]", lockKey);
					} finally {
						log.info("执行结束， {}", System.currentTimeMillis());
					}
				}
			}
		}
	}
}