package com.usky.system.controller.web;


import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.system.controller.web.page.TableDataInfo;
import com.usky.system.domain.*;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.mapper.SysUserTenantMapper;
import com.usky.system.service.*;
import com.usky.system.service.vo.SysUserNewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author yq
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private SysUserTenantMapper sysUserTenantMapper;

    @Autowired
    private SysUserPersonService sysUserPersonService;

    /**
     * 获取用户列表
     */
//    @Log(title = "用户列表", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public ApiResult<TableDataInfo> list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return ApiResult.success(getDataTable(list));
    }

    /**
     * 运维管理系统-获取平台账号列表
     */
//    @Log(title = "用户列表", businessType = BusinessType.SELECT)
    @GetMapping("/platAccountlist")
    public ApiResult<TableDataInfo> platAccountlist(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.platAccountlist(user);
        return ApiResult.success(getDataTable(list));
    }

    /**
     * 新增运维管理系统-平台账号
     */
    @Log(title = "新增运维管理系统-平台账号", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/platAccountAdd")
    public ApiResult<Void> platAccountAdd(@Validated @RequestBody SysUser user)
    {
        int row = userService.insertPlatAccount(user);
        return toAjax(row);
    }

    /**
     * 修改运维管理系统-平台账号
     */
    @Log(title = "修改运维管理系统-平台账号", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping("/updatePlatAccount")
    public ApiResult<Void> updatePlatAccount(@Validated @RequestBody SysUser user)
    {
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updatePlatAccount(user));
    }

    /**
     * 获取用户列表
     */
//    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @GetMapping("/dUserList")
    public ApiResult<List<SysUserNewVO>> dUserList(SysUser user)
    {
        List<SysUserNewVO> list = userService.dUserList(user);
        return ApiResult.success(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public ApiResult<Map<String,Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        Integer tenantId = SecurityUtils.getTenantId();
        Map<String,Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (Objects.nonNull(userId))
        {
            ajax.put("data", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId, tenantId));
        }
        return ApiResult.success(ajax);
    }

    /**
     * 新增用户
     */
    @Log(title = "新增用户", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public ApiResult<Void> add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName(),0)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique1(user.getPhonenumber(),0))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique1(user.getEmail(),0))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增邮箱'" + user.getEmail() + "'失败，邮箱已存在");
        }
        user.setUserType("00");
        user.setTenantId(SecurityUtils.getTenantId());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int row = userService.insertUser(user);

        // 新增用户登录通知设置
        SysUserPerson sysUserPerson = new SysUserPerson();
        sysUserPerson.setUserId(user.getUserId());
        sysUserPerson.setIsLoginNotify(0);
        sysUserPersonService.save(sysUserPerson);

        return toAjax(row);
    }

    /**
     * 新增APP用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/appAdd")
    public ApiResult<Void> appAdd(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName(),0)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique1(user.getPhonenumber(),0))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique1(user.getEmail(),0))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增邮箱'" + user.getEmail() + "'失败，邮箱已存在");
        }
        List<SysDept> list = deptService.deptListByTenant(user.getTenantId());
        if (!list.isEmpty()){
            user.setDeptId(list.get(0).getDeptId());
        }
        user.setUserType("00");
        user.setTenantId(user.getTenantId());
        user.setCreateBy(user.getUserName());
        user.setTenantId(user.getTenantId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int row = userService.insertUser(user);
        return toAjax(row);
    }

    /**
     * 修改用户
     */
    @Log(title = "修改用户", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public ApiResult<Void> edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ApiResult<Void> remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 删除用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}/{password}")
    public ApiResult<Void> remove(@PathVariable Long userId,@PathVariable String password)
    {
        String password1 = SecurityUtils.encryptPassword(password);
        return toAjax(userService.deleteUserByPwd(userId,password1));
    }

    /**
     * 重置密码
     */
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public ApiResult<Void> resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    public ApiResult<Void> changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public ApiResult<Map<String,Object>> authRole(@PathVariable("userId") Long userId)
    {
        Map<String,Object> ajax = new HashMap<>();
        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 ApiResult.success(ajax);
    }

    /**
     * 用户授权角色
     */
    @PutMapping("/authRole")
    public ApiResult<Void> insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return ApiResult.success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/selectUserOne")
    public ApiResult selectUserOne(@RequestParam(value = "phonenumber", required = false) String phonenumber,
                                 @RequestParam(value = "userName", required = false) String userName,
                                 @RequestParam(value = "email", required = false) String email)
    {
        return ApiResult.success(userService.selectUserOne(phonenumber,userName,email));
    }
}
