package com.izouma.nineth.service;

import com.alipay.api.domain.UserIdentity;
import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.BankValidate;
import com.izouma.nineth.dto.BindCardRequest;
import com.izouma.nineth.dto.UserBankCard;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.IdentityAuthRepo;
import com.izouma.nineth.repo.UserBalanceRepo;
import com.izouma.nineth.repo.UserBankCardRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.utils.BankUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
@Slf4j
@AllArgsConstructor
public class UserBankCardService {
    private final UserRepo         userRepo;
    private final UserService      userService;
    private final UserBankCardRepo userBankCardRepo;
    private final IdentityAuthRepo identityAuthRepo;
    private final PayEaseService   payEaseService;
    private final UserBalanceRepo  userBalanceRepo;

    public Map<String, String> bindCard(Long userId, String phone, String bankNo) {
        IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
                .orElseThrow(new BusinessException("请先完成实名认证"));
        BindCardRequest request = new BindCardRequest(userId.toString(), bankNo, phone, identityAuth.getRealName(),
                identityAuth.getIdNo(), null);
        String bindCardId = payEaseService.bindCard(request);
        Map<String, String> map = new HashMap<>();
        map.put("bindCardId", bindCardId);
        return map;
    }

    public void bindCardConfirm(String bindCardId, String code) {
        BindCardRequest request = payEaseService.bindCardConfirm(bindCardId, code);
        BankValidate validate = new BankValidate();
        try {
            validate = BankUtils.validate(request.getBankNo());
        } catch (Exception ignored) {
        }
        userBankCardRepo.deleteByUserId(Long.parseLong(request.getUserId()));
        userBankCardRepo.save(UserBankCard.builder()
                .bank(validate.getBank())
                .bankName(Optional.ofNullable(validate.getBankName()).orElse(validate.getBankName()))
                .cardType(validate.getCardType())
                .cardTypeDesc(validate.getCardTypeDesc())
                .bankNo(request.getBankNo())
                .idNo(request.getIdNo())
                .bindCardId(request.getBindCardId())
                .realName(request.getName())
                .userId(Long.parseLong(request.getUserId()))
                .phone(request.getPhone())
                .bindCardId(request.getBindCardId())
                .build());
        userBalanceRepo.unlock(Long.parseLong(request.getUserId()));
        User user = userRepo.findById(Long.parseLong(request.getUserId())).orElse(null);
        if (user != null) {
            user.setSettleAccountId(request.getBindCardId());
            userService.save(user);
            userRepo.flush();
            log.info("绑卡成功，加积分{}", user.getId());
            //加积分加限购
            userService.savePoint(user);
        }
        userBalanceRepo.unlock(Long.parseLong(request.getUserId()));
    }

    public void bindCardCaptcha(String bindCardId) {
        payEaseService.bindCardCaptcha(bindCardId);
    }

    public void unbind(Long userId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        userBankCardRepo.findByUserId(userId).forEach(userBankCard -> {
            if (StringUtils.isNotEmpty(userBankCard.getBindCardId())) {
                payEaseService.unbind(userId.toString(), userBankCard.getBindCardId());
            }
            userBankCardRepo.delete(userBankCard);
        });
        user.setSettleAccountId(null);
        userService.save(user);
    }
}
