package com.iformall.service.impl;
import com.iformall.domain.dto.WxUserCouponDto;
import com.iformall.domain.po.WxCoupon;
import com.iformall.domain.po.WxCouponOrder;
import com.iformall.mapper.WxCouponMapper;
import com.iformall.mapper.WxCouponOrderMapper;
import com.iformall.service.WxUserCouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by syf on 2018/8/10.
 */
@Service
public class WxUserCouponServiceImpl implements WxUserCouponService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponOrderMapper wxCouponOrderMapper;
    @Autowired
    private WxCouponMapper wxCouponMapper;

    /**
     *
     * @param userId 用户id
     * @param status 用户卡券状态
     * @return
     */
    @Override
    public List<WxUserCouponDto> findList(Long userId, int status) {
        //TODO 待测试优化
        List<WxUserCouponDto> wxUserCoupons = new ArrayList<>();
        //查询订单表
        WxCouponOrder wxCouponOrder = new WxCouponOrder();
        wxCouponOrder.setCUserId(userId);
        wxCouponOrder.setCouponOrderStatus(status);//状态：0，待使用 1，已核销 2，已过期 3，已退款
        List<WxCouponOrder> wxCouponOrders = wxCouponOrderMapper.findList(wxCouponOrder);
        if(wxCouponOrders.isEmpty()){
            return wxUserCoupons;
        }
        List<Long> ids = wxCouponOrders.stream().map(p->p.getCouponId()).distinct().collect(Collectors.toList());
        WxCoupon wxCoupon = new WxCoupon();
        wxCoupon.setIds(ids);
        List<WxCoupon> wxCoupons = wxCouponMapper.findList(wxCoupon);
        Map<Long,WxCoupon> couponNamesMap = wxCoupons.stream().collect(Collectors.toMap(WxCoupon::getId,p->p));
        for (WxCouponOrder temp:wxCouponOrders) {
            wxUserCoupons.add(getWxUserCoupon(temp,couponNamesMap.get(temp.getCouponId())));
        }
        return wxUserCoupons;
    }
    public WxUserCouponDto getWxUserCoupon(WxCouponOrder wxCouponOrder, WxCoupon wxCoupon){
        WxUserCouponDto wxUserCoupon = new WxUserCouponDto();
        wxUserCoupon.setOrderId(wxCouponOrder.getId());
        wxUserCoupon.setCUserId(wxCouponOrder.getCUserId());
        wxUserCoupon.setCouponStatus(wxCouponOrder.getCouponOrderStatus());
        wxUserCoupon.setCouponId(wxCouponOrder.getCouponId());
        wxUserCoupon.setValidDate(wxCouponOrder.getExpiredTime());
        wxUserCoupon.setCouponTitle(wxCoupon.getTitle());
        return wxUserCoupon;
    }
}


