package com.imdroid.beidou.controller;

import com.imdroid.beidou.auth.SessionUtils;
import com.imdroid.beidou.common.HttpResult;
import com.imdroid.beidou.data.WxMiniUserSession;
import com.imdroid.beidou.data.vo.MiniUserRegisterVO;
import com.imdroid.beidou.data.vo.MiniUserVO;
import com.imdroid.beidou.data.vo.UserLoginVO;
import com.imdroid.beidou.entity.Tenant;
import com.imdroid.beidou.entity.TenantMapper;
import com.imdroid.beidou.entity.User;
import com.imdroid.beidou.entity.UserMapper;
import com.imdroid.beidou.utils.BCryptPasswordEncoderUtil;
import com.imdroid.beidou.utils.WXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述
 *
 * @author LiGang
 */
@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private WXUtils wxUtils;

    @Autowired
    private BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    @PostMapping(value = "/do_login")
    @ResponseBody
    public HttpResult login(UserLoginVO userLoginVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (UserLoginVO.LOGIN_TYPE_MINI.equals(userLoginVO.getType())) {
            // 小程序登录
            WxMiniUserSession wxMiniUserSession = wxUtils.getMiniProgramUserOpenid(userLoginVO.getCode());
            if (wxMiniUserSession == null) {
                return HttpResult.fail("用户code错误");
            }
            User user = userMapper.queryByOpenid(wxMiniUserSession.getOpenid());
            if (user == null) {
                return HttpResult.fail(HttpResult.HTTP_RSP_USER_NOT_EXIST, "用户不存在");
            }
            Tenant tenant = tenantMapper.selectById(user.getTenantid());
            SessionUtils.setCurrentUser(request, user, tenant);

            return HttpResult.success(buildMiniUser(user, tenant));
        } else {
            // web登录
            User user = userMapper.queryByName(userLoginVO.getUsername());
            if (user == null) {
                return HttpResult.fail("用户不存在");
            }
            if (!bCryptPasswordEncoderUtil.matches(userLoginVO.getPassword(), user.getPassword())) {
                return HttpResult.fail("用户名或密码错误");
            }
            Tenant tenant = tenantMapper.selectById(user.getTenantid());
            SessionUtils.setCurrentUser(request, user, tenant);
            //response.sendRedirect("/index"); //发这条没用，会导致login.html收不到应答，也跳转不了
            return HttpResult.success(null);
        }
    }

    private MiniUserVO buildMiniUser(User user, Tenant tenant) {
        MiniUserVO miniUserVO = new MiniUserVO();
        miniUserVO.setUsername(user.getUsername());
        miniUserVO.setMobile(user.getMobile());
        miniUserVO.setNickName(user.getNickname());
        miniUserVO.setAvatarUrl(user.getAvatar_url());
        miniUserVO.setTenantName(tenant.getName());
        return miniUserVO;
    }

    /**
     * 小程序用户注册
     *
     * @param miniUserRegisterVO miniUserRegisterVO
     * @return HttpResult
     */
    @PostMapping(value = "/mini-register")
    public HttpResult miniUserRegister(@Validated MiniUserRegisterVO miniUserRegisterVO) {
        WxMiniUserSession wxMiniUserSession = wxUtils.getMiniProgramUserOpenid(miniUserRegisterVO.getCode());
        if (wxMiniUserSession == null) {
            return HttpResult.fail("用户code错误");
        }
        User user = userMapper.queryByOpenid(wxMiniUserSession.getOpenid());
        if (user != null) {
            return HttpResult.fail("用户已注册");
        }
        user = userMapper.queryByMobile(miniUserRegisterVO.getMobile());
        if (user == null) {
            return HttpResult.fail(HttpResult.HTTP_RSP_USER_NOT_EXIST, "用户不存在");
        }
        // 更新用户信息
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setAvatar_url(miniUserRegisterVO.getAvatarUrl());
        newUser.setOpenid(wxMiniUserSession.getOpenid());
        newUser.setNickname(miniUserRegisterVO.getNickName());
        userMapper.updateById(newUser);

        return HttpResult.success(null);
    }

    @RequestMapping(value = "/do_logout")
    public String logout(HttpServletRequest request) throws IOException {
        request.getSession().invalidate();
        return "/login";
    }
}
