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.AdamEntersVo;
import com.liquidnet.service.adam.dto.vo.AdamUserMemberVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.feign.adam.api.FeignAdamBaseClient;
import com.liquidnet.service.kylin.utils.DataUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

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

    @PostMapping("cache/member")
    @ApiOperation("获取会员相关数据")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "query", dataType = "String", name = "uid", value = "会员id"),
    })
    public void cacheMember(@RequestParam("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> memberVo = JsonUtils.fromJson(returnData, new TypeReference<ResponseDto<AdamUserMemberVo>>() {
            });

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

}
