package im.zksy.yjmqserver.system.controller;

import com.github.pagehelper.PageInfo;
import im.zksy.yjmqserver.common.util.PageResultBean;
import im.zksy.yjmqserver.common.util.ResultBean;
import im.zksy.yjmqserver.common.validate.groups.Create;
import im.zksy.yjmqserver.system.model.User;
import im.zksy.yjmqserver.system.service.RoleService;
import im.zksy.yjmqserver.system.service.UserService;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {


    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @GetMapping("/index")
    public String index() {
        return "user/user-list";
    }

    @GetMapping("/send")
    public String send() {
        return "user/user-send";
    }

    @GetMapping("/list")
    @ResponseBody
    public PageResultBean<User> getList(@RequestParam(value = "page", defaultValue = "1") int page,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                        User userQuery) {
        try {
            List<User> users = userService.selectAllWithDept(page, pageSize, userQuery);
            PageInfo<User> userPageInfo = new PageInfo<>(users);
            return new PageResultBean<>(userPageInfo.getTotal(), userPageInfo.getList());
        }catch (Exception ex){
            return  null;

        }
    }

    @GetMapping("/list/userByDeptId")
    @ResponseBody
    public PageResultBean<User> getList(@RequestParam(value = "page", defaultValue = "1") int page,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                        @RequestParam(value = "deptId") String deptId,
                                        @RequestParam(value = "userName") String userName) {
        List<User> users = userService.selectAllWithDeptId(page, pageSize,Integer.parseInt(deptId),userName);
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        return new PageResultBean<>(userPageInfo.getTotal(), userPageInfo.getList());

    }



    @GetMapping
    public String add(Model model) {
        model.addAttribute("roles", roleService.selectAll());
        return "user/user-add";
    }

    @GetMapping("/{userId}")
    public String update(@PathVariable("userId") Integer userId, Model model) {
        model.addAttribute("roleIds", userService.selectRoleIdsById(userId));
        model.addAttribute("user", userService.selectOne(userId));
        model.addAttribute("roles", roleService.selectAll());
        return "user/user-add";
    }

    @PutMapping
    @ResponseBody
    public ResultBean putupdate(@Valid User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) {
        userService.update(user, roleIds);
        return ResultBean.success();
    }


    @PostMapping("/edit")
    @ResponseBody
    public ResultBean update(@Valid User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) {
        user.setModifyTime(sdf.format(new Date()));
        userService.update(user, roleIds);
        return ResultBean.success();
    }

    @PostMapping
    @ResponseBody
    public ResultBean adduser(@Validated(Create.class) User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) {
        user.setCreateTime(sdf.format(new Date()));
        user.setModifyTime(user.getCreateTime());
        return ResultBean.success(userService.add(user, roleIds));
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultBean add(@Validated(Create.class) User user, @RequestParam(value = "role[]", required = false) Integer[] roleIds) {
        user.setCreateTime(sdf.format(new Date()));
        user.setModifyTime(user.getCreateTime());
        return ResultBean.success(userService.add(user, roleIds));
    }

    /***
     * 禁用账号
     * @param userId
     * @return
     */
    @PostMapping("/{userId:\\d+}/disable")
    @ResponseBody
    public ResultBean disable(@PathVariable("userId") Integer userId) {
        return ResultBean.success(userService.disableUserByID(userId));
    }

    /**
     * 激活账号
     * @param userId
     * @return
     */
    @PostMapping("/{userId}/enable")
    @ResponseBody
    public ResultBean enable(@PathVariable("userId") Integer userId) {
        return ResultBean.success(userService.enableUserByID(userId));
    }

    @DeleteMapping("/{userId}")
    @ResponseBody
    public ResultBean delete(@PathVariable("userId") Integer userId) {
        userService.delete(userId);
        return ResultBean.success();
    }

    @GetMapping("/{userId}/reset")
    public String resetPassword(@PathVariable("userId") Integer userId, Model model) {
        model.addAttribute("userId", userId);
        return "user/user-reset-pwd";
    }

    /***
     * 重置密码
     * @param userId
     * @param password
     * @return
     */
    @PostMapping("/{userId}/reset")
    @ResponseBody
    public ResultBean resetPassword(@PathVariable("userId") Integer userId, String password) {
        int result=userService.updatePasswordByUserId(userId, password);
        if(result>0) {
            return ResultBean.success();
        }
        return ResultBean.error("");
    }

    /***
     * 重置密码
     * @param user
     * @param newpwd
     * @return
     */
    @PostMapping("/myreset/{newpwd}")
    @ResponseBody
    public ResultBean resetPassword(User user,  @PathVariable("newpwd") String newpwd) {
        //验证当前用户是否输入密码正确
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            subject.login(token);
           int result= userService.updatePasswordByUserId(user.getUserId(), newpwd);
            if(result>0) {
                return ResultBean.success();
            }
            return ResultBean.error("更新失败");
        }catch( AuthenticationException ex) {
            return ResultBean.error("密码错误");
        }
    }

    @GetMapping("/update/{name}/{alarmlevel}")
    public String editmodel(@PathVariable("name") String name, @PathVariable("alarmlevel") String alarmlevel,Model model) {
        model.addAttribute("manualname", name);
        model.addAttribute("manualalarmlevel", alarmlevel);
        return "user/user-addsend";
    }

}