package com.hzs.member.login.controller;

import cn.hutool.core.codec.Base64Decoder;
import com.hzs.common.auth.LoginBody;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.SysConstants;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMemberShare;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.security.auth.AuthMemberUtil;
import com.hzs.common.security.service.MemberTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.dto.LoginMember;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.ICuMemberShareService;
import com.hzs.member.login.param.AutoLoginParam;
import com.hzs.member.login.service.IMemberLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员端 token 控制
 *
 * @author hzs
 */
@RequestMapping("/auth/api")
@RestController
public class MemberTokenController {

    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberShareService iCuMemberShareService;

    @Autowired
    private IMemberLoginService iMemberLoginService;

    /**
     * 会员登录
     *
     * @param form
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody form) {
        // 用户登录
        LoginMember loginMember = iMemberLoginService.login(form.getUsername(), form.getPassword());

        // 获取登录token
        return AjaxResult.success(memberTokenService.createToken(loginMember));
    }

    /**
     * 会员登出
     *
     * @param request
     * @return
     */
    @DeleteMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            // 删除用户缓存记录
            AuthMemberUtil.logoutByToken(token);
        }
        return AjaxResult.success();
    }

    /**
     * 自动登录 -- 生成临时用户
     *
     * @param param 入参
     * @return
     */
    @RepeatSubmitSimple
    @PostMapping("/auto-login")
    public AjaxResult autoLogin(@RequestBody AutoLoginParam param) {
        if (StringUtils.isEmpty(param.getPkParent())) {
            return AjaxResult.error("缺少注册信息！");
        }

        // 上级编码（推荐人）
        Long pkParent = Long.parseLong(new String(Base64Decoder.decode(param.getPkParent())));
        // 查询上级信息
        CuMemberExt parentCuMember = iCuMemberService.getMemberById(pkParent);
        if (null == parentCuMember) {
            return AjaxResult.error("二维码已经失效！");
        }

        // 生成的会员编号
        String memberCode = iCuMemberService.createUserNameByPremix(parentCuMember.getPkSettleCountry(), false, MagicNumberConstants.DIGIT);

        CuMemberShare cuMemberShare = new CuMemberShare();
        cuMemberShare.setMemberCode(memberCode);
        cuMemberShare.setPkParent(pkParent);
        cuMemberShare.setLoginPassword(SysConstants.LOGIN_PASSWORD);
        cuMemberShare.setLoginPwd(SecurityUtils.encryptPassword(SysConstants.LOGIN_PASSWORD));
        cuMemberShare.setPayPassword(SysConstants.PAY_PASSWORD);
        cuMemberShare.setPayPwd(SecurityUtils.encryptPassword(SysConstants.PAY_PASSWORD));
        cuMemberShare.setPkCreator(pkParent);
        cuMemberShare.setPkCountry(parentCuMember.getPkSettleCountry());
        if (iCuMemberShareService.save(cuMemberShare)) {
            // 会员登录
            LoginMember loginMember = iMemberLoginService.shareLogin(memberCode, SysConstants.LOGIN_PASSWORD);

            // 获取登录token
            return AjaxResult.success(memberTokenService.createToken(loginMember));
        }
        return AjaxResult.error();
    }

}
