/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.sys.controller;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.security.comment.model.UpdatePasswordDto;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.common.config.Constant;
import com.yami.shop.bean.model.SysUser;
import com.yami.shop.sys.service.SysRoleService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 系统用户信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-10-30
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private PasswordEncoder passwordEncoder;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('sys:user:page')")
	public R<IPage<SysUser>> page(String username,PageParam<SysUser> page){
		return R.SUCCESS(sysUserService.selectPage(username,page));
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R<SysUser> info(){
		return R.SUCCESS(sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId()));
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	@ApiOperation(value="修改密码", notes="修改当前登陆用户的密码")
	public R<String> password(@RequestBody @Valid UpdatePasswordDto param){
		Long userId = SecurityUtils.getSysUser().getUserId();

		SysUser dbUser = sysUserService.getSysUserById(userId);
		if (!passwordEncoder.matches(param.getPassword(), dbUser.getPassword())) {
			 throw new GlobalException("原密码不正确");
		}
		//新密码
		String newPassword = passwordEncoder.encode(param.getNewPassword());
//		更新密码
		sysUserService.updatePasswordByUserId(userId, newPassword);
		return  R.SUCCESS();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@PreAuthorize("@pms.hasPermission('sys:user:info')")
	public R<SysUser> info(@PathVariable("userId") Long userId){
		SysUser user = sysUserService.getSysUserById(userId);
		user.setUserId(null);
		//获取用户所属的角色列表
		List<Long> roleIdList = sysRoleService.listRoleIdByUserId(userId);
		//获取用户所属企业列表
		user.setChannelIdList(sysUserService.findByUserIdListId(userId));
		user.setRoleIdList(roleIdList);
		return  R.SUCCESS(user);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys:user:save')")
	public R<String> save(@Valid @RequestBody SysUser user){
		String username = user.getUsername();
		SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getUsername, username));
		if (dbUser!=null) {
			return R.FAIL("该用户已存在");
		}
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		sysUserService.saveUserAndUserRole(user);

		return  R.SUCCESS();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys:user:update')")
	public R<String> update(@Valid @RequestBody SysUser user){
		String password = user.getPassword();

		SysUser dbUser = sysUserService.getSysUserById(user.getUserId());
		SysUser dbUserNameInfo = sysUserService.getByUserName(user.getUsername());

		if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),user.getUserId())) {
			return R.FAIL("该用户已存在");
		}
		if (StrUtil.isBlank(password)) {
			user.setPassword(null);
		}else {
			user.setPassword(passwordEncoder.encode(user.getPassword()));
		}
		sysUserService.updateUserAndUserRole(user);
		return  R.SUCCESS();
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys:user:delete')")
	public R<String> delete(@RequestBody Long[] userIds){
		if (userIds.length == 0) {
			return R.FAIL("请选择需要删除的用户");
		}
		if(ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)){
			return R.FAIL("系统管理员不能删除");
		}
		if(ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())){
			return R.FAIL("当前用户不能删除");
		}
		sysUserService.removeByIds(Arrays.asList(userIds));
		return  R.SUCCESS();
	}

	/**
	 * 退出
	 */
	@PostMapping(value = "/logout")
	public R<String> logout() {
		SecurityContextHolder.clearContext();
		return  R.SUCCESS();
	}



}
