package com.izouma.nineth.web;

import com.izouma.nineth.domain.*;
import com.izouma.nineth.enums.AccountType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserBankCardRepo;
import com.izouma.nineth.repo.UserFundAccountRepo;
import com.izouma.nineth.service.UserFundAccountForSumpayService;
import com.izouma.nineth.service.UserFundAccountService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商盟钱包
 */
@RestController
@RequestMapping("/walletSumpay")
@AllArgsConstructor
@Slf4j
public class WalletSumpayController extends BaseController{

    private static Thread repairAccountThread;

    private UserFundAccountService userFundAccountService;

    private UserFundAccountForSumpayService userFundAccountForSumpayService;

    private UserFundAccountRepo userFundAccountRepo;

    private UserBankCardRepo userBankCardRepo;


    /**
     * 修复账户
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/repairAccount")
    public String repairAccount(){
        if(repairAccountThread != null && repairAccountThread.isAlive()){
            throw new BusinessException("任务正在进行，请稍后再试");
        }

        repairAccountThread = new Thread(() -> {
            List<UserFundAccount> dataList = userFundAccountRepo.findLockedAccount(AccountType.SUMPAY_USER);
            dataList.forEach(item -> {
                userFundAccountForSumpayService.repairAccount(item.getUserId());
            });
        });

        repairAccountThread.start();
        return "异步调用成功，请勿重复操作";

    }


    /**
     * 开通商盟钱包账户
     * @return
     */
    @PostMapping("register")
    public UserFundAccount register(){
        User user = currentUser();
        UserFundAccount account = userFundAccountForSumpayService.addAccount(user.getId());
        //自动绑卡
        UserBankCard userBankCard = userBankCardRepo.findByUserId(user.getId()).stream().findAny().orElse(null);
        if(userBankCard != null){
            userFundAccountForSumpayService.bindCard(userBankCard);
        }

        return account;
    }


}
