package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.PoUser;
import com.ruoyi.system.service.IPoUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 被分配用户Controller
 *
 * @author ruoyi
 * @date 2023-01-17
 */
@RestController
@RequestMapping("/system/users")
public class PoUserController extends BaseController
{
    @Autowired
    private IPoUserService poUserService;

    /**
     * 查询用户列表
     */
    @ApiOperation("查询用户列表")
    @PreAuthorize("@ss.hasPermi('system:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(PoUser poUser)
    {
        startPage();
        List<PoUser> list = poUserService.selectPoUserList(poUser);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @ApiOperation("导出用户列表")
    @PreAuthorize("@ss.hasPermi('system:users:export')")
    @Log(title = "被分配权限的用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PoUser poUser)
    {
        List<PoUser> list = poUserService.selectPoUserList(poUser);
        ExcelUtil<PoUser> util = new ExcelUtil<PoUser>(PoUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:users:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        poUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            PoUser poUser = poUserService.selectPoUserByUserId(userId);
            ajax.put(AjaxResult.DATA_TAG, poUser);
        }
        return ajax;
    }

    /**
     * 新增分配权限用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:users:add')")
    @Log(title = "获得权限用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated  @RequestBody PoUser poUser)
    {
        if(UserConstants.NOT_UNIQUE.equals(poUserService.checkUserNameUnique(poUser))){
            return error("新增用户"+poUser.getUserName()+"失败,用户账号已经存在");
        } else if (StringUtils.isNotEmpty(poUser.getPhonenumber())&& UserConstants.NOT_UNIQUE.equals(poUserService.checkPhoneUnique(poUser))) {
            return error("新增用户"+poUser.getPhonenumber()+"失败,用户手机号已经存在");
        }else if(StringUtils.isNotEmpty(poUser.getEmail()) && UserConstants.NOT_UNIQUE.equals(poUserService.checkEmailUnique(poUser))){
            return error("新增用户"+poUser.getEmail()+"失败,用户邮箱账号已经存在");
        }
        poUser.setCreateBy(getUsername());
        poUser.setPassword(SecurityUtils.encryptPassword(poUser.getPassword()));
        return toAjax(poUserService.insertPoUser(poUser));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermi('system:users:edit')")
    @Log(title = "修改权限用户", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit( @Validated @RequestBody PoUser poUser)
    {

        poUserService.checkUserAllowed(poUser);

        poUserService.checkUserDataScope(poUser.getUserId());
        if (UserConstants.NOT_UNIQUE.equals(poUserService.checkUserNameUnique(poUser)))
        {
            return error("修改用户'" + poUser.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(poUser.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(poUserService.checkPhoneUnique(poUser)))
        {
            return error("修改用户'" + poUser.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(poUser.getEmail())
                && UserConstants.NOT_UNIQUE.equals(poUserService.checkEmailUnique(poUser)))
        {
            return error("修改用户'" + poUser.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(poUserService.updatePoUser(poUser));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('system:users:remove')")
    @Log(title = "删除权限用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }

        return toAjax(poUserService.deletePoUserByUserIds(userIds));
    }
    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('system:users:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody PoUser poUser)
    {
        //检验是否有操作权限
        poUserService.checkUserAllowed(poUser);
        //检验是否有访问数据权限
        poUserService.checkUserDataScope(poUser.getUserId());
        poUser.setPassword(SecurityUtils.encryptPassword(poUser.getPassword()));
        poUser.setUpdateBy(getUsername());
        return toAjax(poUserService.resetPwd(poUser));
    }
    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('system:users:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody PoUser poUser)
    {
        poUserService.checkUserAllowed(poUser);
        poUserService.checkUserDataScope(poUser.getUserId());
        poUser.setUpdateBy(getUsername());
        return toAjax(poUserService.updateUserStatus(poUser));
    }
}

