package cn.pluss.platform.controller.home;

import cn.hutool.crypto.digest.MD5;
import cn.pluss.platform.annotation.PassToken;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.entity.UserInfo;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.ipLocation.IpLocationService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.IpUtils;
import cn.pluss.platform.util.JwtUtils;
import cn.pluss.platform.wx.WxTalkService;
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserInfoService uiService;

    @Autowired
    private WxTalkService wxTalkService;

    @Autowired
    private IpLocationService ipLocationService;

    @PassToken
    @GetMapping("/auth")
    @ResponseBody
    public Result<Object> jwtTest(HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");

        if (!Objects.equals("244", userId)) {
            // 此处不能返回401, 不然会形成死循环
            throw new MsgException("未授权");
        }

        Object tokenUserId = JwtUtils.get("uid", token);
        if (!Objects.equals(userId, tokenUserId.toString())) {
            // 此处不能返回401, 不然会形成死循环
            throw new MsgException("未授权");
        }

        try {
            boolean verify = JwtUtils.verify(token, userId);
            if (!verify) {
                // 此处不能返回401, 不然会形成死循环
                throw new MsgException("未授权");
            }

            Object expireTime = JwtUtils.get("expire_time", token);
            if (!(expireTime instanceof Long)) {
                throw new MsgException("未授权");
            }

            if (((Long) expireTime) < System.currentTimeMillis()) {
                throw new MsgException("未授权");
            }

        } catch (Exception e) {
            throw new MsgException("未授权");
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     *引导页
     */
    @PassToken
    @GetMapping
    public String index(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        switch (contextPath) {
            case "/merchant":
                return "index/loginMerchant";
            case "/service":
                return "index/loginService";
            default:
                return "index/login";
        }
    }

    @PassToken
    @PostMapping("/doLogin")
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request, @RequestParam("loginName") String username, @RequestParam("password") String password) {
        Map<String,Object> result= new HashMap<>();
		result.put("result", 2);
        UserInfo userInfo = new UserInfo();
        userInfo.setLoginName(username);
        userInfo = uiService.getOne(new QueryWrapper<>(userInfo));

        String ipAddr = IpUtils.getIpAddr(request);
        DescribeIpv4LocationResponse clientLocation = ipLocationService.getLocation(ipAddr);
        String location = clientLocation.getCountry()
                + "," + clientLocation.getProvince()
                + "," + clientLocation.getCity()
                + "," + clientLocation.getCounty();
        if (userInfo == null) {
            wxTalkService.sendManageLoginInfo(username, password, ipAddr, clientLocation.getIsp(), location, false);
            result.put("message", "用户名或者密码错误");
            return result;
        }

        if (!userInfo.getPassword().equals(MD5.create().digestHex(password, StandardCharsets.UTF_8))) {
            wxTalkService.sendManageLoginInfo(username, password, ipAddr, clientLocation.getIsp(), location, false);
            result.put("message", "用户名或者密码错误");
            return result;
        }

        result.put("result", 1);
        result.put("redirectUri", "/manage/platform/console");
        result.put("token", JwtUtils.getToken(userInfo));
        result.put("userId", userInfo.getId());

        wxTalkService.sendManageLoginInfo(username, password, ipAddr, clientLocation.getIsp(), location, true);
        return result;
    }

}
