package com.xydl.cac.controller;

import com.xydl.cac.entity.Admin;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.Response;
import com.xydl.cac.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@Api(tags = {"管理员相关接口"})
@RequestMapping("user")
@Slf4j
public class UserController extends BasicController {

    @Resource
    AdminService service;

    @GetMapping("listAll")
    @ApiOperation("查询全部列表")
    public Response<List<Admin>> listAll() {
        List<Admin> result = service.listAll();
        for (Admin item : result) {
            item.setPassword("");
        }
        return Response.success(result);
    }

    @PostMapping("add")
    @ApiOperation("新增")
    public Response<Admin> add(@Validated @RequestBody Admin item) throws Exception {
        Admin result = service.add(item);
        return Response.success(result);
    }

    @PostMapping("updatePasswd")
    @ApiOperation("更新")
    public Response<String> updatePasswd(@Validated @RequestBody Admin item) throws Exception {
        if (item.getId() == null) {
            throw new BusinessException("id不能为空!");
        }
        service.updatePasswd(item);
        return Response.success("OK");
    }

    @PostMapping("delete")
    @ApiOperation("删除")
    public Response<String> delete(@Validated @NotNull(message = "id不能为空!") Integer id) throws Exception {
        if (id == null) {
            throw new BusinessException("id不能为空!");
        }
        service.delete(id);
        return Response.success("OK");
    }

    @ApiOperation(value = "旧版登录")
    @PostMapping(value = "loginold")
    public Response<Admin> loginold(String username, String password) throws Exception {
        Admin admin = service.loginold(username, password);
        admin.setPassword("");
        return Response.success(admin);
    }

    @ApiOperation(value = "登录")
    @PostMapping(value = "login")
    public Response<Admin> login(@RequestBody Admin user) throws Exception {
        Admin admin = service.login(user);
        admin.setPassword("");
        return Response.success(admin);
    }

    @ApiOperation(value = "退出")
    @PostMapping(value = "logout")
    public Response<String> logout() throws Exception {
        return Response.success("OK");
    }
}
