package com.dgtly.api.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dgtly.apiframework.exception.LessParamException;
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.Community;
import com.dgtly.system.domain.EntryPass;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ICommunityService;
import com.dgtly.system.service.IEntryPassService;
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.*;

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


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

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IEntryPassService entryPassService;

    @Autowired
    private ICommunityService communityService;

    @PostMapping("/login")
    @ResponseBody
    @ApiPassToken
    public AjaxResult ajaxLogin( )
    {
        Map<String,Object> paramMap =  getJsonMap();
        String username = (String)paramMap.get("loginname");
        String password = (String)paramMap.get("password");
        if(username==null||username.trim().equals("")
        ||password==null||password.trim().equals("")){
            throw  new LessParamException();
        }
        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.getRoles().get(0).getRoleId());
        }else{
            return  new AjaxResult(300,"账号或密码错误！");
        }
    }

    /**
     * 获取用户基本信息
     * @return
     */
    @PostMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult getUser(){
        Long userId = Long.parseLong(TokenUtil.getTokenUserId());
        SysUser user = sysUserService.selectUserById(userId);
        return AjaxResult.success(user);
    }

    /**
     * 获取用户基本信息
     * @return
     */
    @PostMapping("/getUserInfoByUserId")
    @ResponseBody
    @ApiPassToken
    public AjaxResult getUserInfoByUserId(){
        Map param = getJsonMap();
        if(!param.containsKey("userId")){
            throw new LessParamException();
        }
        SysUser user = sysUserService.selectUserById(Long.parseLong(param.get("userId").toString()));
        return AjaxResult.success(user);
    }

    /**
     * 查询社区列表
     */
    @PostMapping("/community/list")
    @ResponseBody
    @ApiPassToken
    public Object list()
    {
        Community community = new Community();
        List<Community> list = communityService.selectCommunityList(community);
        return AjaxResult.success().putKV("list",list);
    }

    /**
     * 获取用户基本信息
     * @return
     */
    @PostMapping("/getPassInfo")
    @ResponseBody
    @ApiPassToken
    public AjaxResult getPassInfo(){
        Map<String,Object> paramMap =  getJsonMap();
        if(!paramMap.containsKey("userId")){
            throw new LessParamException();
        }
        String userId = paramMap.get("userId").toString();
        EntryPass ep = entryPassService.selectEntryPassByUserId(Long.parseLong(userId));
        return AjaxResult.success(ep);
    }




}
