package com.duiba.tuia.youtui.web.service.impl;

import static cn.com.duiba.tuia.activity.center.api.constant.BalanceType.CASH;
import static cn.com.duiba.tuia.activity.center.api.constant.BalanceType.GAME;
import static java.util.stream.Collectors.toList;

import cn.com.duiba.tuia.activity.center.api.constant.BalanceType;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.embed.DpmBuilder;
import com.duiba.tuia.youtui.web.embed.WalletEmbed;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import java.util.List;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;

import cn.com.duiba.tuia.activity.center.api.constant.BalanceRecordType;
import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteUserBalanceService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import com.duiba.tuia.youtui.web.constant.CacheKey;
import com.duiba.tuia.youtui.web.model.BalanceRecordVO;
import com.duiba.tuia.youtui.web.model.req.BalanceRecordQuery;
import com.duiba.tuia.youtui.web.model.rsp.PageBalanceRecord;
import com.duiba.tuia.youtui.web.service.BalanceRecordService;
import com.duiba.tuia.youtui.web.service.BaseCacheService;
import com.duiba.tuia.youtui.web.tool.CachedKeyUtils;
import com.duiba.tuia.youtui.web.tool.JsonUtils;

import cn.com.duiba.tuia.activity.center.api.common.PageDto;
import cn.com.duiba.tuia.activity.center.api.dto.consumer.BalanceRecordDto;
import cn.com.duiba.tuia.activity.center.api.dto.consumer.req.BalanceRecordMove;
import cn.com.duiba.tuia.activity.center.api.dto.consumer.req.BalanceRecordQueryDto;
import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteBalanceRecordService;
import org.springframework.util.StringUtils;

@Service
public class BalanceRecordServiceImpl extends BaseCacheService implements BalanceRecordService {

    @Resource
    private RemoteBalanceRecordService remoteBalanceRecordService;
    @Resource
    private RemoteUserBalanceService remoteUserBalanceService;

    @Override
    public PageBalanceRecord pageQuery(BalanceRecordQuery query, HttpServletRequest request) {

        Long userId = query.getUserId();
        Long appId = RequestLocal.get().getAppId();
        String host = request.getHeader("host");
        Integer balanceType = query.getBalanceType();
        BalanceRecordQueryDto queryDto = new BalanceRecordQueryDto();
        int rowStart = (query.getCurrentPage() - 1) * query.getPageSize();
        queryDto.setRowStart(rowStart);
        queryDto.setPageSize(query.getPageSize());
        queryDto.setSort("gmt_create");
        queryDto.setOrder("desc");
        queryDto.setUserId(userId);
        queryDto.setBalanceType(balanceType);

        PageDto<BalanceRecordDto> balanceRecordDtoPageDto = remoteBalanceRecordService.pageList(queryDto);

        List<BalanceRecordDto> list1 = balanceRecordDtoPageDto.getList();
        List<BalanceRecordVO> voList = list1.stream().map(dto -> {
            BalanceRecordVO vo = new BalanceRecordVO();
            vo.setAmount(dto.getAmount());
            vo.setDate(dto.getGmtCreate());
            vo.setTitle(BalanceRecordType.getDesc(dto.getRecordType()));
            vo.setFlowType(dto.getChangeType());
            if (Objects.equals(dto.getRecordType(), BalanceRecordType.WITHDRAW.getType()) &&
                    !StringUtils.isEmpty(dto.getExtInfo())) {
                vo.setStatus(JsonUtils.jsonToObject(BalanceRecordDto.ExtInfo.class, dto.getExtInfo()).getStatus());
            }
            return vo;
        }).collect(toList());

        int totalCount = balanceRecordDtoPageDto.getTotalCount();
        PageBalanceRecord pageBalanceRecord = new PageBalanceRecord();
        pageBalanceRecord.setTotal(totalCount);
        pageBalanceRecord.setBalanceRecordList(voList);
        pageBalanceRecord.setHasNext(totalCount > query.getCurrentPage() * query.getPageSize());
        pageBalanceRecord.setTotalAmount(remoteUserBalanceService.getAmount(userId, balanceType.equals(CASH.getType()) ? CASH : GAME));
        WalletEmbed embed = new WalletEmbed(null, null, DpmBuilder.build(appId, Constants.DPM.DPM_B_58, Constants.DPM.DPM_C_4, Constants.DPM.DPM_D_1), userId, appId, host);
        pageBalanceRecord.setStInfo(embed.buildWantCash());
        return pageBalanceRecord;

    }

    @Override
    public List<BalanceRecordVO> recentlyList(Integer size) {
        String redisKey = CachedKeyUtils.getRedisKey(CacheKey.RANDOM_BALANCE_RECORD_LIST);
        List<String> range = stringRedisTemplate.opsForList().range(redisKey, 0, size);
        return range.stream().map(s -> JsonUtils.jsonToObject(BalanceRecordVO.class, s)).collect(toList());
    }

    @Override
    public void putInRecentlyList(BalanceRecordVO vo, Integer size) {
        String redisKey = CachedKeyUtils.getRedisKey(CacheKey.RANDOM_BALANCE_RECORD_LIST);
        // 放入缓存
        stringRedisTemplate.opsForList().leftPush(redisKey, JsonUtils.objectToString(vo));
        // 只保存最近50条
        stringRedisTemplate.opsForList().trim(redisKey, 0, size);
        stringRedisTemplate.expire(redisKey, getRestSecondsToday(), TimeUnit.SECONDS);
    }

    @Override
    public Boolean moveBalance(Long srcUserId, Long destUserId, BalanceType balanceType) {
        return remoteBalanceRecordService.move(new BalanceRecordMove(srcUserId, destUserId, balanceType.getType()));
    }

    @Override
    public BalanceRecordDto getCreditsConsumeRecord(Long userId, String orderId, String duibaOrderNUm){
        return remoteBalanceRecordService.getCreditsConsumeRecord(userId, orderId, duibaOrderNUm);
    }
}
