package com.dgtly.api.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dgtly.apiframework.util.TokenUtil;
import com.dgtly.common.annotation.ApiNoCheckSign;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ResultType;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ISysUserService;
import io.swagger.annotations.Api;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/login")
    @ResponseBody
    @ApiPassToken
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        SysUser resultUser = null;
        SysUser user = new SysUser();
        user.setLoginName(username);
        user.setPhonenumber(username);
        List<SysUser> users = sysUserService.selectUserByLoginNameOrPhone(username);
        for (SysUser u : users) {
            if(u.getPassword().equals(EncryptPassWordClass.encryptPassword(u.getLoginName(), password, u.getSalt()))){
                resultUser = u;
            }
        }
        if(resultUser!=null){
            Date start = new Date();
            long currentTime = System.currentTimeMillis() + 12*60* 60 * 1000;//12小时有效时间
            Date end = new Date(currentTime);
            String token = "";

            token = JWT.create().withAudience(resultUser.getUserId().toString())
                    .withIssuedAt(start)
                    .withExpiresAt(end)
                    .sign(Algorithm.HMAC256(resultUser.getPassword()));
            return success().putKV("token",token).putKV("type",resultUser.getRoleId());
        }else{
            return  new AjaxResult(300,"账号或密码错误！");
        }
    }

    @PostMapping("/getUser")
    @ResponseBody
    public AjaxResult getUser(){
        return AjaxResult.success().putKV("id",TokenUtil.getTokenUserId());
    }
}
