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.context.annotation.Lazy;
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;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@ApiSupport(order = 10030)
@Api(tags = "会员信息")
@Slf4j
@Validated
@RestController
@RequestMapping("member")
public class AdamMemberController {
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    AdamRdmService adamRdmService;
    @Autowired
    IAdamUserMemberService adamUserMemberService;
    @Autowired
    @Lazy
    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());

            String currentUid = CurrentUtil.getCurrentUid();
            int rightsVFlag = 0;
            if (!StringUtils.isEmpty(currentUid)) {
                AdamUserMemberVo userMemberVo = adamRdmService.getUserMemberVoByUid(currentUid);
                memberVo.setUserMemberVo(userMemberVo);
                if (null != userMemberVo && userMemberVo.isActive() && userMemberVo.isOldMember()) {
                    rightsVFlag = 1;
                }
            } else {
                memberVo.setUserMemberVo(null);
            }

            // 权益只挂在价格包下：priceVoList[].rightsVoList
            memberVo.setPriceVoList(attachRightsToPriceList(
                    adamRdmService.getMemberPriceVoByMemberId(memberVo.getMemberId()),
                    adamRdmService.getMemberRightsVoByMemberId(memberVo.getMemberId(), rightsVFlag),
                    rightsVFlag
            ));
        }
        return ResponseDto.success(memberVo);
    }

    /**
     * 将权益挂到对应价格包。
     * vFlag=0：按 memberPriceId 精确匹配；
     * vFlag=1：老会员展示用权益无价格包绑定，挂到每个价格包下。
     */
    private List<AdamMemberPriceVo> attachRightsToPriceList(List<AdamMemberPriceVo> priceVoList,
                                                            List<AdamMemberRightsVo> rightsVoList,
                                                            int rightsVFlag) {
        if (priceVoList == null || priceVoList.isEmpty()) {
            return priceVoList;
        }
        List<AdamMemberRightsVo> allRights = rightsVoList == null ? Collections.emptyList() : rightsVoList;
        for (AdamMemberPriceVo priceVo : priceVoList) {
            if (rightsVFlag == 1) {
                priceVo.setRightsVoList(allRights);
                continue;
            }
            String priceId = priceVo.getMemberPriceId();
            if (StringUtils.isEmpty(priceId)) {
                priceVo.setRightsVoList(Collections.emptyList());
                continue;
            }
            List<AdamMemberRightsVo> matched = new ArrayList<>();
            for (AdamMemberRightsVo rightsVo : allRights) {
                if (priceId.equals(rightsVo.getMemberPriceId())) {
                    matched.add(rightsVo);
                }
            }
            priceVo.setRightsVoList(matched);
        }
        return priceVoList;
    }

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