package com.platform.modules.sys.controller;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.R;
import com.platform.common.validator.Assert;
import com.platform.common.validator.ValidatorUtils;
import com.platform.common.validator.group.AddGroup;
import com.platform.common.validator.group.UpdateGroup;
import com.platform.modules.live.utils.PlatformTenantProperties;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.form.PasswordForm;
import com.platform.modules.sys.service.SysUserRoleService;
import com.platform.modules.sys.service.SysUserService;
import com.platform.modules.sys.vo.SysUserEntityVo;
import com.platform.modules.sys.vo.SysUserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 */
@RestController
@RequestMapping("/sys/user")
@Api(value = "用户接口", tags = "用户接口")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private PlatformTenantProperties tenantProperties;
	@Value("${materia.basePath}")
	private String DOMAIN;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	@ApiOperation(value = "用户列表", notes = "用户列表")
	public R list(@RequestParam Map<String, Object> params) {
		// 只有超级管理员，才能查看所有管理员列表
//		if (getUserId() != Constant.SUPER_ADMIN) {
//			params.put("createUserId", getUserId());
//		}
		// 只有系统管理员与报业可以看所有用户
		Long tenantId = getUser().getTenantId();
		if (null != tenantId && !tenantProperties.getManageTenantId().equals(tenantId)){
			params.put("tenantId", tenantId.toString());
		}

		PageUtils page = sysUserService.queryPage(params);

		return R.ok().put("page", page);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	@ApiOperation(value = "获取当前登录用户", notes = "获取当前登录用户")
	public R info() {
		// 获取登陆用户信息
		SysUserEntity userEntity = getUser();
		if (null == userEntity)
			return R.error("获取用户信息失败");
		// 处理用户身份证号
		String idCard = userEntity.getIdCard();
		if (StringUtils.isNotBlank(idCard) && idCard.trim().length() > 15) {
			String idCardShow = idCard.replace(idCard.substring(4, 14), "**********");
			userEntity.setIdCard(idCardShow);
		}

		SysUserEntityVo userVo = new SysUserEntityVo(userEntity);

		// 拼接图片地址
		String userImg = userVo.getUserImg();
		if (StringUtils.isNotBlank(userVo.getUserImg())){
			userImg = DOMAIN + userImg;
			userVo.setUserImg(userImg);
		}

		return R.ok().put("user", userVo).put("mngTenantId", tenantProperties.getManageTenantId()).put("isMng", userEntity.getTenantId() == null || userEntity.getTenantId().equals(tenantProperties.getManageTenantId()));
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody PasswordForm form) {
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");

		// sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		// sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	@ApiOperation(value = "用户信息", notes = "用户信息")
	public R info(@PathVariable("userId") Long userId) {
		SysUserEntity user = sysUserService.selectById(userId);

		// 获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);

		SysUserInfoVo infoVo = new SysUserInfoVo(user);

		// 拼接图片地址
		String userImg = infoVo.getUserImg();
		if (StringUtils.isNotBlank(infoVo.getUserImg())){
			userImg = DOMAIN + userImg;
			infoVo.setUserImg(userImg);
		}

		return R.ok().put("user", infoVo);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	@ApiOperation(value = "保存用户", notes = "保存用户")
	public R save(@ModelAttribute SysUserEntity user,MultipartFile materialFile) {
		ValidatorUtils.validateEntity(user, AddGroup.class);
		String result = sysUserService.checkExist(user.getUserId(), user.getUsername(), user.getMobile(), user
				.getEmail());
		if (StringUtils.isNotBlank(result)) {
			return R.error(result);
		}

		user.setCreateUserId(getUserId());
		try {
			sysUserService.save(user, materialFile);
		} catch (IOException e) {
			return R.error(e.getMessage());
		}
		return R.ok();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	@ApiOperation(value = "更新用户", notes = "更新用户")
	public R update(@ModelAttribute SysUserEntity user, MultipartFile materialFile) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		String result = sysUserService.checkExist(user.getUserId(), user.getUsername(), user.getMobile(), user
				.getEmail());
		if (StringUtils.isNotBlank(result)) {
			return R.error(result);
		}

		user.setCreateUserId(getUserId());
		sysUserService.update(user, materialFile);

		return R.ok();
	}

	@SysLog("修改自身密码")
	@PostMapping("/update/password")
	@ApiOperation("修改用户自己的密码")
	public R updateUserPassword(@RequestBody PasswordForm form) {

		if (StringUtils.isBlank(form.getPassword())) {
			return R.error("新密码不为能空");
		}
		// sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		// sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

		if (password.equals(newPassword)) {
			return R.error("原密码与新密码相同");
		}

		// 更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}

		return R.ok();
	}
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds) {
		if (ArrayUtils.contains(userIds, 1L)) {
			return R.error("系统管理员不能删除");
		}

		if (ArrayUtils.contains(userIds, getUserId())) {
			return R.error("当前用户不能删除");
		}

		sysUserService.deleteBatch(userIds);

		return R.ok();
	}
}
