package com.izouma.nineth.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anji.captcha.util.StringUtils;
import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.domain.UserBankCard;
import com.izouma.nineth.domain.UserFundAccount;
import com.izouma.nineth.dto.userfund.BalanceInfoDTO;
import com.izouma.nineth.enums.AccountStatus;
import com.izouma.nineth.enums.AccountType;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.IdentityAuthRepo;
import com.izouma.nineth.repo.UserFundAccountRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Map;

/**
 *
 * 商盟资金账户
 *
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserFundAccountForSumpayService {

    private UserFundAccountRepo userFundAccountRepo;

    private SumpayMerchantService sumpayMerchantService;

    private IdentityAuthRepo identityAuthRepo;

    /**
     * 获取商盟账户
     * @param userId
     * @return
     */
    public UserFundAccount getAccount(Long userId){
        UserFundAccount userFundAccount = userFundAccountRepo.findByUserIdAndAccountType(userId, AccountType.SUMPAY_USER)
                .orElse(null);
        return  userFundAccount;
    }


    /**
     * 添加商盟账户
     * @param userId
     * @return
     */
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public UserFundAccount addAccount(Long userId){
        IdentityAuth identityAuth = identityAuthRepo.findFirstByUserIdAndStatusAndDelFalseOrderByCreatedAtDesc(userId, AuthStatus.SUCCESS)
                .orElseThrow(new BusinessException("用户未通过实名认证"));
        //相同的注册会返回同一个ID
        Map<String,String> res = sumpayMerchantService.register(identityAuth);
        //失败时返回
        String error_code = res.get("error_code");
        String error_msg = res.get("error_msg");
        String description = res.get("description");
        String thirdUserId = res.get("user_id");
        String status = res.get("status");
        AccountStatus accountStatus = AccountStatus.NORMAL;
        //0-失败，1-成功，2-处理中
        if(!"1".equals(status)){
            accountStatus = AccountStatus.LOCALED;
        }

        String accountError = null;
        if("0".equals(status)){
            accountError = error_msg + "("+error_code+")";
        }

        //记录资金账户信息
        UserFundAccount account  = userFundAccountRepo.findByUserIdAndAccountType(userId, AccountType.SUMPAY_USER)
                .orElse(null);

        if(account != null){
            account.setAccountNo(identityAuth.getIdNo());
            account.setAccountName(identityAuth.getRealName());
            account.setThirdUserId(thirdUserId);
            account.setAccountStatus(accountStatus);
        }else{
            UserFundAccount.UserFundAccountBuilder builder = UserFundAccount.builder();
            builder.userId(userId).accountType(AccountType.SUMPAY_USER)
                    .accountNo(identityAuth.getIdNo())
                    .accountName(identityAuth.getRealName())
                    .thirdUserId(thirdUserId).accountStatus(accountStatus);
            account = builder.build();
        }

        account.setAccountError(accountError);

        userFundAccountRepo.save(account);

        return account;
    }


    /**
     * 检查商盟支付账户状态
     * @param userId
     * @return
     */
    @Transactional
    public UserFundAccount checkAccount(Long userId){
        Map<String,String>  res = sumpayMerchantService.registerQuery(userId);
        String registerStatus = res.get("register_status");
        String userStatus = res.get("user_status");
        String description = res.get("description");
        if(StringUtils.isNotEmpty(description)){
            log.warn("商盟账户状态不正确， 用户ID:{}, 状态：{}, 描述：{}", userId, userStatus, description);
        }

        AccountStatus accountStatus = AccountStatus.NORMAL;
        if(!"1".equals(userStatus)){
            accountStatus = AccountStatus.LOCALED;
        }
        //记录资金账户信息
        UserFundAccount account  = userFundAccountRepo.findByUserIdAndAccountType(userId, AccountType.SUMPAY_USER)
                .orElseThrow(new BusinessException("对应资金账户未找到"));
        account.setAccountStatus(accountStatus);
        return account;
    }

    /**
     * 修复商盟账户状态
     * @param userId
     * @return
     */
    @Transactional
    public UserFundAccount repairAccount(Long userId){
        //记录资金账户信息
        UserFundAccount account  = userFundAccountRepo.findByUserIdAndAccountType(userId, AccountType.SUMPAY_USER)
                .orElse(null);

        if(account != null && account.getAccountStatus() == AccountStatus.LOCALED){
            Map<String,String>  res = sumpayMerchantService.userModify(userId);
            String userStatus = res.get("user_status");
            String description = res.get("description");
            AccountStatus accountStatus = AccountStatus.NORMAL;
            if(StringUtils.isNotEmpty(description)){
                log.warn("商盟账户状态不正确， 用户ID:{}, 状态：{}, 描述：{}", userId, userStatus, description);
                accountStatus = AccountStatus.LOCALED;
            }

            account.setAccountStatus(accountStatus);

        }

        return account;
    }


    /**
     * 商盟余额查询
     * @param userId
     * @return
     */
    public BalanceInfoDTO balanceQuery(Long userId){
        //记录资金账户信息
        UserFundAccount account  = userFundAccountRepo.findByUserIdAndAccountType(userId, AccountType.SUMPAY_USER)
                .orElseThrow(new BusinessException("杉德账户不存在"));
        Map<String,String>  balanceRes = sumpayMerchantService.balanceQuery(account.getUserId());
        //{total_balance=0.85, resp_code=000000, avaliable_balance=0.85, freeze_balance=0}

        String avaliableBalance = balanceRes.get("avaliable_balance");
        String freezeBalance = balanceRes.get("freeze_balance");
        BalanceInfoDTO balanceInfo = new BalanceInfoDTO();
        balanceInfo.setAvailableBalance(new BigDecimal(avaliableBalance));
        balanceInfo.setFreezeBalance(new BigDecimal(freezeBalance));
        balanceInfo.setAccountStatus(account.getAccountStatus().name());

        return balanceInfo;
    }

    /**
     * 商盟支付绑卡
     * @return
     */
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public UserFundAccount bindCard(UserBankCard userBankCard){
        //记录资金账户信息
        UserFundAccount account  = userFundAccountRepo.findByUserIdAndAccountType(userBankCard.getUserId(), AccountType.SUMPAY_USER)
                .orElse(null);
        if(account != null){
            Map<String,String>  res = sumpayMerchantService.bindCard(userBankCard.getUserId(), userBankCard.getBankNo(), userBankCard.getPhone());
            String bind_card_id = res.get("bind_card_id");
            account.setUserBankCardId(userBankCard.getId());
            account.setThirdBankId(bind_card_id);
            userFundAccountRepo.save(account);

        }

        return account;

    }



}
