package com.qs.mp.user.service.impl;
import java.util.Date;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.common.enums.AppSourceEnum;
import com.qs.mp.common.enums.UserRedPkgStatusEnum;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.system.service.id.BizIdGenerator;
import com.qs.mp.user.domain.UserRedPkg;
import com.qs.mp.user.domain.param.RedPkgDrawParam;
import com.qs.mp.user.mapper.UserRedPkgMapper;
import com.qs.mp.user.service.IUserRedPkgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.transferbatch.TransferBatchService;
import com.wechat.pay.java.service.transferbatch.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wechat.pay.java.core.RSAConfig;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
/**
 * @auther quanshu
 * @create 2023-06-12 15:03:20
 * @describe 用户的红包服务实现类
 */
@Service
public class UserRedPkgServiceImpl extends ServiceImpl<UserRedPkgMapper, UserRedPkg> implements IUserRedPkgService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
    // 商户号
    public static String merChantId = "1643756321";
    // 证书编号
    public static String serialNumber = "6BA03F001024F81FAE490CAF240910512CBB1247";
    // privateKey
    public static String privateKeyFromPath = "/home/mangpiao/mp-server/data/apiclient_key.pem";
    // wechatPayCertificates
    public static String wechatPayCertificatesFromPath = "/home/mangpiao/mp-server/data/wechatpay.pem";
    @Autowired
    private BizIdGenerator bizIdGenerator;

    @Override
    public void distribute(Long userId, Integer value, String title, String picUrl, String refId) {
        UserRedPkg userRedPkg = new UserRedPkg();
        userRedPkg.setId(bizIdGenerator.newIdWithUidSharding(String.valueOf(userId)));
        userRedPkg.setUserId(userId);
        userRedPkg.setRefId(refId);
        userRedPkg.setTitle(title);
        userRedPkg.setPicUrl(picUrl);
        userRedPkg.setValue(value);
        userRedPkg.setStatus(UserRedPkgStatusEnum.UN_DRAW);
        save(userRedPkg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean draw(RedPkgDrawParam param) {

        // 获取红包信息
        UserRedPkg userRedPkg = getById(param.getId());

        boolean rst = update(new LambdaUpdateWrapper<UserRedPkg>().set(UserRedPkg::getStatus, UserRedPkgStatusEnum.DRAW)
                .set(UserRedPkg::getDrawTime,new Date())
                .eq(UserRedPkg::getId, userRedPkg.getId()));
        Assert.isTrue(rst,"用户红包提现更新失败");


        RSAConfig config = new RSAConfig.Builder()
                .merchantId(merChantId)
//                .privateKeyFromPath("mp-service/src/main/resources/config/apiclient_key.pem")
                .privateKeyFromPath(privateKeyFromPath)
                .merchantSerialNumber(serialNumber)
//                .wechatPayCertificatesFromPath("mp-service/src/main/resources/config/apiclient_cert.pem")
                .wechatPayCertificatesFromPath(wechatPayCertificatesFromPath)
                .build();


        TransferBatchService service = new TransferBatchService.Builder().config(config).build();
        InitiateBatchTransferRequest initiateBatchTransferRequest =
                new InitiateBatchTransferRequest();
        initiateBatchTransferRequest.setAppid(AppSourceEnum.MSDQ.getAppId());
        initiateBatchTransferRequest.setOutBatchNo("rp" + RandomUtil.randomNumbers(10));
        initiateBatchTransferRequest.setBatchName("红包提现");
        initiateBatchTransferRequest.setBatchRemark("红包提现");
        initiateBatchTransferRequest.setTotalAmount(Long.valueOf(userRedPkg.getValue()));
//        initiateBatchTransferRequest.setTotalAmount(100L);
        initiateBatchTransferRequest.setTotalNum(1);
        {
            List<TransferDetailInput> transferDetailListList = new ArrayList<>();
            {
                TransferDetailInput transferDetailInput = new TransferDetailInput();
                transferDetailInput.setOutDetailNo("rp" + RandomUtil.randomNumbers(10));
                transferDetailInput.setTransferAmount(Long.valueOf(userRedPkg.getValue()));
//                transferDetailInput.setTransferAmount(100L);
                transferDetailInput.setTransferRemark("红包提现");
                transferDetailInput.setOpenid(param.getOpenId());
                transferDetailListList.add(transferDetailInput);
            }
            initiateBatchTransferRequest.setTransferDetailList(
                    transferDetailListList);
        }
        initiateBatchTransferRequest.setTransferSceneId("1000");
        try {
            InitiateBatchTransferResponse response =
                    service.initiateBatchTransfer(initiateBatchTransferRequest);
        } catch (Exception e) {
            LogUtil.error(logger, e.getMessage());
            return false;
        }
        return true;
    }
}
