package com.changfa.controller;

import com.alibaba.fastjson.JSONObject;
import com.changfa.base.BaseController;
import com.changfa.config.shiro.CustomRealm;
import com.changfa.constants.ApiResult;
import com.changfa.enums.StatusEnum;
import com.changfa.dto.MenuDto;
import com.changfa.dto.UserBaseDto;
import com.changfa.dto.UserDto;
import com.changfa.exception.BuzEx;
import com.changfa.service.ITMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wwz
 * @since 2022-06-24
 */
@RestController
@Api(tags = "用户登录Api")
@RequestMapping(value = "/user",method = RequestMethod.POST)
public class UserController extends BaseController {

    @Autowired
    private ITMenuService menuService;
    @Autowired
    private CustomRealm customRealm;

    @ApiOperation("登录")
    @RequestMapping("/login")
    public ApiResult login(@Valid @RequestBody  UserDto userDto, @ApiIgnore Errors errors){
        try{
            if(errors.hasErrors()){
                return ApiResult.error(errors.getFieldError().getDefaultMessage());
            }
            Subject subject =  SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(userDto.getAccount(),userDto.getPassword()));
            if(subject.isAuthenticated()){
                subject.getSession().setAttribute("account",userDto.getAccount());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token",subject.getSession().getId());
                UserBaseDto userBaseDto = userBaseInfo();
                if(userBaseDto.getRole() != null){
                    List<MenuDto> menuList = menuService.selectMenuListByRoleId(userBaseDto.getRole().getId());
                    if(!ObjectUtils.isEmpty(menuList)){
                        userBaseDto.setMenuList(customRealm.recursionForMenu(-1,menuList));
                    }
                }
                jsonObject.put("userBase",userBaseDto);
                return ApiResult.success(jsonObject);
            }
        }catch (BuzEx buzEx){
            return ApiResult.error(buzEx.getStatusEnum());
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ApiResult.error(StatusEnum.USER_OR_PASSWORD_ERROR);

    }


    @ApiOperation("退出登录")
    @RequestMapping("/logout")
    public ApiResult logout(){
        try{
            Subject subject =  SecurityUtils.getSubject();
            if(subject.isAuthenticated()){
                subject.logout();
                return ApiResult.success();
            }
        }catch (Exception e){

        }
        return ApiResult.error(StatusEnum.FAIL);
    }
}
