package org.linlinjava.jz.admin.web;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.linlinjava.jz.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.jz.admin.service.LogHelper;
import org.linlinjava.jz.admin.util.SecurityHelper;
import org.linlinjava.jz.admin.vo.SysUserVo;
import org.linlinjava.jz.core.util.IpUtil;
import org.linlinjava.jz.core.util.MD5Utils;
import org.linlinjava.jz.core.util.RegexUtil;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.jz.core.validator.Order;
import org.linlinjava.jz.core.validator.Sort;
import org.linlinjava.jz.db.domain.JzRole;
import org.linlinjava.jz.db.domain.SysUser;
import org.linlinjava.jz.db.domain.SysUserOnline;
import org.linlinjava.jz.db.service.JzRoleService;
import org.linlinjava.jz.db.service.JzSysUserOnlineService;
import org.linlinjava.jz.db.service.JzSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;

import static org.linlinjava.jz.admin.util.AdminResponseCode.*;

@Api(tags = "系统管理", description = "管理用户权限")
@RestController
@RequestMapping("/admin/admin")
@Validated
public class AdminSysUserController {
    private final Log logger = LogFactory.getLog(AdminSysUserController.class);

    @Autowired
    private JzSysUserService adminService;

    @Autowired
    private LogHelper logHelper;


    @Autowired
    private JzSysUserOnlineService onlineService;

    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(required = false) String username,
                       @RequestParam(required = false) String userAccount,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "create_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<SysUser> adminList = adminService.querySelective(username, userAccount, page, limit, sort, order);


        List<SysUserVo> sysUserVos = Lists.newArrayList();
        for (SysUser user : adminList) {
            SysUserVo vo = new SysUserVo();
            vo.setAvatar(user.getAvatar());
            vo.setId(user.getId().intValue());
            vo.setUserAccount(user.getUserAccount());
            vo.setUserName(user.getUserName());
            //vo.setDepartmentName(user.getDepartment() == null ? "" : user.getDepartment().getName());
            vo.setDepartmentId(user.getDepartmentId() == null ? 0 : user.getDepartmentId());
            vo.setRoleIds(user.getRoleIds());
            vo.setExtNo(user.getExtNo());
            vo.setType(user.getType());
            sysUserVos.add(vo);
        }

        return ResponseUtil.okList(sysUserVos, adminList);
    }

    private Object validate(SysUser admin) {
        String name = admin.getUserAccount();//.getUsername();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        if (!RegexUtil.isUsername(name)) {
            return ResponseUtil.fail(ADMIN_INVALID_NAME, "管理员名称不符合规定");
        }
        String password = admin.getUserPassword();//.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "管理员密码长度不能小于6");
        }
        return null;
    }

    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody SysUser admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        String username = admin.getUserName();//.getUsername();
        List<SysUser> adminList = adminService.findAdmin(admin.getUserAccount());
        if (adminList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "管理员已经存在");
        }

        String rawPassword = admin.getUserPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = MD5Utils.stringToMD5(rawPassword);// encoder.encode(rawPassword);
        admin.setUserPassword(encodedPassword);
        adminService.add(admin);
        logHelper.logAuthSucceed("添加管理员", username);
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        SysUser admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }

    @GetMapping("/readAdmin")
    public Object read() {
        SysUser admin = adminService.findById(SecurityHelper.getAdminId());
        return ResponseUtil.ok(admin);
    }


    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody SysUser admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        Integer anotherAdminId = admin.getId().intValue();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        // 不允许管理员通过编辑接口修改密码
        admin.setUserPassword(null);//.setPassword(null);

        if (adminService.updateById(admin) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        logHelper.logAuthSucceed("编辑管理员", admin.getUserName());//.getUsername());
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody SysUser admin) {
        Integer anotherAdminId = admin.getId().intValue();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        // 管理员不能删除自身账号
        Subject currentUser = SecurityUtils.getSubject();
        SysUser currentAdmin = (SysUser) currentUser.getPrincipal();
        if (currentAdmin.getId().equals(anotherAdminId)) {
            return ResponseUtil.fail(ADMIN_DELETE_NOT_ALLOWED, "管理员不能删除自己账号");
        }

        adminService.deleteById(anotherAdminId);
        logHelper.logAuthSucceed("删除管理员", admin.getUserName());
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:admin:all")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "所有管理员")
    @GetMapping("/all")
    public Object all() {
        return ResponseUtil.ok(adminService.all());
    }

    /**
     * 在线状态
     *
     * @param request
     * @return
     */
    @GetMapping("/status")
    public Object online(HttpServletRequest request) {
        SysUser admin = (SysUser) SecurityUtils.getSubject().getPrincipal();

        SysUserOnline userOnline = new SysUserOnline();
        userOnline.setLastOnlineTime(LocalDateTime.now());
        userOnline.setLastOnlineIp(IpUtil.getIpAddr(request));
        userOnline.setUserId(admin.getId().intValue());
        onlineService.update(userOnline);

        return ResponseUtil.ok();
    }
}
