package com.liquidnet.service.candy.service.impl;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.base.OrderCloseMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.candy.constant.CandyRedisConst;
import com.liquidnet.service.candy.dto.CandyUserCouponBasicDto;
import com.liquidnet.service.candy.service.ICandyConsumerService;
import com.liquidnet.service.candy.util.QueueUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 券消费 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-08-18
 */
@Service
public class CandyConsumerServiceImpl implements ICandyConsumerService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    QueueUtils queueUtils;

    @Override
    public ResponseDto<Boolean> couponOrderBackRedis(String uid, ArrayList<String> uCouponIdList) {
        try {
            List<CandyUserCouponBasicDto> dtoList = backCoupon(getCouponByUid(uid), uCouponIdList);
            setCouponByUid(uid, dtoList);
        } catch (Exception e) {
            LinkedList<String> mqList = new LinkedList<>();
            mqList.add(uCouponIdList + "," + uid);
            queueUtils.sendMsgByRedis(MQConst.CandyQueue.COUPON_ORDER_BACK.getKey(), OrderCloseMapping.get(mqList));
            return ResponseDto.failure();
        }
        return ResponseDto.success();
    }


    private List<CandyUserCouponBasicDto> getCouponByUid(String uid) {
        String redisKey = CandyRedisConst.BASIC_USER_COUPON.concat(uid);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            //降级
            return new ArrayList();
        } else {
            return (List<CandyUserCouponBasicDto>) obj;
        }
    }

    // 覆盖 CandyUserCouponBasicDto数组 根据用户id
    private void setCouponByUid(String uid, List<CandyUserCouponBasicDto> dtoList) {
        String redisKey = CandyRedisConst.BASIC_USER_COUPON.concat(uid);
        redisUtil.set(redisKey, dtoList);
    }

    /**
     * 回退券
     *
     * @param dtoList       CouponBaseDtoList
     * @param uCouponIdList 券唯一id list
     * @return List<CandyUserCouponBasicDto>
     */
    private List<CandyUserCouponBasicDto> backCoupon(List<CandyUserCouponBasicDto> dtoList, ArrayList<String> uCouponIdList) {
        boolean isHas = false;
        for (CandyUserCouponBasicDto dtoItem : dtoList) {
            if (uCouponIdList.contains(dtoItem.getUcouponId())) {
                if (dtoItem.getState().equals(5)) {
                    dtoItem.setState(1);
                    isHas = true;//券存在
                } else {
                }
            }
        }
        if (!isHas) {
            return null;//券不存在
        }
        return dtoList;
    }
}
