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.dto.ApLogDTO;
import com.xxfc.platform.activity.entity.*;
import com.xxfc.platform.activity.mapper.ActivityPopularizeMapper;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 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
public class ActivityPopularizeBiz extends BaseBiz<ActivityPopularizeMapper,ActivityPopularize> {

    @Autowired
    ActivityPopularizeRelationBiz relationBiz;

    @Autowired
    ActivityPopularizeBiz popularizeBiz;

    @Autowired
    ActivityPopularizeUserBiz popularizeUserBiz;

    @Autowired
    ActivityPopularizeLogBiz popularizeLogBiz;

    @Autowired
    ActivityPopularizeItemBiz activityPopularizeItemBiz;

    @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) {

        if (StringUtils.isNotBlank(registerQueueDTO.getInParamDTO().getActivityCode())) {
            String activityCode = registerQueueDTO.getInParamDTO().getActivityCode().replace(PREFIX, "");
            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);
                }});
                if (activityPopularize != null) {
                    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));
                        return;
                    }

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

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

                    BigDecimal amount = new BigDecimal(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) {
                                String amountString = jsonObject1.getString("amount");
                                amount.add(new BigDecimal(amountString));
                            }
                        }
                    }
                    //添加活动关系
                    relationBiz.insertSelective(new ActivityPopularizeRelation(){{
                        setPopularizeId(activityPopularize.getId());
                        setMajorUserId(majorUserId);
                        setMinorUserId(appUserDTO.getUserid());
                        setNum(num);
                        setAmount(amount);
                    }});

                    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());
                    }});
                    //修改当前进度
                    activityPopularizeUser.setCurrentProgress(activityPopularizeUser.getCurrentProgress().add(amount));
                    //任务没有完成
                    if(!SYS_TRUE.equals(activityPopularizeUser.getStatus())) {
//                AwardDTO awardDTO = JSONUtil.toBean(activityPopularize.getValue(), AwardDTO.class);
                        //检查是否满足奖励
                        if(relationBiz.selectList(new ActivityPopularizeRelation(){{
                            setMajorUserId(majorUserId);
                            setPopularizeId(activityPopularize.getId());
                        }}).size() >= 2) {
                            apLogDTO.setStatus(SYS_TRUE);
                            popularizeLogBiz.updateSelectiveById(BeanUtil.toBean(apLogDTO, ActivityPopularizeLog.class));
                            activityPopularizeUser.setStatus(SYS_TRUE);
                            activityPopularizeUser.setCurrentProgress(new BigDecimal(apLogDTO.getItem().getProgress()));
                            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);
                            }}));
                        }
                    }
                }
            }
        }
    }
}