package com.m2pool.system.controller;

import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.constant.UserConstants;
import com.m2pool.common.core.utils.DateUtils;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.core.web.Result.AjaxResult;
import com.m2pool.common.core.web.controller.BaseController;
import com.m2pool.common.log.annotation.Log;
import com.m2pool.common.log.enums.BusinessType;
import com.m2pool.common.security.annotation.InnerAuth;
import com.m2pool.common.security.annotation.RequiresPermissions;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.system.api.entity.SysRole;
import com.m2pool.system.api.entity.SysUser;
import com.m2pool.system.api.model.LoginUser;
import com.m2pool.system.service.SysPermissionService;
import com.m2pool.system.service.SysRoleService;
import com.m2pool.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @Description TODO
 * @Date 2022/6/14 17:33
 * @Author 杜懿
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 根据用户名获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{account}")
    @ApiOperation(value = "",response = List.class)
    public R<LoginUser> info(@PathVariable("account") String account)
    {
        String em = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

        System.out.println(account);


        SysUser user = userService.selectUserByEmail(account);

        if (StringUtils.isNull(user))
        {
            return R.fail("邮箱未被注册");
        }

        List<Long> roleIdList = roleService.selectRoleListByUserId(user.getUserId());
        Long[] roleIds = roleIdList.toArray(new Long[roleIdList.size()]);
        user.setRoleIds(roleIds);
        //if(roleIds.length > 0){
        //    user.setRoleId(roleIds[0]);
        //}


        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUserid(user.getUserId());
        sysUserVo.setUsername(user.getUserName());
        sysUserVo.setIpaddr(user.getLoginIp());
        sysUserVo.setSysUser(user);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.success(sysUserVo);
    }


    /**
     * 注册用户信息
     */
    //@InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        String username = sysUser.getUserName();
        String email = sysUser.getEmail();
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username)))
        {
            return R.fail("用户'" + username + "'注册失败，注册账号已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser)))
        {
            return R.fail("用户'" + username + "'注册失败，邮箱"+email+"已被其他用户注册");
        }

        return R.success(userService.registerUser(sysUser));
    }

    /**
     * 修改用户登录次数和最后一次登录的ip
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody SysUser user)
    {
        //user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        List<Long> roleIdList = roleService.selectRoleListByUserId(user.getUserId());
        Long[] roleIds = roleIdList.toArray(new Long[roleIdList.size()]);
        user.setRoleIds(roleIds);
        return toAjax(userService.updateUser(user));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @GetMapping("/checkMail/{email}")
    public AjaxResult checkMail(@PathVariable("email") String email)
    {

        String em = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if(!email.matches(em)){
            return AjaxResult.error(300,"邮箱格式错误");
        }


        if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailExist(email)))
        {
            return AjaxResult.error(301,"邮箱已被注册");
        }
        return AjaxResult.success("邮箱未被注册");
    }

    @GetMapping("/getCSList")
    public R<List<SysUser>> getCSList()
    {
        List<SysUser> list = userService.getCSList();
        if(StringUtils.isNull(list)){
            return R.fail("未能获取到客服列表");
        }
        return R.success(list);
    }
}
