package cn.pluss.platform.sxf.audit;

import cn.pluss.platform.channel.BaseMchChannelRateNewService;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.MerchantRateNew;
import cn.pluss.platform.entity.MerchantRateNewRecord;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantBaseInfoMapper;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.sxf.SxfService;
import cn.pluss.platform.util.RSAUtils;
import cn.pluss.platform.util.SignUtils;
import cn.pluss.platform.util.SxfConfg;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 *
 * @author djh
 */
@Slf4j
@RequiredArgsConstructor
@Service("sxfChangeRateNewService")
@EqualsAndHashCode(callSuper = true)
public class SxfChangeRateNewServiceImpl extends BaseMchChannelRateNewService {

    private final SxfService sxfService;
    private final MerchantBaseInfoMapper merchantBaseInfoMapper;

    @Setter(onMethod_ = {@Autowired,@Lazy})
    private MerchantChannelStatusService merchantChannelStatusService;

    @Override
    public void process(String userId, MerchantRateNew merchantRate) {
        MerchantRateNew.setRateValue(merchantRate);

        List<MerchantBaseInfo> merchantBaseInfoList = merchantBaseInfoMapper.selectListByUserId(userId);
        if (merchantBaseInfoList == null || merchantBaseInfoList.size() == 0) {
            throw new MsgException("无法获取商户信息");
        }

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoList.get(0);
        MerchantChannelStatus merchantChannelStatus = new MerchantChannelStatus().setChannel(1).setMerchantCode(merchantBaseInfo.getMerchantCode());
        merchantChannelStatus = merchantChannelStatusService.getOne(new QueryWrapper<>(merchantChannelStatus));
        if (merchantChannelStatus == null) {
            throw new MsgException("商户还未进件");
        }

        JSONObject reqParam = new JSONObject();
        reqParam.put("mno", merchantChannelStatus.getMerchantId());
        JSONArray qrCodeList = new JSONArray();
        // 微信
        JSONObject rate1 = new JSONObject();
        rate1.put("rate", merchantRate.getWxRateValue().divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
        rate1.put("rateType", "01");
        qrCodeList.add(rate1);
        // 支付宝
        rate1 = new JSONObject();
        rate1.put("rate", merchantRate.getAliRateValue().divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
        rate1.put("rateType", "02");
        qrCodeList.add(rate1);
        // 银联，小于1000, 银联费率最低是23
        rate1 = new JSONObject();
        rate1.put("rate", merchantRate.getBankRateValue().divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
        rate1.put("rateType", "06");
        qrCodeList.add(rate1);
        // 银联，大于1000
        rate1 = new JSONObject();
        rate1.put("rate", "0.60");
        rate1.put("rateType", "07");
        qrCodeList.add(rate1);
        reqParam.put("qrcodeList", qrCodeList);
        //reqParam.put("mecAuthority", "01");
        reqParam.put("startSettleAmt", "0.00");
        reqParam.put("reserveSettleAmt", "0.00");
        reqParam.put("settleType", "04");
        String[] channelArr = new String[]{"01", "02", "03"};
        reqParam.put("supportPayChannels", channelArr);

        String[] tradeType = new String[] {"01", "02", "03", "04"};
        reqParam.put("supportTradeTypes", tradeType);

        JSONObject result = sxfService.requestApi(SxfConfg.SXF_UPDATE_MERCHANT_RATE, reqParam);

        String signContent = SignUtils.getSignContent(result);
        boolean sign;
        try {
            sign = RSAUtils.checkSign(SxfConfg.PUBLIC_KEY, signContent, result.getString("sign"));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("修改费率结果验签失败");
            throw new MsgException("修改费率失败");
        }
        if (!sign) {
            throw new MsgException("修改费率失败");
        }

        if (!SxfConfg.SXF_SUCCESS_CODE.equals(result.getString("code"))) {
            throw new MsgException(result.getString("msg"));
        }

        JSONObject respData = result.getJSONObject("respData");
        if (!SxfConfg.SXF_SUCCESS_CODE.equals(respData.get("bizCode"))) {
            throw new MsgException(respData.getString("bizMsg"));
        }
    }

    @Override
    public void after(String userId, MerchantRateNew merchantRate) {
        // 保存费率修改记录
        MerchantRateNewRecord merchantRateRecord = Converter.INSTANCE.trans(merchantRate);
        merchantRateRecord.setStatus("3");
        merchantRateRecord.setCreateTime(new Date());
        merchantRateRecord.setUpdateTime(new Date());
        rateNewRecordService.save(merchantRateRecord);
    }

    @Override
    public String getChannelId() {
        return "1";
    }

    @Override
    public MerchantRateNew getDefaultRate() {
        MerchantRateNew merchantRateNew = new MerchantRateNew();
        merchantRateNew.setChannel(1);
        merchantRateNew.setWxRate(38);
        merchantRateNew.setAliRate(38);
        merchantRateNew.setBankRate(38);
        merchantRateNew.setBankRateLarge(-1);
        return merchantRateNew;
    }
}