package com.liquidnet.service.adam.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.service.adam.dto.vo.*;
import com.liquidnet.service.adam.service.AdamRdmService;
import com.liquidnet.service.adam.service.IAdamUserMemberService;
import com.liquidnet.service.adam.util.QueueUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.feign.adam.rsc.FeignAdamPlatformClient;
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.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

@ApiSupport(order = 10030)
@Api(tags = "会员信息")
@Slf4j
@Validated
@RestController
@RequestMapping("member")
public class AdamMemberController {
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    AdamRdmService adamRdmService;
    @Autowired
    IAdamUserMemberService adamUserMemberService;
    @Autowired
    FeignAdamPlatformClient feignAdamPlatformClient;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "会员信息")
    @GetMapping("info")
    public ResponseDto<AdamMemberVo> info() {
        AdamMemberSimpleVo memberSimpleVo = adamRdmService.getMemberSimpleVo();
        AdamMemberVo memberVo = null;
        if (null != memberSimpleVo && null != (memberVo = adamRdmService.getMemberVoByMemberId(memberSimpleVo.getMemberId()))) {
//            memberVo.setBuySwitch(adamRdmService.getSwitch(AdamRedisConst.SWITCH_BUY_MEMBER));
            memberVo.calculateLimitMarker(adamRdmService.getMaxMemberLimitation());

            memberVo.setPriceVoList(adamRdmService.getMemberPriceVoByMemberId(memberVo.getMemberId()));

            String currentUid = CurrentUtil.getCurrentUid();
            if (!StringUtils.isEmpty(currentUid)) {
                AdamUserMemberVo userMemberVo = adamRdmService.getUserMemberVoByUid(currentUid);

                memberVo.setUserMemberVo(userMemberVo);

                if (null == userMemberVo || !userMemberVo.isActive()) {
                    memberVo.setRightsVoList(adamRdmService.getMemberRightsVoByMemberId(memberVo.getMemberId(), 0));
                } else if (userMemberVo.isActive()) {
                    memberVo.setRightsVoList(
                            userMemberVo.isOldMember() ? adamRdmService.getMemberRightsVoByMemberId(memberVo.getMemberId(), 1)
                            : adamRdmService.getMemberRightsVoByMemberId(memberVo.getMemberId(), 0)
                    );
                }
            } else {
                memberVo.setUserMemberVo(null);
                memberVo.setRightsVoList(adamRdmService.getMemberRightsVoByMemberId(memberVo.getMemberId(), 0));
            }
        }
        return ResponseDto.success(memberVo);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "会员协议")
    @GetMapping("agreement")
    public ResponseDto<String> agreement() {
        return ResponseDto.success(adamRdmService.getMemberAgreement());
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "权益详情")
    @GetMapping("info/rights")
    public ResponseDto<AdamMemberRightsDetailVo> infoRights(@RequestParam String memberId, @RequestParam String mrightsId) {
        return ResponseDto.success(adamRdmService.getMemberRightsDetailVoByRightsId(memberId, mrightsId));
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "会员开售状态")
    @GetMapping("onsale")
    public ResponseDto<Integer> onsale() {
        AdamMemberSimpleVo memberSimpleVo = adamRdmService.getMemberSimpleVo();
        AdamMemberVo memberVo = null;
        if (null != memberSimpleVo && null != (memberVo = adamRdmService.getMemberVoByMemberId(memberSimpleVo.getMemberId()))) {
            return ResponseDto.success(memberVo.getOnsale());
        }
        return ResponseDto.success(1);
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "会员卡信息")
    @GetMapping("joininfo")
    public ResponseDto<AdamMemberJoinusVo> joininfo() {
        String currentUid = CurrentUtil.getCurrentUid();

        AdamUserInfoVo userInfoVo = null;
        if (!StringUtils.isEmpty(currentUid)) {
            userInfoVo = adamRdmService.getUserInfoVoByUid(currentUid);
        }
        AdamMemberJoinusVo joinusVo;
        if (null == userInfoVo || StringUtils.startsWithIgnoreCase(userInfoVo.getQrCode(), "lN")) {
            joinusVo = adamRdmService.getMemberJoinusVo(0);
        } else {
            AdamUserMemberVo userMemberVo = adamRdmService.getUserMemberVoByUid(currentUid);
            joinusVo = adamRdmService.getMemberJoinusVo(null != userMemberVo && userMemberVo.isActive() ? 50 : 10);
            joinusVo.setState(1);
            joinusVo.setQrCode(userInfoVo.getQrCode());
            if (null != userMemberVo) {
                joinusVo.setMemberNo(userMemberVo.getMemberNo());
            }
        }

        return ResponseDto.success(joinusVo);
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "领取会员卡")
    @GetMapping("joinus")
    public ResponseDto<AdamMemberJoinusVo> joinus() {
        String currentUid = CurrentUtil.getCurrentUid();

        AdamUserInfoVo userInfoVo;
        if (StringUtils.isEmpty(currentUid) || null == (userInfoVo = adamRdmService.getUserInfoVoByUid(currentUid))) {
            log.warn("###用户不存在[UID:{},TOKEN:{}]", currentUid, CurrentUtil.getToken());
            return this.joininfo();
        }
        final String oldQrCode = userInfoVo.getQrCode();
        if (StringUtils.startsWithIgnoreCase(oldQrCode, "lN")) {// `lN`开头即未领取，这里做领取操作
            userInfoVo.setQrCode(adamRdmService.generateMemberUniqueSerialNumber(userInfoVo.getMobile()));
            adamRdmService.setUserInfoVoByUid(currentUid, userInfoVo);
            log.info("领取会员卡[UID:{},MOBILE:{},QR_CODE:{},OLD_QR_CODE:{}]", currentUid, userInfoVo.getMobile(), userInfoVo.getQrCode(), oldQrCode);

            queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UCENTER.getKey(),
                    SqlMapping.get("adam_user_info.update_qr_code", userInfoVo.getQrCode(), currentUid)
            );
        }
        AdamUserMemberVo userMemberVo = adamRdmService.getUserMemberVoByUid(currentUid);
        AdamMemberJoinusVo joinusVo = adamRdmService.getMemberJoinusVo(null != userMemberVo && userMemberVo.isActive() ? 50 : 10);
        joinusVo.setState(1);
        joinusVo.setQrCode(userInfoVo.getQrCode());
        if (null != userMemberVo) {
            joinusVo.setMemberNo(userMemberVo.getMemberNo());
        }

