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.entity.IntegralRule;
import com.xxfc.platform.activity.entity.IntegralUserRecord;
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.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.math.BigDecimal;
import java.util.List;

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

    @Autowired
    UserInfoBiz userInfoBiz;

    @Autowired
    IntegralUserTotalBiz integralUserTotalBiz;

    @Autowired
    IntegralRuleBiz integralRuleBiz;

    /**
     * 添加用户积分记录
     *
     * @param integralUserRecord
     * @return
     */
    public ObjectRestResponse add(IntegralUserRecordDto integralUserRecord) {
        log.info("添加积分记录的参数：integralUserRecord = {}", integralUserRecord);
        if (integralUserRecord == null || StringUtils.isBlank(integralUserRecord.getIntegralRuleCode())) {
            return ObjectRestResponse.paramIsEmpty();
        }
        //如果参数没有积分，说明是消息队列过来的参数，需要查询规则表获取积分数
        if (integralUserRecord.getPoint() == null) {
            IntegralRuleDto integralRule = new IntegralRuleDto();
            integralRule.setCode(integralUserRecord.getIntegralRuleCode());
            ObjectRestResponse<IntegralRule> ruleObjectRestResponse = integralRuleBiz.getOne(integralRule);
            if (ruleObjectRestResponse.getData() == null) {
                return ObjectRestResponse.createFailedResult(1202, "积分规则不存在");
            }
            Integer point = 0;

            if(ruleObjectRestResponse.getData().getPoint() == 0) {//没有基础分需要计算分数
                Integer amount = Integer.parseInt(new BigDecimal(integralUserRecord.getAmount()).divide(new BigDecimal("100"), 0, BigDecimal.ROUND_DOWN).toString());
                JSONObject jsonObject = JSONObject.parseObject(ruleObjectRestResponse.getData().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());
        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);
    }
}
