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.constant.MALLGlobalConfig;
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.enums.type.TranObjectEnum;
import com.fzm.mall.server.admin.finance_center.enums.type.UserAssetsTypeEnum;
import com.fzm.mall.server.admin.finance_center.model.*;
import com.fzm.mall.server.admin.finance_center.service.*;
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/29 10:42
 * @description 积分转账
 * @since JDK 1.8
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IntegralTranConsumer {
    private final FzmChain fzmChain;
    private final IMerchantAssetsFlowService merchantAssetsFlowService;
    private final IMerchantAssetsService merchantAssetsService;
    private final IUserAssetService userAssetService;
    private final IUserAssetRecordService userAssetRecordService;
    private final IMerchantIntegralService merchantIntegralService;
    private final IPlatformAssetsFlowService platformAssetsFlowService;
    private final IPlatformIntegralService platformIntegralService;

    //商户积分转账
    @RabbitListener(queues = "ly.merchant.integral.tran.queue")
    public void issueIntegral(Map<String, Object> obj) {
        try {
            String hash = (String) obj.get("hash");
            String tokenIssueAddr = (String) obj.get("tokenIssueAddr");
            String userAddr = (String) obj.get("userAddr");
            BigDecimal amount = (BigDecimal) obj.get("amount");
            String label = (String) obj.get("label");
            String merchantId = (String) obj.get("merchantId");
            String uid = (String) obj.get("uid");
            Integer success = AssetsFlowStatusEnum.SUCCESS.getStatus();
            Integer fail = AssetsFlowStatusEnum.FAIL.getStatus();
            Integer tranIn = AssetsFlowTypeEnum.DIGITAL_TRAN_IN.getType();
            Integer tranOut = AssetsFlowTypeEnum.DIGITAL_TRAN_OUT.getType();
            String flowId = UUIDUtil.getUUID();

            //商户流水
            MerchantAssetsFlow merchantAssetsFlow = new MerchantAssetsFlow(
                    flowId,
                    merchantId,
                    label,
                    amount,
                    tranOut,
                    success,
                    userAddr
            );

            //商户资产
            MerchantAssets merchantAssets = merchantAssetsService.queryByMerchantIdAndCoin(merchantId, label);
            merchantAssets.setAmount(merchantAssets.getAmount().subtract(amount));

            //用户流水
            UserAssetRecord userAssetRecord = new UserAssetRecord(
                    flowId,
                    uid,
                    label,
                    tranIn,
                    amount,
                    success,
                    tokenIssueAddr
            );

            //用户资产
            UserAsset userAsset = userAssetService.queryByUidAndCoin(uid, label);
            if (userAsset == null) {
                userAsset = new UserAsset(
                        uid,
                        label,
                        amount,
                        UserAssetsTypeEnum.PAY_COIN.getType()

                );
            } else {
                userAsset.setAmount(userAsset.getAmount().add(amount));
            }

            //上链结果轮询确认
            JSONObject json = fzmChain.cycleConfirmTxWithHash(hash);
            if (json.getString("status").equals("SUCCESS")) {
                //更新商户资产
                merchantAssetsService.updateById(merchantAssets);
                //更新用户资产
                userAssetService.saveOrUpdate(userAsset);

                if (!label.equals(MALLGlobalConfig.PLATFORM_BASE_INTEGRAL)) {
                    //更新商户积分
                    MerchantIntegral merchantIntegral = merchantIntegralService.queryByMerchantIdAndLabel(label, merchantId);
                    merchantIntegral.setBalanceNum(merchantIntegral.getBalanceNum().subtract(amount));
                    merchantIntegralService.updateById(merchantIntegral);
                }
            } else {
                merchantAssetsFlow.setStatus(fail);
                userAssetRecord.setStatus(fail);
            }

            //保存流水
            merchantAssetsFlowService.save(merchantAssetsFlow);
            userAssetRecordService.save(userAssetRecord);

        } catch (Exception e) {
            return;
        }
    }

    //平台积分转账
    @RabbitListener(queues = "ly.platform.integral.tran.queue")
    public void platformIntegralTran(Map<String, Object> obj) {
        try {
            String hash = (String) obj.get("hash");
            String coin = (String) obj.get("coin");
            BigDecimal amount = (BigDecimal) obj.get("amount");
            String oppositeAddr = (String) obj.get("oppositeAddr");
            String oppositeId = (String) obj.get("oppositeId");
            Integer type = (Integer) obj.get("type");

            Integer tranOut = AssetsFlowTypeEnum.DIGITAL_TRAN_OUT.getType();
            Integer tranIn = AssetsFlowTypeEnum.DIGITAL_TRAN_IN.getType();
            Integer success = AssetsFlowStatusEnum.SUCCESS.getStatus();
            Integer fail = AssetsFlowStatusEnum.FAIL.getStatus();
            String flowId = UUIDUtil.getUUID();


            //平台流水
            PlatformAssetsFlow platformAssetsFlow = new PlatformAssetsFlow(
                    flowId,
                    coin,
                    amount,
                    tranOut,
                    success,
                    oppositeAddr
            );

            MerchantAssetsFlow merchantAssetsFlow = null;
            UserAssetRecord userAssetRecord = null;
            MerchantAssets merchantAssets = null;
            UserAsset userAsset = null;

            if (type.equals(TranObjectEnum.MERCHANT.getType())) {
                //商户流水
                merchantAssetsFlow = new MerchantAssetsFlow(
                        flowId,
                        oppositeId,
                        coin,
                        amount,
                        tranIn,
                        success,
                        "平台"
                );

                //商户资产
                merchantAssets = merchantAssetsService.queryByMerchantIdAndCoin(oppositeId, coin);
                if (merchantAssets == null) {
                    merchantAssets = new MerchantAssets(
                            oppositeId,
                            oppositeAddr,
                            coin,
                            amount
                    );
                } else {
                    merchantAssets.setAmount(merchantAssets.getAmount().add(amount));
                }
            } else {
                //用户流水
                userAssetRecord = new UserAssetRecord(
                        flowId,
                        oppositeId,
                        coin,
                        tranIn,
                        amount,
                        success,
                        "平台"
                );

                //用户资产
                userAsset = userAssetService.queryByUidAndCoin(oppositeId, coin);
                if (userAsset == null) {
                    userAsset = new UserAsset(
                            oppositeId,
                            coin,
                            amount,
                            UserAssetsTypeEnum.PAY_COIN.getType()

                    );
                } else {
                    userAsset.setAmount(userAsset.getAmount().add(amount));
                }
            }

            //上链结果轮询确认
            JSONObject json = fzmChain.cycleConfirmTxWithHash(hash);
            if (json.getString("status").equals("SUCCESS")) {
                if (type.equals(TranObjectEnum.MERCHANT.getType())) {
                    //更新商户资产
                    merchantAssetsService.saveOrUpdate(merchantAssets);
                } else {
                    //更新用户资产
                    userAssetService.saveOrUpdate(userAsset);
                }

                //更新平台基础积分
                PlatformIntegral platformIntegral = platformIntegralService.queryByLabel(coin);
                platformIntegral.setBalanceNum(platformIntegral.getBalanceNum().subtract(amount));
                platformIntegralService.updateById(platformIntegral);
            } else {
                platformAssetsFlow.setStatus(fail);
                merchantAssetsFlow.setStatus(fail);
            }

            //保存流水
            platformAssetsFlowService.save(platformAssetsFlow);
            if (type.equals(TranObjectEnum.MERCHANT.getType())) {
                merchantAssetsFlowService.save(merchantAssetsFlow);
            } else {
                userAssetRecordService.save(userAssetRecord);
            }

        } catch (Exception e) {
            return;
        }
    }

    //平台积分回收
    @RabbitListener(queues = "ly.platform.integral.recover.queue")
    public void platformIntegralRecover(Map<String, Object> obj) {
        try {
            String hash = (String) obj.get("hash");
            String coin = (String) obj.get("coin");
            BigDecimal amount = (BigDecimal) obj.get("amount");

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

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

            //保存流水
            platformAssetsFlowService.save(flow);

        } catch (Exception e) {
            return;
        }
    }

    //用户资产充值或扣除
    @RabbitListener(queues = "ly.user.assets.recharge.or.deduction.queue")
    public void userAssetsRechargeOrDeduction(Map<String, Object> obj) {
        try {
            String hash = (String) obj.get("hash");
            String coin = (String) obj.get("coin");
            BigDecimal amount = (BigDecimal) obj.get("amount");
            Integer type = (Integer) obj.get("type");
            String otherSide = (String) obj.get("otherSide");
            String uid = (String) obj.get("uid");

            Integer success = AssetsFlowStatusEnum.SUCCESS.getStatus();
            Integer fail = AssetsFlowStatusEnum.FAIL.getStatus();
            String flowId = UUIDUtil.getUUID();

            Integer platformRecordType = type.equals(AssetsFlowTypeEnum.RECHARGE.getType()) ? AssetsFlowTypeEnum.DIGITAL_TRAN_OUT.getType() : AssetsFlowTypeEnum.DIGITAL_TRAN_IN.getType();

            //平台流水
            PlatformAssetsFlow platformAssetsFlow = new PlatformAssetsFlow(
                    flowId,
                    coin,
                    amount,
                    platformRecordType,
                    success,
                    otherSide
            );

            //用户流水
            UserAssetRecord userAssetRecord = new UserAssetRecord(
                    flowId,
                    uid,
                    coin,
                    type,
                    amount,
                    success,
                    "平台"
            );

            //用户资产
            UserAsset userAsset = userAssetService.queryByUidAndCoin(uid, coin);
            if (type.equals(AssetsFlowTypeEnum.RECHARGE.getType())) {
                userAsset.setAmount(userAsset.getAmount().add(amount));
            } else {
                userAsset.setAmount(userAsset.getAmount().subtract(amount));
            }

            //上链结果轮询确认
            JSONObject json = fzmChain.cycleConfirmTxWithHash(hash);
            if (json.getString("status").equals("SUCCESS")) {
                //更新平台积分
                PlatformIntegral integral = platformIntegralService.queryByLabel(coin);
                if (type.equals(AssetsFlowTypeEnum.RECHARGE.getType())) {
                    integral.setBalanceNum(integral.getBalanceNum().subtract(amount));
                } else {
                    integral.setBalanceNum(integral.getBalanceNum().add(amount));
                }
                platformIntegralService.updateById(integral);

                //更新用户资产
                userAssetService.updateById(userAsset);
            } else {
                platformAssetsFlow.setStatus(fail);
                userAssetRecord.setStatus(fail);
            }

            //保存流水
            platformAssetsFlowService.save(platformAssetsFlow);
            userAssetRecordService.save(userAssetRecord);

        } catch (Exception e) {
            return;
        }
    }


}


