package com.hzs.member.share.controller.api;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.config.BdConfig;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.sign.Base64Util;
import com.hzs.common.core.utils.uuid.IdUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.MemberShare;
import com.hzs.member.share.param.ShareRegisterParam;
import com.hzs.system.base.ISystemConfigServiceApi;
import com.hzs.third.share.IShareServiceApi;
import com.hzs.third.share.dto.ShareServiceDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 会员分享相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/share")
public class ApiShareController {

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private RedisService redisService;

    @DubboReference
    IShareServiceApi iShareServiceApi;
    @DubboReference
    ISystemConfigServiceApi iSystemConfigServiceApi;


    /**
     * 获取188分享码（H5）
     */
    @GetMapping("/fans-code-h5")
    public AjaxResult fansCodeH5() {
        Long userId = SecurityUtils.getUserId();

        // 0元会员不涌进行分享
        CuMemberExt cuMemberExt = iCuMemberService.getMemberById(userId);
        if (null == cuMemberExt.getPkPlaceParent()) {
            return AjaxResult.error("当前会员无权进行个人推广");
        }

        // 188注册分享人就是自己
        R<String> resultR = iShareServiceApi.queryShareCode(ShareServiceDTO.builder()
                .eShareType(EShareType.FANS)
                .pkBusiness(userId)
                .pkCountry(SecurityUtils.getPkCountry())
                .userId(userId)
                .build());
        if (resultR.isSuccess()) {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("dataUrl", resultR.getData());
            // 前端无法根据URL生成海报，此处需要转一下base64
            resultMap.put("dataStr", Base64Util.toUrlBase64(resultR.getData()));
            return AjaxResult.success(resultMap);
        }
        return AjaxResult.error();
    }


    ////////////////////////////// 0元注册 //////////////////////////////


    /**
     * 分享查询推荐人编号 -- 不需要登录
     *
     * @param parentCode 推荐人（加密）
     */
    @GetMapping("/find-share-code/{parentCode}")
    public AjaxResult findShareCode(@PathVariable("parentCode") String parentCode) {
        CuMember cuMember = iCuMemberService.getMemberById(Long.parseLong(new String(Base64Decoder.decode(parentCode))));
        if (null != cuMember) {
            return AjaxResult.success("", cuMember.getMemberCode());
        }
        return AjaxResult.error();
    }

    /**
     * 分享注册 -- 不需要登录
     *
     * @param registerParam 分享注册入参
     */
    @RepeatSubmitSimple
    @PostMapping("/share-register")
    public AjaxResult shareRegister(@Valid @RequestBody ShareRegisterParam registerParam,
                                    @RequestHeader("Source") Integer source) {
        // 设置数据来源
        registerParam.setSource(source);

        // 验证推荐人
        CuMember parentMember = iCuMemberService.getMember(registerParam.getParentCode());
        if (null == parentMember) {
            return AjaxResult.error("推荐编号不存在");
        }
        registerParam.setParentMember(parentMember);

        String value = iSystemConfigServiceApi.getBonusSystemConfig(CountryConstants.CHINA_COUNTRY, ESystemConfig.REGISTER_NUMBER.getKey()).getData();
        List<CuMember> memberList = iCuMemberService.list(Wrappers.<CuMember>lambdaQuery()
                .eq(CuMember::getPhone, registerParam.getPhone())
                .eq(CuMember::getDelFlag, EDelFlag.UN_DELETE.getValue())
                .eq(CuMember::getCategory, ECategory.NORMAL.getValue())
        );
        // 手机号注册次数
        if (memberList.size() >= Integer.parseInt(value)) {
            return AjaxResult.error(MemberMsgConstants.SYSTEM_REGISTER_COUNT);
        }
        // 一个手机号只能有一个姓名
        if (!memberList.stream().allMatch(cuMember -> registerParam.getMemberName().equals(cuMember.getMemberName()))) {
            return AjaxResult.error(MemberMsgConstants.PHONE_ALREADY_REGISTER);
        }


        CuMember newCuMember = iCuMemberService.shareRegisterMember(registerParam);
        if (null != newCuMember) {
            // 自动登录 uuid 标记
            String uuid = IdUtils.simpleUUID();
            // 根据会员编号放一个登录 uuid 做为自动登录校验使用（60分钟有效）
            redisService.setCacheObject(CacheConstants.AUTO_LOGIN + newCuMember.getMemberCode(), uuid, CacheConstants.LOGIN_TOKEN_REFRESH_TIME, TimeUnit.MINUTES);

            MemberShare memberShare = MemberShare.builder()
                    .memberCode(newCuMember.getMemberCode())
                    .memberName(newCuMember.getMemberName())
                    .phone(newCuMember.getPhone())
                    .loginPassword(newCuMember.getLoginPassword())
                    .payPassword(newCuMember.getPayPassword())
                    .urlAddress(BdConfig.getPc())
                    .uuid(uuid)
                    .build();
            return AjaxResult.success(memberShare);
        } else {
            return AjaxResult.error("注册失败，请重试");
        }
    }


}
