package com.patzn.lims.security.controller;

import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.common.CookieHelper;
import com.baomidou.kisso.common.IpHelper;
import com.baomidou.kisso.common.util.RandomUtil;
import com.baomidou.kisso.security.token.SSOToken;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.api.PtResult;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.web.SuperController;
import com.patzn.lims.security.payload.LoginRequest;
import com.patzn.lims.sys.entity.SysUser;
import com.patzn.lims.sys.enums.WxTypeEnum;
import com.patzn.lims.sys.service.ISysUserService;
import io.jsonwebtoken.Jwts;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/v1/auth")
public class AuthController extends SuperController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     */
    @Login(action = Action.Skip)
    @PostMapping("/login")
    public PtResult<Boolean> login(@Valid LoginRequest loginRequest) {
        SysUser sysUser = sysUserService.getByUserName(loginRequest.getUsername());
        PtAssert.fail(null == sysUser, "用户不存在");
        boolean can=  passwordEncoder.matches(loginRequest.getPassword(), sysUser.getPassword());
        PtAssert.fail(!can, "用户密码错误");
        // 授权登录
        SSOHelper.setCookie(request, response, SSOToken.create(Jwts.builder()
                .claim(LoginHelper.COMPANY_ID, sysUser.getCompanyId())
                .setId(String.valueOf(sysUser.getId()))
                .setIssuer(sysUser.getUsername()))
                .setUserAgent(request), false);
        if (log.isDebugEnabled()) {
            log.debug("用户 {} 登录成功 IP = {}", sysUser.getUsername(), IpHelper.getIpAddr(request));
        }
        // 添加一个 JS 可读标示
        SSOConfig config = SSOConfig.getInstance();
        CookieHelper.addCookie(response, config.getCookieDomain(), config.getCookiePath(),
                "ln", RandomUtil.getCharacterAndNumber(6), -1, false, false);
        return success(true);
    }

    /**
     * 退出
     */
    @Login(action = Action.Skip)
    @GetMapping("/logout")
    public PtResult<Boolean> logout() {
        try {
            SSOHelper.clearLogin(request, response);
            SSOConfig config = SSOConfig.getInstance();
            CookieHelper.clearCookieByName(request, response, "ln",
                    config.getCookieDomain(), config.getCookiePath());
        } catch (Exception e) {
            return failed(e.getMessage());
        }
        return success(true);
    }



    @Login(action = Action.Skip)
    @GetMapping("/login_home")
    public ModelAndView login(){
        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;
    }


    /**
     * JSON 序列化测试
     */
    @GetMapping("/hello")
    public PtResult testJson() {
        return success(new TestJson(1233635718841012218L, WxTypeEnum.MA));
    }



    @Data
    @AllArgsConstructor
    class TestJson {
        private Long id;
        private WxTypeEnum wxTypeEnum;
    }
}
