package com.cool.bang.modules.system.controller;

import com.cool.bang.common.constant.enums.StatusType;
import com.cool.bang.core.annotation.Log;
import com.cool.bang.common.base.BaseController;
import com.cool.bang.common.constant.ControllerConstant;
import com.cool.bang.common.constant.enums.OperationType;
import com.cool.bang.common.web.request.PageDomain;
import com.cool.bang.common.web.response.Result;
import com.cool.bang.common.web.response.module.ResultTable;
import com.cool.bang.modules.system.domain.po.Menu;
import com.cool.bang.modules.system.domain.po.User;
import com.cool.bang.modules.system.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

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

/**
 * system user controller
 *
 * @author PeiZhi Guo
 * 2021-2-8 14:58
 */
@RestController
@RequestMapping(ControllerConstant.SYSTEM + "user/v1")
public class UserController extends BaseController {

    private PasswordEncoder passwordEncoder;

    private IUserService userService;

    @Autowired
    public UserController (IUserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping
    @PreAuthorize("hasPermission('', 'sys:user:main')")
    public ResultTable main(PageDomain pageDomain, User param) {
        param.setDelFlag(true);
        PageInfo<User> userPage = userService.page(pageDomain, param);
        return pageTable(userPage.getList(), userPage.getTotal());
    }

    @GetMapping("{id}")
    @PreAuthorize("hasPermission('','sys:user:main')")
    public Result get(@PathVariable Long id) {
        return success(userService.queryById(id));
    }

    @GetMapping("getUserMenu")
    public List<Menu> getUserMenu() {
        User user = getCurrentUser();
        return userService.toUserMenu(user.getMenuList(), 0L);
    }

    @GetMapping("userInfo")
    public Result userInfo() {
        User user = getCurrentUser();
        return success(user);
    }

    @PostMapping
    @PreAuthorize("hasPermission('','sys:user:add')")
    @Log(operationType = OperationType.INSERT, title = "用户管理")
    public Result save(@RequestBody User user) {
        User isUser = userService.queryByUsername(user.getUsername());
        if (isUser != null) {
            return failure("该账号已被使用");
        }
        user.setLock(StatusType.ENABLE.ordinal());
        user.setLastLoginTime(new Date());
        user.setLoginFailureNum(0);
        return decide(userService.save(user));
    }

    @PutMapping
    @PreAuthorize("hasPermission('','sys:user:edit')")
    @Log(operationType = OperationType.UPDATE , title = "用户管理")
    public Result edit(@RequestBody User user) {
        if (StringUtils.isBlank(user.getUsername())) {
            return failure("账号名不能为空");
        }
        if (userService.usernameUniqueCheck(user.getUsername(), user.getId())) {
            return failure("该账号已被使用");
        }
        return decide(userService.update(user));
    }

    //查询用户列表使用范围（流程选择用户时 回显所有用户列表 别删）
    @GetMapping("userList")
    public Result userList() {
        User param = new User();
        param.setDelFlag(true);
        return success(userService.list(param));
    }

    @DeleteMapping("{id}")
    @PreAuthorize("hasPermission('','sys:user:del')")
    @Log(operationType = OperationType.DELETE , title = "用户管理")
    public Result remove(@PathVariable Long id) {
        if (id.equals(1L)) {
            return failure("管理员无法删除。");
        }
        return decide(userService.removeById(id));
    }

    @PutMapping("switch")
    @PreAuthorize("hasPermission('','sys:user:switch')")
    @Log(operationType = OperationType.OTHER, title = "禁用|启用")
    public Result isEnable(Long id, boolean enable) {
        return decide(userService.updateEnable(id, enable));
    }

    @PutMapping("changePassword")
    @Log(operationType = OperationType.OTHER, title = "修改密码")
    public Result changePassword(String oldPwd, String newPwd, String confirmPwd) {
        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd) || StringUtils.isBlank(confirmPwd)) {
            return failure("密码不能为空");
        }
        if (!confirmPwd.equals(newPwd)) {
            return failure("两次密码不一致");
        }
        User user = getCurrentUser();
        if (!passwordEncoder.matches(oldPwd, user.getPassword())) {
            return failure("旧密码错误");
        }
        user.setPassword(passwordEncoder.encode(newPwd));
        return decide(userService.update(user));
    }
}
