package com.liquidnet.service.kylin.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.dto.vo.AdamUserMemberVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.service.IKylinConsmerService;
import com.liquidnet.service.kylin.utils.DataUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Api(tags = "内部接口")
@RestController
@RequestMapping("inner")
@Slf4j
public class InnerController {
    @Autowired
    DataUtils dataUtils;
    @Value("${liquidnet.adam.url}")
    private String adamUrl;

    @Autowired
    IKylinConsmerService kylinConsmerService;

    @GetMapping("cache/member/{uid}")
    @ApiOperation("获取会员相关数据")
    public void cacheMember(@NotBlank @PathVariable(value = "uid") String uid) {
        try {
            MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
            header.add("Accept", "application/json;charset=UTF-8");
            String returnData = HttpUtil.get(adamUrl + "/adam/rsc/inquire/member?uid=" + uid, null, header);
            ResponseDto<AdamUserMemberVo> responseDto = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserMemberVo>>() {
            });
            if (null != responseDto) {
                AdamUserMemberVo userMemberVo = responseDto.getData();
                if (null != userMemberVo) {
                    if (userMemberVo.getState() == 1) {
                        long second = ChronoUnit.SECONDS.between(LocalDateTime.now(), userMemberVo.getExpiryAt());
                        log.debug("过期时间=" + second);
                        if (userMemberVo.isOldMember()) {
                            dataUtils.saveMember(uid, 2, second);
                        } else {
                            dataUtils.saveMember(uid, 1, second);
                        }
                    } else {
                        dataUtils.delMember(uid);
                    }
                }
            }
        } catch (Exception e) {
            log.error("会员信息error[uid={}]", uid, e);
        }
    }

    @PostMapping("consumer/orderTransferOverTime")
    @ApiOperation("转赠过期消费")
    public ResponseDto<Boolean> orderTransferOverTime(String orderId) {
        return kylinConsmerService.orderTransferOverTime(orderId);
    }
}
