package com.izouma.dingdong.service;


import com.izouma.dingdong.domain.BankCard;
import com.izouma.dingdong.domain.MoneyRecord;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.domain.WithdrawApply;
import com.izouma.dingdong.domain.backstage.Email;
import com.izouma.dingdong.enums.FinancialType;
import com.izouma.dingdong.enums.WithdrawStatus;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.BankCardRepo;
import com.izouma.dingdong.repo.MoneyRecordRepo;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.repo.WithdrawApplyRepo;
import com.izouma.dingdong.repo.backstage.EmailRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;


@AllArgsConstructor
@Service
public class WithdrawApplyService {

    private WithdrawApplyRepo withdrawalsApplyRepo;
    private UserRepo          userRepo;
    private BankCardRepo      bankCardRepo;
    private MoneyRecordRepo   moneyRecordRepo;
    private EmailRepo         emailRepo;

    /*
    提现申请
     */
    @Transactional
    public WithdrawApply apply(Long userId, BigDecimal amount, Long bankCardId) {
        if (BigDecimal.ZERO.compareTo(amount) >= 0) {
            throw new BusinessException("提现金额小于等于0");
        }

        User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
        BankCard bankCard = bankCardRepo.findById(bankCardId).orElseThrow(new BusinessException("银行卡信息不存在"));

        if (BigDecimal.ZERO.compareTo(user.getMoney()) == 0) {
            throw new BusinessException("当前可提现金额0");
        }
        if (amount.compareTo(user.getMoney()) > 0) {
            throw new BusinessException("提现金额大于余额");
        }

        WithdrawApply apply = WithdrawApply.builder()
                .amount(amount)
                .bankCardId(bankCardId)
                .status(WithdrawStatus.PENDING)
                .userId(userId)
                .withdrawTime(LocalDateTime.now())
                //.bankCard(bankCard)
                .build();

        emailRepo.save(Email.builder()
                .receiveUserId(user.getId())
                .title("提现申请提交")
                .sendTime(LocalDate.now())
                .content(apply.getAmount() + "元，" + "提现到：" + bankCard.userInfo())
                .build()
        );

        return withdrawalsApplyRepo.save(apply);

    }

    /*
    申请是否成功
    */
    @Transactional
    public WithdrawApply audit(Long withdrawalsId, Boolean consent) {
        WithdrawApply withdrawals = withdrawalsApplyRepo.findById(withdrawalsId)
                .orElseThrow(new BusinessException("无此申请记录"));
        if (consent == null) {
            throw new BusinessException("操作错误");
        }
        Email email;

        if (consent) {
            withdrawals.setConsent(true);
            withdrawals.setStatus(WithdrawStatus.SUCCESS);

            //人工提现，设置余额
            User user = userRepo.findById(withdrawals.getUserId()).orElseThrow(new BusinessException("无用户"));
            user.setMoney(user.getMoney().subtract(withdrawals.getAmount()));
            userRepo.save(user);


            //记录到对账单
            BankCard bankCard = withdrawals.getBankCard();
            moneyRecordRepo.save(
                    MoneyRecord.builder()
                            .avatar(user.getAvatar())
                            .name("提现")
                            .userId(withdrawals.getUserId())
                            .time(LocalDateTime.now())
                            .type(FinancialType.WITHDRAW)
                            .remark(bankCard.getBankName())
                            .amount(withdrawals.getAmount())
                            .build()
            );

            //发送邮件通知
            email = Email.builder()
                    .receiveUserId(user.getId())
                    .title("提现申请通过")
                    .sendTime(LocalDate.now())
                    .content(withdrawals.getAmount() + "元，" + "提现到：" + bankCard.userInfo())
                    .build();

        } else {
            withdrawals.setConsent(false);
            withdrawals.setStatus(WithdrawStatus.FAIL);
            //发送邮件通知
            email = Email.builder()
                    .receiveUserId(withdrawals.getUserId())
                    .title("提现申请失败")
                    .sendTime(LocalDate.now())
                    .content("提现失败")
                    .build();
        }
        //报错邮件通知
        emailRepo.save(email);

        withdrawals.setAuditTime(LocalDateTime.now());
        return withdrawalsApplyRepo.save(withdrawals);
    }

}
