package com.fzm.mall.server.admin.pay.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fzm.mall.server.admin.order.mapper.LogMapper;
import com.fzm.mall.server.admin.order.mapper.OrderMapper;
import com.fzm.mall.server.admin.order.mapper.PayMapper;
import com.fzm.mall.server.admin.order.model.Order;
import com.fzm.mall.server.admin.order.model.OrderLog;
import com.fzm.mall.server.admin.order.model.Pay;
import com.fzm.mall.server.admin.pay.service.WxPayService;
import com.fzm.mall.server.admin.util.WxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wulixian
 * @since 2021/10/18
 */
@Slf4j
@Service
@Transactional
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private LogMapper logMapper;

    @Override
    public void wxPayRefundReturn(String outBizNo, String eventType, String summary) {
        QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_biz_no", outBizNo);
        Pay pay = payMapper.selectOne(queryWrapper);

        JSONArray array = JSONObject.parseArray(pay.getOidsJson());
        array.stream().forEach(oidObj -> {
            String oid = oidObj.toString();
            UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
            orderUpdateWrapper.eq("oid", oid);

            Order order = new Order();

            String operation = OrderLog.ORDER_REFUND_SUCCESS;
            Integer orderState = Order.ORDER_STATE_REFUNDED;
            if (!eventType.equals(WxPayUtil.REFUND_SUCCESS)) {
                orderState = Order.ORDER_STATE_REFUND_FAIL;
                operation = OrderLog.ORDER_REFUND_FAILED;
            }
            order.setOrderState(orderState);
            order.setOid(oid);
            orderMapper.update(order, orderUpdateWrapper);

            /**
             * 商品订单操作记录
             */
            OrderLog log = new OrderLog(oid, orderState, operation, null, summary);
            logMapper.insert(log);
        });
    }
}
