package com.liquidnet.service.consumer.kylin.receiver;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.OrderCloseMapping;
import com.liquidnet.service.candy.constant.CandyRedisConst;
import com.liquidnet.service.candy.dto.CandyUserCouponBasicDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.stream.StreamListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public abstract class AbstractCouponOrderBackRedisReceiver implements StreamListener<String, MapRecord<String, String, String>> {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        log.debug("CONSUMER SQL[streamKey:{},messageId:{},stream:{},body:{}]",
                this.getRedisStreamKey(), message.getId(), message.getStream(), message.getValue());

        boolean result = this.consumerSqlOperationCouponOrderBackHandler(message.getValue().get("message"));
        log.info("CONSUMER SQL RESULT:{} ==> MESSAGE_ID:{}", result, message.getId());

        try {
            stringRedisTemplate.opsForStream().acknowledge(getRedisStreamGroup(), message);
            stringRedisTemplate.opsForStream().delete(this.getRedisStreamKey(), message.getId());
        } catch (Exception e) {
            log.error("#CONSUMER SQL RESULT:{} ==> DEL_REDIS_QUEUE_MSG_EXCEPTION[MESSAGE_ID:{},MSG:{}]", result, message.getId(), JsonUtils.toJson(message), e);
        } finally {
            try {
                stringRedisTemplate.opsForStream().acknowledge(getRedisStreamGroup(), message);
                stringRedisTemplate.opsForStream().delete(this.getRedisStreamKey(), message.getId());
            } catch (Exception ignored) {
            }
        }
    }

    private boolean consumerSqlOperationCouponOrderBackHandler(String msg) {
        boolean aBoolean = false;
        try {
            OrderCloseMapping.orderCloseMessage mqMessage = JsonUtils.fromJson(msg, OrderCloseMapping.orderCloseMessage.class);

            //这里是 uCouponId和uid 懒。所以没新写方法
            for (int x = 0; x < mqMessage.getOrderTicketIds().size(); x++) {
                String t = mqMessage.getOrderTicketIds().get(x);
                String uCouponId = t.split(",")[0];
                String uid = t.split(",")[1];
                ArrayList<String> uCouponIdList = CollectionUtil.arrayListString();
                uCouponIdList.add(uCouponId);
                List<CandyUserCouponBasicDto> dtoList = backCoupon(getCouponByUid(uid), uCouponIdList);
                setCouponByUid(uid, dtoList);
            }

            aBoolean = true;
        } catch (Exception e) {
            log.error("CONSUMER SQL FAIL ==> {}", e.getMessage(), e);
        } finally {
            if (!aBoolean) {
                HashMap<String, String> map = CollectionUtil.mapStringString();
                map.put("message", msg);
                stringRedisTemplate.opsForStream().add(StreamRecords.mapBacked(map).withStreamKey(this.getRedisStreamKey()));
            }
        }
        return aBoolean;
    }

    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;
    }

    protected abstract String getRedisStreamKey();

    protected abstract String getRedisStreamGroup();
}
