package com.boman.wechat.controller;

import com.boman.common.core.enums.UserStatus;
import com.boman.common.core.exception.BaseException;
import com.boman.common.security.service.TokenService;
import com.boman.domain.AppletLoginForm;
import com.boman.domain.SysUser;
import com.boman.domain.constant.Constants;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.AppletSessionDTO;
import com.boman.system.api.RemoteLogService;
import com.boman.system.api.RemoteUserService;
import com.boman.system.api.model.LoginUser;
import com.boman.wechat.utils.WxCodeSessionUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author shiqian
 * @date 2021年09月08日 17:29
 **/
@RestController
@RequestMapping("applet")
public class AppletLoginController {

    @Resource
    private WxCodeSessionUtil codeUtil;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteLogService remoteLogService;
    @Resource
    private TokenService tokenService;

    @PostMapping("/login")
    public AjaxResult getPhone(@RequestBody AppletLoginForm form) {
        AppletSessionDTO dto = codeUtil.jscode2Session(form);
        String phoneNumber = dto.getPhoneNumber();
        SysUser user = remoteUserService.getByPhone(phoneNumber);
        String userName = user.getUserName();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            remoteLogService.saveLogininfor(userName, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BaseException("对不起，您的账号：" + userName + " 已被删除");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            remoteLogService.saveLogininfor(userName, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + userName + " 已停用");
        }

        remoteLogService.saveLogininfor(userName, Constants.LOGIN_SUCCESS, "登录成功");
        LoginUser loginUser = remoteUserService.packInfo(user);
        Map<String, Object> map = tokenService.createToken(loginUser);
        return AjaxResult.success(map);
    }

}
