package com.zhongzheng.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.zhongzheng.common.annotation.Log;
import com.zhongzheng.common.constant.Constants;
import com.zhongzheng.common.constant.UserConstants;
import com.zhongzheng.common.core.bo.SysUserEditBo;
import com.zhongzheng.common.core.controller.BaseController;
import com.zhongzheng.common.core.domain.AjaxResult;
import com.zhongzheng.common.core.domain.entity.SysRole;
import com.zhongzheng.common.core.domain.entity.SysUser;
import com.zhongzheng.common.core.domain.model.LoginUser;
import com.zhongzheng.common.core.page.TableDataInfo;
import com.zhongzheng.common.enums.BusinessType;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.exception.user.UserPasswordNotMatchException;
import com.zhongzheng.common.utils.MessageUtils;
import com.zhongzheng.common.utils.SecurityUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.common.utils.poi.ExcelUtil;
import com.zhongzheng.framework.manager.AsyncManager;
import com.zhongzheng.framework.manager.factory.AsyncFactory;
import com.zhongzheng.framework.web.service.TokenService;
import com.zhongzheng.modules.exam.domain.ExamConfig;
import com.zhongzheng.modules.system.service.ISysPostService;
import com.zhongzheng.modules.system.service.ISysRoleService;
import com.zhongzheng.modules.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

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

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

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

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {  "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        SysUser sysUser = userService.selectUserById(userId);
        ajax.put("roles", SysUser.isAdmin(sysUser.getUserName()) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (Validator.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @ApiOperationSupport(ignoreParameters = {"id","orderDate.id"})
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("更新用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUserEditBo bo)
    {
        if (bo.getStatus().equals(-1)){
            SysUser user = BeanUtil.toBean(bo, SysUser.class);
            int result = userService.updateUser(user);
            return toAjax(result);
        }
        SysUser user = BeanUtil.toBean(bo, SysUser.class);
        userService.checkUserAllowed(user);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if(!loginUser.getUser().isAdmin()&&loginUser.getUser().getUserId()!=user.getUserId()){
            return AjaxResult.error("您无权限修改本信息");
        }

        if (Validator.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if(Validator.isNotEmpty(user.getPassword())){
            //重置密码
            if(!loginUser.getUser().isAdmin()){
                //普通用户需传入旧密码修改
                // 旧密码用户验证
                Authentication authentication = null;
                try
                {
                    // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                    authentication = authenticationManager
                            .authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUser().getUserName(), bo.getOldPassword()));
                }
                catch (Exception e)
                {
                    return AjaxResult.error("旧密码错误");
                }

            }
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        int result = userService.updateUser(user);
        if(result>0){
            SysUser newUser = userService.selectUserByUserName(loginUser.getUser().getUserName());
            //同个用户ID则更新用户信息,admin操作其他用户则不更新
            if(newUser.getUserId()==loginUser.getUser().getUserId()){
                // 更新缓存用户
                loginUser.setUser(newUser);
            }
            tokenService.setLoginUser(loginUser);
        }
        return toAjax(result);
    }

    /**
     * 删除用户
     */
  /*  @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }*/

    /**
     * 重置密码
     */

  /*  @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }*/

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