package com.hai.service.pay.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.utils.DateUtil;
import com.hai.dao.HighPayRecordMapper;
import com.hai.entity.HighPayRecord;
import com.hai.service.pay.PayRecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;

@Service(value = "payRecordService")
public class PayRecordServiceImpl implements PayRecordService {

    @Resource
    private HighPayRecordMapper payRecordMapper;

    @Override
    public int addPayRecord(Map<String, String> paramsMap, String payType) throws Exception {
        HighPayRecord payRecord = new HighPayRecord();
        if ("Alipay".equals(payType)) {

            payRecord.setPaySerialNo(paramsMap.get("trade_no"));
            payRecord.setResType(2);
            payRecord.setPayType(1);
            payRecord.setPayMoney(new BigDecimal(paramsMap.get("receipt_amount")));
            payRecord.setPayTime(DateUtil.StringToDate(paramsMap.get("gmt_payment"), "yyyy-MM-dd HH:mm:ss"));
            payRecord.setBodyInfo(JSONObject.toJSONString(paramsMap));
            payRecord.setPayResult(paramsMap.get("trade_status"));

        } else if ("WechatPay".equals(payType)) {

            payRecord.setPaySerialNo(paramsMap.get("transaction_id"));
            payRecord.setResType(2);
            payRecord.setPayType(2);
            payRecord.setPayMoney(new BigDecimal(paramsMap.get("cash_fee")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
            payRecord.setPayTime(DateUtil.StringToDate(paramsMap.get("time_end"), "yyyyMMddHHmmss"));
            payRecord.setBodyInfo(JSONObject.toJSONString(paramsMap));
            payRecord.setPayResult(paramsMap.get("result_code"));

        } else {
            return 0;
        }

        payRecord.setCreateTime(new Date());
        return payRecordMapper.insertSelective(payRecord);
    }

    @Override
    public int addPayRecord(HighPayRecord payRecord) throws Exception {

        payRecord.setCreateTime(new Date());
        return payRecordMapper.insertSelective(payRecord);
    }

}
