package com.izouma.nineth.service.pay;

import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.BankValidate;
import com.izouma.nineth.domain.UserBankCard;
import com.izouma.nineth.dto.pay.*;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.*;
import com.izouma.nineth.service.SiweipayService;
import com.izouma.nineth.service.sms.SmsService;
import com.izouma.nineth.utils.BankUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service(UniformPayConstants.SIWEIPAY_PLATFORM)
@AllArgsConstructor
@Slf4j
public class SiweipayPlatformImpl implements UniformPayService{

    private UserRepo userRepo;

    private IdentityAuthRepo identityAuthRepo;

    private UserBankCardRepo userBankCardRepo;

    private SmsService smsService;

    private SiweipayService siweipayService;

    /**
     *
     * 微信扫码：W01，用于微信PC扫码
     * 微信个码：W02 微信个码
     * 微信相册截图：W04，用于微信手机截图
     * 支付宝转卡：A01，用于支付宝PC扫码
     * 支付宝个码：A02 企业个人支付宝
     * 支付宝网关：A03 支付宝网关快捷
     * 支付宝H5：A05，支付宝手机H5
     * 云闪付： U01 银联截图扫码支付
     * P01：拼多多微信
     * P02：拼多多支付宝
     *
     *
     */
    @Cacheable(value = UniformPayConstants.SIWEIPAY_PLATFORM, key = "#request.uniqueId")
    @Override
    public UniformPayResult pay(UniformPayRequest request) throws Exception {
        throw new BusinessException("暂不支持此支付平台");
    }

    @Override
    public UniformNotifyResult notify(UniformNotifyRequest request) throws Exception {
        throw new BusinessException("暂不支持此支付平台");
    }

    @Override
    public Map<String, Object> refund(String orderNo, String refundReason) throws Exception {
        throw new BusinessException("暂不支持此支付平台");
    }

    @Override
    public UniformNotifyResult refundNotify(UniformNotifyRequest request) throws Exception {
        throw new BusinessException("暂不支持此支付平台");
    }

    @Override
    public UniformNotifyResult transferNotify(UniformNotifyRequest request) throws Exception {
        throw new BusinessException("暂不支持");
    }

    @Override
    public UserBankCard addBankCard(UniformBindBank bindBank) throws Exception {
        Long userId = bindBank.getUserId();
        String bankNo = bindBank.getBankNo();
        String phone = bindBank.getPhone();
        String smsCode = bindBank.getSmsCode();
        //短信验证
        smsService.verify(phone, smsCode);
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
                .orElseThrow(new BusinessException("用户未通过实名认证"));
        if (identityAuth.isOrg()) {
            //throw new BusinessException("企业认证用户请绑定对公账户");
        }

        if(isBindBankCard(userId)){
            throw new BusinessException("此账号已绑定过，请先解绑");
        }

        BankValidate bankValidate = BankUtils.validate(bankNo);
        if (!bankValidate.isValidated()) {
            throw new BusinessException("暂不支持此卡");
        }

//        user.setBankCard(true);
        userRepo.save(user);

        UserBankCard userBankCard = userBankCardRepo.save(UserBankCard.builder()
                .payPlatform(UniformPayConstants.SIWEIPAY_PLATFORM)
                .bank(bankValidate.getBank())
                .bankName(bankValidate.getBankName())
                .bankNo(bankNo)
                .cardType(bankValidate.getCardType())
                .cardTypeDesc(bankValidate.getCardTypeDesc())
                .userId(userId)
                .phone(phone)
                .realName(identityAuth.getRealName())
                .idNo(identityAuth.getIdNo())
                .build());
        return userBankCard;
    }

    @Override
    public void removeBankCard(Long userId) throws Exception {
        //直接解绑
        userBankCardRepo.deleteByUserId(userId);
    }

    @Override
    public boolean isBindBankCard(Long userId) {
        User owner = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        UserBankCard userBankCard = userBankCardRepo.findByUserId(owner.getId()).stream().findAny()
                .orElse(null);
        if(userBankCard != null){
            return true;
        }
        return false;
    }

}
