package com.fuzamei.web;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
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 com.alibaba.fastjson.JSON;
import com.fuzamei.constant.HintMSG;
import com.fuzamei.constant.RegexConstant;
import com.fuzamei.constant.Roles;
import com.fuzamei.entity.Role;
import com.fuzamei.entity.User;
import com.fuzamei.service.UserAuthoricationService;
import com.fuzamei.service.UserService;
import com.fuzamei.util.JSONUtil;
import com.fuzamei.util.PageDTO;
import com.fuzamei.util.ValidationUtil;

@RestController
@RequestMapping(path = "/user")
public class UserAction {
	@Autowired
	private UserService userService;
	@Autowired
	private UserAuthoricationService userAuthoricationService;
	@Autowired
	private HttpServletRequest req;
	//private static final int ROW_NUM = 10; // 分页每页显示几条
	/**
	 * 查询*得到所有的角色
	 * 
	 * @return
	 */
	@PostMapping(value = "getAllRoles")
	public Map<String, Object> getAllRoles() {
		try {
			Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			userAuthoricationService.queryUserAuthority(user_id, Roles.ADMIN);
			List<Role> roles = userService.getAllRoles();
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, roles);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}

	}
	/**
	 * 查询最大得userId
	 * @return
	 */
	
	@PostMapping(value = "queryUserIdMax")
	public  Map<String, Object> queryUserIdMax(){
		try {
			Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			userAuthoricationService.queryUserAuthority(user_id, Roles.ADMIN);
			
			Integer maxUserId=userService.queryUserIdMax();
			Integer max_No= maxUserId+1;
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, max_No);
		} catch (Exception e) {
		  return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	

	/**
	 * { "user_id":"1001", "roleId":"3", "username":"", "personName":"" } 查看账户列表
	 * 
	 * @param data
	 * @return
	 */
	@PostMapping(value = "/queryUsers")
	public Map<String, Object> queryUsers(@RequestBody String data) {
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = JSON.parseObject(data, Map.class);
		
			Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			userAuthoricationService.queryUserAuthority(user_id, Roles.ADMIN);
			Integer page = ValidationUtil.checkMinAndAssignInt(map.get("page"), 1); //默认第一页
			Integer rowNum = ValidationUtil.checkMinAndAssignInt(map.get("rowNum"), 1);//每页显示多少条
			Integer roleId = ValidationUtil.checkBlankIntegerAndAssignNullIfIsBlank(map.get("roleId"));
			String username = ValidationUtil.checkBlankStringAndAssignEmptyIfIsBlank(map.get("username"));
			String personName = ValidationUtil.checkBlankStringAndAssignEmptyIfIsBlank(map.get("personName"));
			Map<String, Object> mapToService = new LinkedHashMap<String, Object>();
			mapToService.put("user_id", user_id);
			mapToService.put("roleId", roleId);
			mapToService.put("username", username);
			mapToService.put("personName", personName);
			
			mapToService.put("startPage", (page - 1) * rowNum);
			mapToService.put("rowNum", rowNum); // 默认每页显示数据是几条
			PageDTO  pt = userService.queryUsers(mapToService);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS,pt);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL + ":" + e.getMessage(), null);
		}

	}

	/**
	 * 编辑修改 根据用户id修改账号，密码，名称，角色，信息
	 * 
	 * @param data
	 * @return 
	 * 
	  {
	    "tokenId":"Bearer8df740431cd24b81ad34dce61177efe6&1001",//管理员
	    "username": "王五998",
	    "password": "123456",
	    "roleId": "1",
	    "personName": "张三7" 
	    }
	 */
	@PostMapping(value = "/updateAccountByUserId")
	public Map<String, Object> updateAccountByUserId(@RequestBody User user) {
		try {
			 Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			 user.setUserId(user_id);
			 userAuthoricationService.queryUserAuthority(user_id, Roles.ADMIN);
			 Integer userIdb = ValidationUtil.checkAndAssignInt(user.getUserIdb());
			 userAuthoricationService.queryUserAuthority(userIdb, Roles.PLANNER,Roles.SUPPLIER,Roles.CARRIER,Roles.STOCKER);
			 ValidationUtil.checkBlankAndAssignString(user.getUsername());//校验账号
			 ValidationUtil.checkBlankAndAssignString(user.getPassword(),RegexConstant.PWD_REGEX);//校验密码
			 ValidationUtil.checkBlankAndAssignString(user.getPersonName());//校验名称
			 ValidationUtil.checkBlankAndAssignString(user.getSign());//校验签名
			 int num = userService.findUserByuserIdandusername(user);
			 if(num!=0) throw new RuntimeException("该账号名已存在");
			 userService.updateAccountByUserId(user);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}

	}
       
	/**
	 * 添加用户
	 * 
	 * @param user
	 * @param result
	 * @return 
	    { 
	      "tokenId":"Bearer8df740431cd24b81ad34dce61177efe6&1001",//管理员
	      "userId": "xxx", 
	      "username": "王五998",
	      "password": "123456",
	      "roleId": "1",
	      "personName": "张三7" 
	    }
	 */
	@PostMapping(value = "/insertUsers")
	public Map<String, Object> insertUsers(@RequestBody User user) {
		try {
			Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			user.setUserId(user_id);
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(user_id), Roles.ADMIN);
			ValidationUtil.checkAndAssignInt(user.getUserIdb());
		    ValidationUtil.checkRangeAndAssignInt(user.getRoleId(),1,4);//校验角色
			ValidationUtil.checkBlankAndAssignString(user.getUsername());//校验账号
			ValidationUtil.checkBlankAndAssignString(user.getPassword());//校验密码
			ValidationUtil.checkBlankAndAssignString(user.getPersonName());//校验名称
			String random = ValidationUtil.checkBlankAndAssignString(user.getRandom(),RegexConstant.RANDOM_REGEX);//随机数校验
			ValidationUtil.checkBlankAndAssignString(user.getSign());//校验签名
		    int uu=userService.queryRondomRepetition(random);//校验拿到的随机数和数据库得随机数校验
			List<User> us = userService.findUserById(user);
		    if(uu!=0) throw new RuntimeException("随机数重复");
		    if (us.size()!=0) throw new RuntimeException("账号已存在");
			userService.insertUsers(user);
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}
	
	}

	/**
	 * 让前端传过来Id{1001,1002,1003,1004}以逗号隔开 "userids" ——》1，2，3，4，5，6
	 * 
	 * @param userIds
	 * @return
	 */
	  
	@PostMapping(value = "/deleteFromUserId")
	public Map<String, Object> deleteFromUserId(@RequestBody String data) {
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = JSON.parseObject(data, Map.class);
			Integer user_id = ValidationUtil.checkAndAssignInt(req.getHeader("Authorization").split("&")[1]);
			userAuthoricationService.queryUserAuthority(user_id, Roles.ADMIN);
			String sign = ValidationUtil.checkBlankAndAssignString(map.get("sign"));//校验签名
			String userIds = ValidationUtil.checkBlankStringAndAssignEmptyIfIsBlank(map.get("userIds"),RegexConstant.NUMBER_NO);// 校验前端传来的参数是不是数字（userIds）正则表达式 XXX
			if(userIds.contains(String.valueOf(user_id))){
				throw new RuntimeException("无法删除自己");
			}
			User user = new User();
			user.setUserId(user_id);
			user.setUserIds(userIds);
			user.setSign(sign);
			userService.deleteFromUserId(user);
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}

	} 

}
