package io.hmit.controller;


import io.hmit.annotation.Login;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.common.utils.Result;
import io.hmit.common.validator.ValidatorUtils;
import io.hmit.dto.LoginDTO;
import io.hmit.dto.UserInfoDTO;
import io.hmit.entity.UserEntity;
import io.hmit.service.TokenService;
import io.hmit.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 登录接口
 *
 * @author zsh 408538940@qq.com
 */

@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
public class ApiLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("login")
    @ApiOperation("登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {

        //表单校验
        ValidatorUtils.validateEntity(dto);

        //用户登录
        Map<String, Object> map = userService.login(dto);

        return new Result().ok(map);
    }

    @GetMapping("login")
    @ApiOperation("登录")
    public Result<Map<String, Object>> login(@RequestParam("openid") String openid) {

        log.info("【微信网页授权】openId={}", openid);
        //用户登录
        Map<String, Object> map = userService.login(openid);

        return new Result().ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@ApiIgnore @RequestAttribute("userId") Long userId) {

        tokenService.expireToken(userId);
        return new Result();
    }

    @Login
    @GetMapping("getUserInfoById")
    @ApiOperation("根据ID查询用户信息")
    @ApiImplicitParam(name = "roleId", value = "用户角色", paramType = "query", dataType = "int")
    public Result<UserInfoDTO> getUserInfoById(Long userId) {

        UserInfoDTO data = ConvertUtils.sourceToTarget(userService.getUserByUserId(userId),UserInfoDTO.class);
        return new Result().ok(data);
    }

    @Login
    @PostMapping("update")
    @ApiOperation("修改用户信息")
    public Result getUserInfoById(@RequestBody UserInfoDTO userInfoDTO) {

        UserEntity userEntity = ConvertUtils.sourceToTarget(userInfoDTO,UserEntity.class);
        userService.updateById(userEntity);

        return new Result();
    }


}
