package com.zksy.web.controller.system;

import com.zksy.common.PinYinUtils;
import com.zksy.common.annotation.Log;
import com.zksy.common.constant.UserConstants;
import com.zksy.common.core.controller.BaseController;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.core.domain.entity.SysRole;
import com.zksy.common.core.domain.entity.SysUser;
import com.zksy.common.core.page.TableDataInfo;
import com.zksy.common.enums.BusinessType;
import com.zksy.common.utils.DateUtils;
import com.zksy.common.utils.SecurityUtils;
import com.zksy.common.utils.StringUtils;
import com.zksy.common.utils.poi.ExcelUtil;
import com.zksy.common.utils.result.Response;
import com.zksy.system.model.request.*;
import com.zksy.system.model.respone.OrgAccPageVo;
import com.zksy.system.model.respone.SysUserRes;
import com.zksy.system.service.ISysPostService;
import com.zksy.system.service.ISysRoleService;
import com.zksy.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "用户信息", description = "用户信息desc")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @ApiOperation(value = "获取用户列表")
    public TableDataInfo list(SysUserListReq user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    //@PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/searchSysUserList")
    @ApiOperation(value = "通过机构ID获取用户列表")
    public Response<SysUserRes> searchSysUserList(@RequestBody SearchSysUserReq req) {
        Response<SysUserRes> response = userService.searchSysUserList(req);
        return response;
    }

    private String getPwd4UserName(SysUser user) {
        Date date = new Date();
        String name = PinYinUtils.getAllFirstLetter(user.getNickName());
        String pwd = "@" + DateUtils.parseDateToStr(DateUtils.YYYYMMDD, date) + name;
        return pwd;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    @ApiOperation(value = "用户数据导出")
    public void export(HttpServletResponse response, SysUserListReq user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    @ApiOperation(value = "用户数据导入")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    @ApiOperation(value = "用户数据导入模板")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation(value = "根据用户编号获取详细信息")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        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 (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById4New(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            if (!ObjectUtils.isEmpty(sysUser.getRoles())) {
                ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
            } else {
                ajax.put("roleIds", new ArrayList<>());
            }
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addMember")
    @ApiOperation(value = "用户新增")
    public AjaxResult addMember(@Validated @RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && 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.setCreateTime(new Date());
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation(value = "修改用户")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && 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.setUpdateTime(new Date());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

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

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "重置密码（有权限控制）")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }


    /**
     * 重置密码
     */
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "重置密码")
    @PostMapping("/resetPwd4New")
    public Response resetPwd4New(@RequestBody SysUser user) {
        return userService.resetPwd4New(user);
    }

    /**
     * 重置为初始密码
     */
    @Log(title = "重置为初始密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "重置为初始密码")
    @PostMapping("/unionsReset")
    public Response unionsReset(@RequestBody UnionsResetReq req) {
        return userService.unionsReset(req);
    }


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

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    @ApiOperation(value = "根据用户编号获取授权角色")
    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;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @ApiOperation(value = "用户授权角色")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 用户批量删除
     */
    @Log(title = "用户批量删除", businessType = BusinessType.GRANT)
    @ApiOperation(value = "用户批量删除")
    @PostMapping("/batchDelUser")
    public Response batchDelUser(@RequestBody List<Long> ids) {
        userService.batchDelUser(ids);
        return Response.success();
    }

    @ApiOperation(value = "启用、停用", notes = "启用、停用")
    @RequestMapping(path = "/enableOrDeactivate", method = RequestMethod.GET)
    @Log(title = "启用、停用", businessType = BusinessType.UPDATE)
    public Response enableOrDeactivate(@ApiParam(value = "账号id", required = true)
                                       @RequestParam(value = "userId", required = true) Long userId,
                                       @ApiParam(value = "0正常，1停用", required = true)
                                       @RequestParam(value = "userId", required = true) Integer type) {

        return userService.enableOrDeactivate(userId, type);
    }


    @ApiOperation(value = "删除干部", notes = "删除干部")
    @RequestMapping(path = "/delcadre", method = RequestMethod.GET)
    @Log(title = "删除干部", businessType = BusinessType.DELETE)
    public Response delcadre(@ApiParam(value = "干部id", required = true)
                             @RequestParam(value = "userId", required = true) Long userId) {

        return userService.delcadre(userId);
    }

    @ApiOperation(value = "创建或修改组织账号", notes = "创建或修改组织账号")
    @RequestMapping(path = "/addOrUpdateNumber", method = RequestMethod.POST)
    @Log(title = "创建或修改组织账号", businessType = BusinessType.UPDATE)
    public Response addOrUpdateNumber(@Validated @RequestBody AddOrUpdateNumberReq req) {

        return userService.addOrUpdateNumber(req);
    }

    @ApiOperation(value = "组织账号列表", notes = "组织账号列表")
    @RequestMapping(path = "/orgAccList", method = RequestMethod.POST)
    public Response<OrgAccPageVo> orgAccList(@Validated @RequestBody OrgAccReq req) {
        return userService.orgAccList(req);
    }
}
