package com.younike.wxpay.service.impl;

import com.beust.jcommander.internal.Lists;
import com.younike.wxpay.enums.TransactionType;
import com.younike.wxpay.params.*;
import com.younike.wxpay.responses.CloseResponse;
import com.younike.wxpay.responses.QueryResponse;
import com.younike.wxpay.responses.TransactionResponse;
import com.younike.wxpay.service.ISupplierPayService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class SupplierPayServiceImpl extends BasePayServiceImpl implements ISupplierPayService {

    @PostConstruct
    public void setup() {
        super.setup(PaymentConfig.builder()
                .isSupplier(true)
                .mchId("1552257391")
                .appId("wxcc56354382c8f8b4")
                .mchSerialNo("6B9A4B7AFDD4BE5213B68564252CCA5A126401DD")
                .apiV3Key("olJz7dYC7GbikgTw0QwTAmAjlFc7az9p")
                .certificatesPath("certs/uxx-supplier")
                .build());
    }

    @Override
    public TransactionResponse transaction(TransactionType type, TransactionParams params) {
        params.setSp_mchid(config.mchId);
        params.setSp_appid(config.appId);
        params.setSettle_info(SettleInfo.builder().profit_sharing(true).build());
        TransactionResponse response = super.transaction(type, params);

        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String noncestr = RandomStringUtils.randomAlphanumeric(32);
        String prepayId = response.getPrepay_id();
        PayInfo payInfo = PayInfo.builder()
                .appid(config.appId)
                .partnerid(config.mchId)
                .prepayid(prepayId)
                .packagestr("Sign=WXPay")
                .noncestr(noncestr)
                .timestamp(timestamp)
                .sign(super.sign(Lists.newArrayList(config.appId, timestamp, noncestr, prepayId)))
                .build();

        response.setPayInfo(payInfo);
        return response;
    }

    @Override
    public QueryResponse query(String outTradeNo, QueryParams params) {
        params.setSp_mchid(config.mchId);
        return super.query(outTradeNo, params);
    }

    @Override
    public CloseResponse close(String outTradeNo, CloseParams params) {
        params.setSp_mchid(config.mchId);
        return super.close(outTradeNo, params);
    }
}
