
package com.tmerclub.cloud.user.controller.app;

import com.tmerclub.cloud.api.payment.vo.PaySettlementConfigVO;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.common.util.PriceUtil;
import com.tmerclub.cloud.user.bo.mongo.MongoUserBalanceLogBO;
import com.tmerclub.cloud.user.constant.DistributedIdKey;
import com.tmerclub.cloud.user.constant.RechargeIoTypeEnum;
import com.tmerclub.cloud.user.constant.RechargeTypeEnum;
import com.tmerclub.cloud.user.dto.UserBalanceRechargeOrderDTO;
import com.tmerclub.cloud.user.model.UserExtension;
import com.tmerclub.cloud.user.service.UserBalanceLogService;
import com.tmerclub.cloud.user.service.UserExtensionService;
import com.tmerclub.cloud.user.service.UserRechargeService;
import com.tmerclub.cloud.user.vo.UserRechargeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 余额充值级别表
 *
 * @author tmerclub
 * @date 2021-04-27 15:51:36
 */
@RestController("appUserRechargeController")
@RequestMapping("/userRecharge")
@Tag(name = "app-余额充值")
public class UserRechargeController {

    @Autowired
    private UserRechargeService userRechargeService;

    @Autowired
    private UserExtensionService userExtensionService;
    @Autowired
    private UserBalanceLogService userBalanceLogService;
    @Autowired
    private SegmentManager segmentManager;
    @DubboReference
    private ConfigFeignClient configFeignClient;

    @GetMapping("/list")
    @Operation(summary = "获取余额充值级别表列表", description = "分页获取余额充值级别表列表")
    public ServerResponseEntity<List<UserRechargeVO>> list() {
        return ServerResponseEntity.success(userRechargeService.list());
    }

    @PostMapping("/recharge")
    @Operation(summary = "充值订单", description = "生成余额充值订单，保存充值记录")
    public ServerResponseEntity<Long> save(@Valid @RequestBody UserBalanceRechargeOrderDTO userBalanceRechargeOrderDTO) {
        Long amount = PriceUtil.toLongCent(userBalanceRechargeOrderDTO.getAmount());
        Long rechargeId = userBalanceRechargeOrderDTO.getRechargeId();
        if (rechargeId != null) {
            UserRechargeVO userRecharge = userRechargeService.getRechargeInfo(rechargeId);
            amount = userRecharge.getRechargeAmount();
        }
        if (amount == null || amount < 1) {
            throw new LuckException("充值金额有误");
        }
        UserExtension userExtension = userExtensionService.getByUserId(AuthUserContext.get().getUserId());
        long userBalance = userExtension.getActualBalance() + amount;
        if (userBalance > Constant.MAX_USER_BALANCE) {
            throw new LuckException("此次充值会导致余额超出最大限制，故无法进行此操作,请减少充值金额后重试");
        }
        MongoUserBalanceLogBO userBalanceLog = new MongoUserBalanceLogBO();
        userBalanceLog.setBalanceLogId(segmentManager.getSegmentId(DistributedIdKey.tmerclub_USER_BALANCE_LOG));
        userBalanceLog.setUserId(AuthUserContext.get().getUserId());
        userBalanceLog.setChangeBalance(amount);
        userBalanceLog.setIoType(RechargeIoTypeEnum.INCOME.value());
        userBalanceLog.setIsPayed(0);
        userBalanceLog.setRechargeId(userBalanceRechargeOrderDTO.getRechargeId());
        userBalanceLog.setType(RechargeTypeEnum.RECHARGE.value());
        // 补充支付类型（默认支付/通联支付）
        ServerResponseEntity<String> configResponse = configFeignClient.getConfig(Constant.PAY_SETTLEMENT_CONFIG);
        if (!configResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        PaySettlementConfigVO paySettlementConfigVO = Json.parseObject(configResponse.getData(), PaySettlementConfigVO.class);
        Integer paySysType = paySettlementConfigVO.getPaySettlementType();
        userBalanceLog.setPaySysType(paySysType);
        userBalanceLogService.saveToMongdb(userBalanceLog);
        return ServerResponseEntity.success(userBalanceLog.getBalanceLogId());
    }
}
