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.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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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;

    @GetMapping("cache/member/{uid}")
    @ApiOperation("获取会员相关数据")
    public void cacheMember(@NotBlank @PathVariable(value = "uid") String uid) {
        try {
            log.info("同步 接口被调用,uid={}", uid);
            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> memberVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserMemberVo>>() {
            });
            log.info("调用 user = "+returnData);
            AdamUserMemberVo userMemberVo = memberVo.getData();
            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", e);
        }
    }

}
