package com.jeequan.jeepay.mch.ctrl.aqf;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.converter.TransferConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.interfaces.paychannel.ITransferService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.service.ValidatorService;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.core.validate.Add;
import com.jeequan.jeepay.db.entity.SysConfig;
import com.jeequan.jeepay.db.entity.TransferInterfaceConfigEntity;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.db.entity.TransferWalletEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.TransferInterfaceConfigService;
import com.jeequan.jeepay.service.impl.TransferSubjectService;
import com.jeequan.jeepay.service.impl.TransferWalletService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * 代付对象
 *
 * @author deng
 * @since 2024/5/9
 */
@Slf4j
@RestController
@RequestMapping("/api/transferSubject")
public class TransferSubjectController extends CommonCtrl {

    @Autowired
    private TransferInterfaceConfigService transferInterfaceConfigService;

    @Autowired
    private ValidatorService validate;

    @Autowired
    private TransferSubjectService transferSubjectService;

    @Autowired
    private TransferWalletService transferWalletService;

    @Autowired
    private TransferConverter transferConverter;

    /**
     * 新增转账发起方
     */
    @PostMapping("/sponsor")
    public ApiRes sponsor() {
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);

        validate.validate(transferSubject, Add.class);

        // 当前登录用户信息
        transferSubject.setId("SUB" + DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        SysUser sysUser = getCurrentUser().getSysUser();
        transferSubject.setSubjectType("FQ");
        transferSubject.setTransApplyId(UUID.randomUUID().toString().replace("-", "").substring(0, 32));

        //如果不传递取默认值
        if (StringUtils.isEmpty(transferSubject.getIsvNo())) {
            SysConfig serviceOne = sysConfigService.getOne(SysConfig.gw().eq(SysConfig::getGroupKey, "defaultConfig")
                    .eq(SysConfig::getConfigKey, "defaultIsvNo"));
            if (serviceOne != null) {
                transferSubject.setIsvNo(serviceOne.getConfigVal());
            }
        }
        if (StringUtils.isNotEmpty(transferSubject.getIsvNo())) {
            //取对应参数信息
            //获取下发金额
            TransferInterfaceConfigEntity configEntity = transferInterfaceConfigService.getTransferConfig(transferSubject.getTransIfCode(), transferSubject.getIsvNo(), CS.SYS_ROLE_TYPE.ISV);

            if (configEntity != null && StringUtils.isNotEmpty(configEntity.getTransIfParams())) {
                String zfbDayMax = JSONObject.parseObject(configEntity.getTransIfParams()).getString("zfbDayMax");
                String bankCardDayMax = JSONObject.parseObject(configEntity.getTransIfParams()).getString("bankCardDayMax");
                transferSubject.setZfbDayMax(Long.valueOf(zfbDayMax));
                transferSubject.setBankCardDayMax(Long.valueOf(bankCardDayMax));
            }
        }

        transferSubject.setCreatedUid(sysUser.getSysUserId());
        boolean save = transferSubjectService.save(transferSubject);
        if (save) {
            return ApiRes.ok();
        } else {
            return ApiRes.customFail("新增失败！");
        }
    }

    @PostMapping("/refreshBalance")
    public ApiRes refreshBalance() {
        String transferSubjectId = getValStringRequired("transferSubjectId");
        TransferSubjectEntity transferSubject = transferSubjectService.getById(transferSubjectId);
        TransferWalletEntity transferWallet = transferWalletService.getByApplyId(transferSubject.getTransApplyId(), null);

        // 刷新记账本余额
        ITransferService transferService = SpringBeansUtil.getBean(transferWallet.getTransIfCode() + "TransferService", ITransferService.class);

        MutablePair<String, Long> balanceResult = transferService.queryBalanceAmount(transferConverter.toModel(transferWallet));
        // 查询更新余额
        transferWallet.setAccountBookBalance(balanceResult.right);
        transferWalletService.updateById(transferWallet);
        transferWalletService.leftQuota(transferWallet);

        return ApiRes.ok(transferWallet);
    }
}
