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

import cn.hutool.core.codec.Base64Decoder;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EShareType;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.sign.Base64Util;
import com.hzs.common.core.utils.uuid.IdUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.MemberShare;
import com.hzs.member.sms.service.IApiAliSmsService;
import com.hzs.member.share.param.ShareRegisterParam;
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.Map;
import java.util.concurrent.TimeUnit;

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

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private IApiAliSmsService iApiAliSmsService;

    @Autowired
    private RedisService redisService;

    @DubboReference
    IShareServiceApi iShareServiceApi;

    /**
     * 获取分享码
     *
     * @return
     */
    @GetMapping("/share-code")
    public AjaxResult shareCode() {
        Long userId = SecurityUtils.getUserId();
        // 分享专区分享人就是自己
        R<String> resultR = iShareServiceApi.queryShareCode(ShareServiceDTO.builder()
                .eShareType(EShareType.SHARE)
                .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();
    }

    /**
     * 分享查询推荐人编号 -- 不需要登录
     *
     * @param parentCode 推荐人（加密）
     * @return
     */
    @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 phone      手机号码
     * @param parentCode 推荐人编号
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/share-sms-code")
    public AjaxResult shareSmsCode(@RequestParam String phone,
                                   @RequestParam String parentCode) {
        if (StringUtils.isEmpty(phone)) {
            return AjaxResult.error("请输入联系方式");
        }

        // 校验注册关系（是否跨团队） -- 2024.12.24 修改为校验手机号必须唯一（9035）
        String relationStr = iCuMemberService.checkRegisterRelation(phone, Long.parseLong(new String(Base64Decoder.decode(parentCode))));
        if (relationStr != null) {
            return AjaxResult.error(relationStr);
        }
        return toAjax(iApiAliSmsService.sendRegisterCode(phone));
    }

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

        // 推荐人
        Long pkParent = Long.parseLong(new String(Base64Decoder.decode(registerParam.getParentCode())));

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

        // 校验短信验证码是否有效
        String checkSmsStr = iApiAliSmsService.checkRegisterCode(registerParam.getPhone(), registerParam.getSmsCode());
        if (null != checkSmsStr) {
            return AjaxResult.error(checkSmsStr);
        }

        // 校验注册关系（是否跨团队） -- 2024.12.24 修改为校验手机号必须唯一（9035）
        // 2025年6月9日 - 手机号不唯一,在此不做唯一校验 - start
//        String relationStr = iCuMemberService.checkRegisterRelation(registerParam.getPhone(), parentMember);
//        if (relationStr != null) {
//            return AjaxResult.error(relationStr);
//        }
        // 2025年6月9日 - 手机号不唯一,在此不做唯一校验 - start

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

            MemberShare memberShare = MemberShare.builder()
                    .memberCode(newCuMember.getMemberCode())
                    .memberName(newCuMember.getMemberName())
                    .phone(newCuMember.getPhone())
                    .loginPassword(newCuMember.getLoginPassword())
                    .payPassword(newCuMember.getPayPassword())
//                    .urlAddress(HzsConfig.getPc())
//                    .gzh(HzsConfig.getGzh())
//                    .ios(HzsConfig.getIos())
//                    .android(HzsConfig.getAndroid())
                    .uuid(uuid)
                    .build();
            return AjaxResult.success(memberShare);
        } else {
            return AjaxResult.error("注册失败，请稍候再试");
        }
    }


}
