package com.xxfc.platform.activity.biz;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.constant.RestCode;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.activity.constant.IntegralRulePeriod;
import com.xxfc.platform.activity.entity.IntegralRule;
import com.xxfc.platform.activity.entity.IntegralUserRecord;
import com.xxfc.platform.activity.entity.IntegralUserStatus;
import com.xxfc.platform.activity.entity.IntegralUserTotal;
import com.xxfc.platform.activity.mapper.IntegralUserRecordMapper;
import com.xxfc.platform.activity.user.UserInfoBiz;
import com.xxfc.platform.activity.util.IntegralToolsUtils;
import com.xxfc.platform.activity.vo.IntegralRuleDto;
import com.xxfc.platform.activity.vo.IntegralUserRecordDto;
import com.xxfc.platform.activity.vo.IntegralUserTotalDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class IntegralUserRecordBiz extends BaseBiz<IntegralUserRecordMapper, IntegralUserRecord> {

    @Autowired
    UserInfoBiz userInfoBiz;

    @Autowired
    IntegralUserTotalBiz integralUserTotalBiz;

    @Autowired
    IntegralRuleBiz integralRuleBiz;

    @Autowired
    IntegralUserStatusBiz integralUserStatusBiz;

    /**
     * 添加用户积分记录
     *
     * @param integralUserRecord
     * @return
     */
    public ObjectRestResponse add(IntegralUserRecordDto integralUserRecord) {
        log.info("添加积分记录的参数：integralUserRecord = {}", integralUserRecord);
        if (integralUserRecord == null || StringUtils.isBlank(integralUserRecord.getIntegralRuleCode())) {
            return ObjectRestResponse.paramIsEmpty();
        }
        //如果参数没有积分，说明是消息队列过来的参数，需要查询规则表获取积分数
        IntegralRuleDto integralRule = new IntegralRuleDto();
        integralRule.setCode(integralUserRecord.getIntegralRuleCode());
        ObjectRestResponse<IntegralRule> ruleObjectRestResponse = integralRuleBiz.getOne(integralRule);
        if (ruleObjectRestResponse.getData() == null) {
            return ObjectRestResponse.createFailedResult(1202, "积分规则不存在");
        }
        IntegralRule oldValue = ruleObjectRestResponse.getData();
        if (integralUserRecord.getPoint() == null) {
            Integer point = 0;
            if (oldValue.getPoint() == 0) {//没有基础分需要计算分数
                //Integer amount = Integer.parseInt(new BigDecimal(integralUserRecord.getAmount()).divide(new BigDecimal("100"), 0, BigDecimal.ROUND_DOWN).toString());
                Integer amount = Integer.parseInt(integralUserRecord.getAmount());
                JSONObject jsonObject = JSONObject.parseObject(oldValue.getOtherRule());
                log.info("查询的其他规则json信息：jsonObject = {}", jsonObject);
                if (jsonObject == null) {
                    point = ruleObjectRestResponse.getData().getPoint();
                } else {
                    point = jsonObject.getInteger("rule") == null ? 0 * amount : jsonObject.getInteger("rule") * amount;
                }

            } else {
                point = ruleObjectRestResponse.getData().getPoint();
            }
            log.info("查询的其他规则积分数：point = {}", point);
            //把规则表中的积分数设置到参数对象中，然后进行后续操作
            integralUserRecord.setPoint(point);
        }

        if (integralUserRecord.getType() == 0) {//获取积分 增加总积分表
            IntegralUserTotalDto integralUserTotalDto = new IntegralUserTotalDto();
            integralUserTotalDto.setUserId(integralUserRecord.getUserId());
            integralUserTotalDto.setPoint(integralUserRecord.getPoint());
            integralUserTotalBiz.update(integralUserTotalDto);
        } else if (integralUserRecord.getType() == 1) {//扣减积分
            ObjectRestResponse<IntegralUserTotal> objectRestResponse = integralUserTotalBiz.getByUser();
            if (objectRestResponse.getStatus() == RestCode.SUCCESS.getStatus() && objectRestResponse.getData() != null) {
                IntegralUserTotal integralUserTotal = objectRestResponse.getData();
                IntegralUserTotalDto integralUserTotalDto = new IntegralUserTotalDto();
                integralUserTotalDto.setUserId(integralUserTotal.getUserId());
                integralUserTotalDto.setPoint(-integralUserRecord.getPoint());
                integralUserTotalBiz.update(integralUserTotalDto);
            } else {
                return ObjectRestResponse.createFailedResult(1008, "用户积分不足");
            }
        }
        insertSelective(integralUserRecord.getIntegralUserRecord());
        if (oldValue != null) {
            getUserRecordStatus(integralUserRecord, oldValue.getPeriod(), oldValue.getNumber());
        }
        return ObjectRestResponse.succ();
    }

    /**
     * 删除一个用户记录
     *
     * @param id
     * @return
     */
    public ObjectRestResponse deleteOne(Integer id) {
        log.info("删除用户积分记录的参数：id = {}", id);
        if (id == null || id <= 0) {
            return ObjectRestResponse.paramIsEmpty();
        }
        IntegralUserRecord integralUserRecord = mapper.selectByPrimaryKey(id);
        if (integralUserRecord == null) {
            log.info("删除的用户记录不存在，要删除的id ={}", id);
            return ObjectRestResponse.createDefaultFail();
        }
        integralUserRecord.setIsdel(true);
        updateByIdRe(integralUserRecord);
        return ObjectRestResponse.succ();
    }

    /**
     * 根据获取某个用户的列表
     *
     * @return
     */
    public ObjectRestResponse<PageDataVO> getUserList(IntegralUserRecordDto integralUserRecordDto) {
        log.info("获取用户积分记录的参数：integralUserRecordDto = {}", integralUserRecordDto.toString());
        AppUserDTO appUserDTO = userInfoBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        integralUserRecordDto.setUserId(appUserDTO.getUserid());
        Query query = new Query(integralUserRecordDto);
        PageDataVO pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByUserId(appUserDTO.getUserid()));
        return ObjectRestResponse.succ(pageDataVO);
    }

    public ObjectRestResponse<List<IntegralUserRecord>> getByUserAndTime(IntegralUserRecordDto integralUserRecordDto) {
        log.info("获取用户积分记录的参数：integralUserRecordDto = {}", integralUserRecordDto.toString());
        if (integralUserRecordDto == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        AppUserDTO appUserDTO = userInfoBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        integralUserRecordDto.setUserId(appUserDTO.getUserid());
        List<IntegralUserRecord> integralUserRecordList = mapper.selectByUserAndTime(integralUserRecordDto);
        return ObjectRestResponse.succ(integralUserRecordList);
    }


    /**
     * //判断用户获取积分是否达标
     *
     * @param integralUserRecordDto 积分记录实体
     * @param period                周期
     *                              number  周期内可获得积分的次数
     */
    public void getUserRecordStatus(IntegralUserRecordDto integralUserRecordDto, Integer period, Integer number) {

        IntegralUserStatus integralUserStatus = new IntegralUserStatus();
        integralUserStatus.setUserId(integralUserRecordDto.getUserId());
        integralUserStatus.setIntegralRuleCode(integralUserRecordDto.getIntegralRuleCode());
        if (period == IntegralRulePeriod.DAY.getCode()) {//按天
            integralUserRecordDto.setStartTime(IntegralToolsUtils.getDayStart());
            integralUserRecordDto.setEndTime(IntegralToolsUtils.getDayStart() + 24 * 60 * 60 * 1000);
            Integer count = mapper.countByUserAndCode(integralUserRecordDto);
            integralUserStatus.setIntegralStatus(count == number);
        } else {
            integralUserRecordDto.setStartTime(null);
            Integer count = mapper.countByUserAndCode(integralUserRecordDto);
            integralUserStatus.setIntegralStatus(count == number);
        }
        integralUserStatusBiz.save(integralUserStatus);
    }


}
