package com.jsowell.pile.service.impl;

import com.google.common.collect.Lists;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.ykc.ActionTypeEnum;
import com.jsowell.common.enums.ykc.OrderPayModeEnum;
import com.jsowell.common.enums.ykc.OrderPayRecordEnum;
import com.jsowell.common.enums.ykc.PaymentInstitutionsEnum;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.*;
import com.jsowell.pile.mapper.OrderPayRecordMapper;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.web.OrderDetailInfoVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderPayRecordServiceImpl implements OrderPayRecordService {

    @Resource
    private OrderPayRecordMapper orderPayRecordMapper;

    @Autowired
    private WxpayCallbackRecordService wxpayCallbackRecordService;

    @Autowired
    private AdapayCallbackRecordService adapayCallbackRecordService;

    @Autowired
    private IMemberTransactionRecordService memberTransactionRecordService;

    @Autowired
    private IOrderBasicInfoService orderBasicInfoService;

    @Autowired
    private RedisCache redisCache;


    @Override
    public int updateByPrimaryKeySelective(OrderPayRecord record) {
        return orderPayRecordMapper.updateByPrimaryKeySelective(record);
    }


    @Override
    public int batchInsert(List<OrderPayRecord> payRecordList) {
        return orderPayRecordMapper.batchInsert(payRecordList);
    }

    @Override
    public List<OrderPayRecord> getOrderPayRecordList(String orderCode) {
        return orderPayRecordMapper.getOrderPayRecordList(orderCode);
    }

    /**
     * 查询订单支付信息
     * 加缓存
     *
     * @param orderCode
     * @return
     */
    @Override
    public List<OrderDetailInfoVO.PayRecord> selectOrderPayInfoList(String orderCode) {
        // 缓存
        String redisKey = "select_order_pay_info_list:" + orderCode;
        List<OrderDetailInfoVO.PayRecord> resultList = redisCache.getCacheList(redisKey);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList;
        }

        // 订单信息
        OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        if (orderBasicInfo == null) {
            return Lists.newArrayList();
        }
        // 支付流水
        List<OrderPayRecord> orderPayRecordList = getOrderPayRecordList(orderCode);
        if (CollectionUtils.isEmpty(orderPayRecordList)) {
            return Lists.newArrayList();
        }
        List<OrderDetailInfoVO.PayRecord> payRecordList = Lists.newArrayList();
        for (OrderPayRecord orderPayRecord : orderPayRecordList) {
            OrderDetailInfoVO.PayRecord payInfo = new OrderDetailInfoVO.PayRecord();

            // 余额支付如果是由本金和赠送一起支付的，合并为一个
            // BigDecimal bigDecimal = orderPayRecordList.stream()
            //         .map(OrderPayRecord::getPayAmount)
            //         .reduce(BigDecimal.ZERO, BigDecimal::add);
            // payInfo.setPayAmount(bigDecimal.toString());
            payInfo.setPayAmount(orderPayRecord.getPayAmount().toString());
            payInfo.setPayStatus(orderBasicInfo.getPayStatus());
            payInfo.setPayTime(DateUtils.formatDateTime(orderBasicInfo.getPayTime()));
            // if (orderBasicInfo.getRefundAmount() != null) {
            //     payInfo.setRefundAmount(orderBasicInfo.getRefundAmount().toString());
            // }

            String payMode = orderPayRecord.getPayMode();
            if (StringUtils.equals(payMode, OrderPayRecordEnum.PRINCIPAL_BALANCE_PAYMENT.getValue())
                    || StringUtils.equals(payMode, OrderPayRecordEnum.GIFT_BALANCE_PAYMENT.getValue())) {
                // 使用余额支付
                payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_BALANCE.getValue());
                payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_BALANCE.getLabel());
            } else if (StringUtils.equals(payMode, OrderPayRecordEnum.WECHATPAY_PAYMENT.getValue())) {
                // 使用微信支付
                payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue());
                payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getLabel());

                // 判断是微信支付还是汇付支付
                MemberTransactionRecord record = memberTransactionRecordService.selectByOrderCode(orderCode, ActionTypeEnum.FORWARD.getValue());
                if (record != null) {
                    String paymentInstitutions = record.getPaymentInstitutions();
                    if (StringUtils.equals(paymentInstitutions, PaymentInstitutionsEnum.WECHAT_PAY.getValue())) {
                        // 查微信支付回调记录
                        WxpayCallbackRecord wxpayCallbackRecord = wxpayCallbackRecordService.selectByOrderCode(orderCode);
                        if (wxpayCallbackRecord != null) {
                            payInfo.setOutTradeNo(wxpayCallbackRecord.getOutTradeNo());
                            payInfo.setTransactionId(wxpayCallbackRecord.getTransactionId());
                        }
                    } else if (StringUtils.equals(paymentInstitutions, PaymentInstitutionsEnum.ADAPAY.getValue())) {
                        // 查询汇付支付回调
                        AdapayCallbackRecord adapayCallbackRecord = adapayCallbackRecordService.selectByOrderCode(orderCode);
                        if (adapayCallbackRecord != null) {
                            payInfo.setOutTradeNo(adapayCallbackRecord.getPaymentId());
                            payInfo.setTransactionId(adapayCallbackRecord.getOutTransId());
                        }
                    }
                }
                // 查微信支付回调记录
                // WxpayCallbackRecord wxpayCallbackRecord = wxpayCallbackRecordService.selectByOrderCode(orderCode);
                // if (wxpayCallbackRecord != null) {
                //     payInfo.setOutTradeNo(wxpayCallbackRecord.getOutTradeNo());
                //     payInfo.setTransactionId(wxpayCallbackRecord.getTransactionId());
                // }
            } else if (StringUtils.equals(payMode, OrderPayRecordEnum.WHITELIST_PAYMENT.getValue())) {
                // 使用白名单支付
                payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getValue());
                payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getLabel());
            }
            payRecordList.add(payInfo);
        }
        redisCache.setCacheList(redisKey, payRecordList);
        redisCache.expire(redisKey, CacheConstants.cache_expire_time_10d);
        return payRecordList;
    }

    @Override
    public int insertSelective(OrderPayRecord record) {
        return orderPayRecordMapper.insertSelective(record);
    }

    @Override
    public OrderPayRecord selectByPrimaryKey(Integer id) {
        return orderPayRecordMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateBatch(List<OrderPayRecord> list) {
        return orderPayRecordMapper.updateBatch(list);
    }

    @Override
    public int insertOrUpdate(OrderPayRecord record) {
        return orderPayRecordMapper.insertOrUpdate(record);
    }

    @Override
    public int insertOrUpdateSelective(OrderPayRecord record) {
        return orderPayRecordMapper.insertOrUpdateSelective(record);
    }
}

