package com.liquidnet.service.order.service.impl;

import com.google.common.base.Joiner;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.entity.KylinOrderCoupons;
import com.liquidnet.service.kylin.service.IKylinOrderRefundsService;
import com.liquidnet.service.order.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单退款表 服务实现类 处理逻辑判断
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-05-26
 */
@Slf4j
@Service
public class OrderRefundOvertimeServiceImpl implements IKylinOrderRefundsService {
    @Autowired
    private KylinRefundsStatusServiceImpl kylinRefundsStatusServiceImpl;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private DataUtils dataUtils;

    @Value("${liquidnet.service.candy.url}")
    private String candyUrl;

    public Boolean refundApply(String orderTicketsId, String paymentId, String paymentType) {
        log.info("订单超时支付refundApply-Start：[orderTicketsId={}, [paymentId={}, paymentType={}]",
                orderTicketsId, paymentId, paymentType);
        KylinOrderTicketVo orderInfo = dataUtils.getOrderTicketVo(orderTicketsId);
        // 快递费 未进行判断
        BigDecimal RefundPriceExpress = orderInfo.getPriceExpress();
        BigDecimal priceActual = orderInfo.getPriceActual();
        BigDecimal priceExpress = orderInfo.getPriceExpress();

        // 查询订单入场人
        List<KylinOrderTicketEntitiesVo> entitiesList = orderInfo.getEntitiesVoList();
        if (!CollectionUtil.isEmpty(entitiesList)) {
            int allEntitiesCount = entitiesList.size();// 总入场人数量 排出未付款的 用来计算单入场人的价格
            BigDecimal onePrice = priceActual.subtract(priceExpress).divide(BigDecimal.valueOf(allEntitiesCount));//单价
            for (KylinOrderTicketEntitiesVo entities : entitiesList) {
                entities.setCanRefundedPrice(onePrice);
            }
        }

        List<String> ticketEntityIds = entitiesList.stream().map(KylinOrderTicketEntities -> KylinOrderTicketEntities.getOrderTicketEntitiesId()).collect(Collectors.toList());
        List<BigDecimal> entitiesPrice = entitiesList.stream().map(KylinOrderTicketEntities -> KylinOrderTicketEntities.getCanRefundedPrice()).collect(Collectors.toList());

        boolean res = kylinRefundsStatusServiceImpl.orderTicketRefunding(
                orderInfo, orderTicketsId,
                RefundPriceExpress,
                ticketEntityIds, entitiesPrice, paymentId, paymentType
        );
        if (res) {
            // 超时直接退还库存
//            for (KylinOrderTicketEntitiesVo entitiesInfo : entitiesList) {
//                // 因固定状态为未支付 所以无需判断 entitiesInfo.getIsPayment() == KylinTableStatusConst.ENTITIES_IS_PAYMENT3
//                dataUtils.changeSurplusGeneral(entitiesInfo.getTicketId(), 1);
//                dataUtils.changeBuyInfo(orderInfo.getUserId(), entitiesInfo.getEnterIdCode(), orderInfo.getPerformanceId(), entitiesInfo.getTicketId(), -1);
//            }
            // 退所有优惠券
            ArrayList<KylinOrderCoupons> orderCoupon = dataUtils.getOrderCoupon(orderTicketsId);
            if (!CollectionUtil.isEmpty(orderCoupon)) {
                List<String> uCouponIds = orderCoupon.stream().map(KylinOrderCoupons -> KylinOrderCoupons.getCouponCode()).collect(Collectors.toList());
                String uCouponIdsStr = Joiner.on(",").join(uCouponIds);
                MultiValueMap<String, String> params = CollectionUtil.linkedMultiValueMapStringString();
                params.add("uCouponIds", uCouponIdsStr);
                params.add("uid", orderInfo.getUserId());

                MultiValueMap<String, String> headers = CollectionUtil.linkedMultiValueMapStringString();
                headers.add("Accept", "application/json;charset=UTF-8");

                log.info("订单超时支付refundApply-退所有优惠券：[orderTicketsId={}, [params={}, candyUrl={}]",
                        orderTicketsId, params, candyUrl);
                String returnData = HttpUtil.post(candyUrl + "/candy-coupon/useBack", params, headers);
                log.info("订单超时支付refundApply-退券结果：[returnData={}]", returnData);
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String getOrderRefundCode(String orderRefundCode, int type) {
        return null;
    }
}