//        try {
//            feignAdamPlatformClient.initScore(currentUid);
//        } catch (Exception e) {
//            log.error("领取会员卡:积分处理异常[UID:{}]", currentUid, e);
//        }

        return ResponseDto.success(joinusVo);
    }

    /* ------------------------------------------------------------｜@API:RSC */

    @ApiOperationSupport(order = 99)
    @ApiOperation(value = "@API:是否会员", notes = "根据UID判断用户是否会员，响应参数[`data`:true-是,false-否]")
    @GetMapping("check/depth")
    public ResponseDto<Boolean> isMember(@NotBlank(message = "用户ID不能为空") @RequestParam String uid) {
        AdamUserMemberVo userMemberInfo = adamRdmService.getUserMemberVoByUid(uid);
        return ResponseDto.success(null != userMemberInfo && userMemberInfo.isActive());
    }

    @ApiOperationSupport(order = 98)
    @ApiOperation(value = "不推荐使用@API:是否会员[新老]", notes = "不推荐使用，建议使用`rsc/inquire/member`")
    @GetMapping("check/depth/new")
    public ResponseDto<AdamUserMemberVo> isMemberNew(@NotBlank(message = "用户ID不能为空") @RequestParam String uid) {
        AdamUserMemberVo userMemberInfo = adamRdmService.getUserMemberVoByUid(uid);
        return ResponseDto.success(userMemberInfo);
    }
}
