package com.liquidnet.service.goblin.service.impl;

import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.vo.GoblinNftOrderDetailsVo;
import com.liquidnet.service.goblin.dto.vo.GoblinNftOrderVo;
import com.liquidnet.service.goblin.dto.vo.GoblinOrderSkuVo;
import com.liquidnet.service.goblin.service.IGoblinNftOrderAppService;
import com.liquidnet.service.goblin.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class GoblinNftOrderAppServiceImpl implements IGoblinNftOrderAppService {

    @Autowired
    GoblinRedisUtils redisUtils;
    @Autowired
    GoblinMongoUtils mongoUtils;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    GoblinOrderUtils orderUtils;

    @Override
    public ResponseDto<PageInfo<GoblinNftOrderDetailsVo>> orderList(int page) {
        String uid = CurrentUtil.getCurrentUid();
        List<GoblinNftOrderDetailsVo> orderVoList = ObjectUtil.goblinNftOrderDetailsVoArrayList();
        List<String> orderIds;
        orderIds = redisUtils.getNftOrderList(uid);

        int size = 40;
        int finalCount = orderIds.size() - page * size;
        int initCount = orderIds.size() - (page - 1) * size - 1;
        if (finalCount <= 0) {
            finalCount = 0;
        }
        for (int i = initCount; i >= finalCount; i--) {
            String orderId = orderIds.get(i);
            GoblinNftOrderVo orderVo = redisUtils.getGoblinNftOrder(orderId);
            GoblinNftOrderDetailsVo vo = GoblinNftOrderDetailsVo.getNew();
            BeanUtils.copyProperties(orderVo, vo);
            GoblinOrderSkuVo orderSkuVo = redisUtils.getGoblinOrderSkuVo(orderVo.getSkuId());
            vo.setOrderSkuVo(orderSkuVo);
            orderVoList.add(vo);
        }
        PageInfo<GoblinNftOrderDetailsVo> pageInfo = new PageInfo(orderVoList);
        pageInfo.setTotal(orderIds.size());
        return ResponseDto.success(pageInfo);
    }

    @Override
    public ResponseDto<GoblinNftOrderDetailsVo> orderDetails(String orderId) {
        GoblinNftOrderVo orderVo = redisUtils.getGoblinNftOrder(orderId);

        String uid = CurrentUtil.getCurrentUid();
        if (orderVo == null || !orderVo.getUserId().equals(uid)) {
            return ResponseDto.failure(ErrorMapping.get("20003"));
        }

        GoblinNftOrderDetailsVo vo = GoblinNftOrderDetailsVo.getNew();
        BeanUtils.copyProperties(orderVo, vo);
        GoblinOrderSkuVo orderSkuVo = redisUtils.getGoblinOrderSkuVo(orderVo.getSkuId());
        vo.setOrderSkuVo(orderSkuVo);

        return ResponseDto.success(vo);
    }

}
