package com.fzm.mall.server.admin.mq.consumer.finance_center;

import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.admin.chain.FzmChain;
import com.fzm.mall.server.admin.finance_center.enums.status.AssetsFlowStatusEnum;
import com.fzm.mall.server.admin.finance_center.enums.type.AssetsFlowTypeEnum;
import com.fzm.mall.server.admin.finance_center.model.PlatformAssetsFlow;
import com.fzm.mall.server.admin.finance_center.model.PlatformIntegral;
import com.fzm.mall.server.admin.finance_center.service.IPlatformAssetsFlowService;
import com.fzm.mall.server.admin.finance_center.service.IPlatformIntegralService;
import com.fzm.mall.server.admin.util.UUIDUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author wangp
 * @date 2021/4/28 13:57
 * @description 增减发积分
 * @since JDK 1.8
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ChangeIntegralConsumer {
    private final IPlatformIntegralService platformIntegralService;
    private final IPlatformAssetsFlowService platformAssetsFlowService;
    private final FzmChain fzmChain;

    //增发发行积分
    @RabbitListener(queues = "ly.platform.integral.add.queue")
    public void platformIntegralAdd(Map<String, Object> obj) {
        try {
            String hash = (String) obj.get("hash");
            BigDecimal amount = (BigDecimal) obj.get("amount");
            String label = (String) obj.get("label");

            //平台流水
            PlatformAssetsFlow flow = new PlatformAssetsFlow(
                    UUIDUtil.getUUID(),
                    label,
                    amount,
                    AssetsFlowTypeEnum.ADD_ISSUE.getType(),
                    AssetsFlowStatusEnum.SUCCESS.getStatus(),
                    "平台"
            );

            //上链结果轮询确认
            JSONObject json = fzmChain.cycleConfirmTxWithHash(hash);
            if (json.getString("status").equals("SUCCESS")) {
                //更新平台积分
                PlatformIntegral integral = platformIntegralService.queryByLabel(label);
                integral.setIssueNum(integral.getIssueNum().add(amount));
                integral.setBalanceNum(integral.getBalanceNum().add(amount));
                platformIntegralService.updateById(integral);
            } else {
                flow.setStatus(AssetsFlowStatusEnum.FAIL.getStatus());
            }

            //保存流水
            platformAssetsFlowService.save(flow);
        } catch (Exception e) {
            return;
        }
    }
}
