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.service.IKylinPerformancesService;
import com.liquidnet.service.kylin.service.impl.KylinOrderTicketsRefundServiceImpl;
import com.liquidnet.service.kylin.service.impl.KylinPerformancesServiceImpl;
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;
import java.util.HashMap;

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

    @Autowired
    IKylinConsmerService kylinConsmerService;

    @Autowired
    private KylinPerformancesServiceImpl kylinPerformancesService;

    @Autowired
    private KylinOrderTicketsRefundServiceImpl kylinOrderTicketsRefundService;

    @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);
    }
    @GetMapping("/setNoticeIds")
    @ApiOperation("演出预告列表定时任务")
    public ResponseDto<HashMap<String,Object>> setNoticeIds(){
        HashMap<String, Object> map = kylinPerformancesService.setNoticeIds();
        return ResponseDto.success(map);
    }

    /**
     * 系统全额退款（拼团超时等平台任务调用）。走 /inner/**，无需登录态。
     */
    @PostMapping("orderRefund/systemFullRefund")
    @ApiOperation("系统全额退款")
    public ResponseDto systemFullRefund(
            @RequestParam("orderId") @NotBlank(message = "订单ID不能为空") String orderId,
            @RequestParam("orderTicketEntitiesId") @NotBlank(message = "票单ID不能为空") String orderTicketEntitiesId,
            @RequestParam(value = "reason", required = false) String reason
    ) {
        return kylinOrderTicketsRefundService.systemFullRefund(orderId, orderTicketEntitiesId, reason);
    }

}
