package com.sqx.modules.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sqx.common.annotation.SysLog;
import com.sqx.common.utils.Constant;
import com.sqx.common.utils.Result;
import com.sqx.common.validator.Assert;
import com.sqx.common.validator.ValidatorUtils;
import com.sqx.common.validator.group.AddGroup;
import com.sqx.common.validator.group.UpdateGroup;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.datacentre.dao.ShopAdminDao;
import com.sqx.modules.datacentre.entity.SysUserShop;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.sys.dao.SysUserDao;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.sys.form.PasswordForm;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private ShopAdminDao shopAdminDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private GoodsShopDao goodsShopDao;
	@Autowired
	private SysUserDao sysUserDao;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public Result list(String page, String limit, String username, String shopName){
		Map<String, Object> params = new HashMap<>();

		if (StrUtil.isNotBlank(username)) {
			params.put("username", username);
		}

		if (StrUtil.isNotBlank(shopName)) {
			params.put("shopName", shopName);
		}

		if (StrUtil.isNotBlank(page)) {
			params.put(Constant.PAGE, page);
		}

		if (StrUtil.isNotBlank(limit)) {
			params.put(Constant.LIMIT, limit);
		}

		return Result.success().put("page", sysUserService.queryPage(params));
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public Result info(){
		SysUserEntity user = getUser();
		UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("admin_user_id", user.getUserId()));
		user.setUserEntity(userEntity);
		List<SysUserShop> sysUserShops = sysUserService.selectShopId(user.getUserId());
		user.setShopList(sysUserShops);
		return Result.success().put("user", user);
	}

	@GetMapping("/infoByShopId")
	public Result infoByShopId(Long shopId){
		GoodsShop goodsShop = goodsShopDao.selectById(shopId);
		UserEntity userEntity = userDao.selectById(goodsShop.getUserId());
		SysUserEntity user=new SysUserEntity();
		user.setUserEntity(userEntity);
		SysUserShop sysUserShop = sysUserDao.selectUserByShopId(shopId);
		user.setUserId(sysUserShop.getUserId());
		List<SysUserShop> sysUserShops = sysUserService.selectShopId(sysUserShop.getUserId());
		user.setShopList(sysUserShops);
		return Result.success().put("user", user);
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public Result 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 Result.error("原密码不正确");
		}
		
		return Result.success();
	}
	
	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public Result info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.getById(userId);
		List<SysUserShop> userShops = shopAdminDao.selectList(new QueryWrapper<SysUserShop>().eq("user_id", userId));
		List list = new ArrayList();
		for(int i = 0;i<userShops.size();i++){
			list.add(userShops.get(i).getShopId());
		}
		user.setShopIdList(list);
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return Result.success().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public Result save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		
		user.setCreateUserId(getUserId());
		user.setUserType(1);
		sysUserService.saveUser(user);
		
		return Result.success();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public Result update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		
		return Result.success();
	}

	/**
	 * 管理端修改密码
	 */
	@SysLog("管理端修改密码")
	@PostMapping("/updateAdmin")
	public Result updateAdmin(@RequestBody SysUserEntity user){
		user.setCreateUserId(getUserId());
		sysUserService.updateAdmin(user);

		return Result.success();
	}

	/**
	 * 商户端修改用户
	 */
	@SysLog("商户端修改密码")
	@PostMapping("/updateShop")
	public Result updateShop(@RequestBody SysUserEntity user){
		SysUserEntity user1 = getUser();
		user.setUserId(user1.getUserId());
		user.setCreateUserId(getUserId());
		sysUserService.updateShop(user);
		return Result.success();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public Result delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return Result.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return Result.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return Result.success();
	}

	@SysLog("判断是否是超级管理员")
	@GetMapping("/isSuperAdmin")
	public Result isSuperAdmin(Integer sysUserId){
//        判断是否是超级管理员
		LambdaQueryWrapper<SysUserRoleEntity> wrapper=new LambdaQueryWrapper<>();
		wrapper.eq(SysUserRoleEntity::getRoleId,3)
				.eq(SysUserRoleEntity::getUserId,sysUserId);
		SysUserRoleEntity sysUserRoleEntity = sysUserRoleService.getOne(wrapper);
		if (ObjectUtils.isEmpty(sysUserRoleEntity)) {
			return Result.success().put("superAdmin",0);
		}else {
			return Result.success().put("superAdmin",1);
		}
	}

}
