package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.MD5Util;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.BsOrganization;
import com.hai.entity.SecRole;
import com.hai.entity.SecUser;
import com.hai.entity.SecUserLabel;
import com.hai.model.ResponseData;
import com.hai.model.SecUserModel;
import com.hai.model.UserInfoModel;
import com.hai.model.UserTreeModel;
import com.hai.service.BsOrganizationService;
import com.hai.service.SecRoleService;
import com.hai.service.SecUserLabelService;
import com.hai.service.SecUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/secUser")
@Api(value="用户管理")
public class SecUserController {

	private static Logger log = LoggerFactory.getLogger(SecUserController.class);

	@Resource
	private UserCenter userCenter;

	@Resource
	private SecUserService secUserService;

	@Resource
	private BsOrganizationService bsOrganizationService;

	@Resource
	private SecRoleService secRoleService;

	@Resource
	private SecUserLabelService userLabelService;

	@RequestMapping(value="/sendUserPass",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改用户密码  {'userId':'','nonceStr':'','newPassword':'','sign':''} ")
	public ResponseData sendUserPass(@RequestBody String reqBody, HttpServletRequest request, HttpServletResponse response) throws Exception{
		try {

			JSONObject jsonObject = JSONObject.parseObject(reqBody);

			Long userId = jsonObject.getLong("userId");				//用户Id
			String oldPassword = jsonObject.getString("oldPassword");		//旧密码
			String password = jsonObject.getString("newPassword");		//密码

			if(userId == null || StringUtils.isBlank(oldPassword) || StringUtils.isBlank(password)) {
				log.error("BaseMemberController --> sendUserPass() error!","参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}

			//查询用户
			SecUser secUser = secUserService.findById(userId);
			if(secUser == null){
				log.error("BaseMemberController --> sendUserPass() error!","");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_MEMBER_ERROR, "");
			}
			if(!secUser.getPassword().equals(MD5Util.encode(oldPassword.getBytes()))) {
				log.error("BaseMemberController --> sendUserPass() error!","旧密码不一致");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "旧密码不一致");
			}
			secUser.setPassword(MD5Util.encode(password.getBytes()));
			//修改
			secUserService.updateUser(secUser);

			return ResponseMsgUtil.success("修改密码成功");

		} catch (Exception e) {
			log.error("getUserByTelephone",e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/getUserList", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取用户列表")
	public ResponseData getUserList(@RequestParam(name = "companyId", required = true) Long companyId,
									@RequestParam(name = "organizationId", required = false) Long organizationId,
									@RequestParam(name = "userName", required = false) String userName,
									@RequestParam(name = "phone", required = false) String phone,
									@RequestParam(name = "pageNum", required = true) Integer pageNum,
									@RequestParam(name = "pageSize", required = true) Integer pageSize) {
		try {
			if (companyId == null || pageNum == null || pageSize == null) {
				log.error("SecUserController --> getUserList() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			PageInfo<SecUserModel> userList = secUserService.findPage(companyId,organizationId,userName,phone,pageNum,pageSize);
			return ResponseMsgUtil.success(userList);
		} catch (Exception e) {
			log.error("SecUserController --> getUserList() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加用户")
	public ResponseData addUser(@RequestBody SecUser secUser) {
		try {
			if (secUser.getCompanyId() == null
					|| secUser.getOrganizationId() == null
					|| StringUtils.isBlank(secUser.getUserName())
					|| StringUtils.isBlank(secUser.getPassword())
					|| StringUtils.isBlank(secUser.getLoginName())
					|| secUser.getRoleId() == null
			) {
				log.error("SecUserController --> addUser() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			SecUser user = secUserService.findByLoginName(secUser.getLoginName());
			if (user != null) {
				log.error("SecUserController --> addUser() error!", "该用户名已存在，请更换");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
			}
			SecUser userPhone = secUserService.findByPhone(secUser.getTelephone());
			if (userPhone != null) {
				log.error("SecUserController --> addUser() error!", "该用户电话已被绑定，请更换");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PHONE_HAS_ONE_ERROR, "");
			}
			secUser.setPassword(MD5Util.encode(secUser.getPassword().getBytes()));
			secUser.setAdminFlag(0);
			secUser.setObjectType(1);
			secUser.setObjectId(secUser.getCompanyId());
			secUser.setStatus(1);
			secUser.setCreateTime(new Date());
			secUser.setUpdateTime(new Date());
			secUserService.addUser(secUser);
			return ResponseMsgUtil.success("增加成功");
		} catch (Exception e) {
			log.error("SecUserController --> addUser() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改用户信息")
	public ResponseData editUser(@RequestBody SecUser secUser) {
		try {
			if (secUser.getId() == null
					|| secUser.getCompanyId() == null
					|| secUser.getOrganizationId() == null
					|| StringUtils.isBlank(secUser.getUserName())
					|| StringUtils.isBlank(secUser.getPassword())
					|| StringUtils.isBlank(secUser.getLoginName())) {
				log.error("SecUserController --> editUser() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			SecUser user = secUserService.findById(secUser.getId());
			if (user.getPassword().equals(secUser.getPassword())) {
				secUser.setPassword(user.getPassword());
			}else {
				secUser.setPassword(MD5Util.encode(secUser.getPassword().getBytes()));
			}

			SecUser userLogin = secUserService.findByLoginName(secUser.getLoginName());
			if (userLogin != null && !userLogin.getId().equals(secUser.getId())) {
				log.error("SecUserController --> addUser() error!", "该用户名已存在，请更换");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_LOGIN_NAME_IS_EXIST_ERROR, "");
			}
			SecUser userPhone = secUserService.findByPhone(secUser.getTelephone());
			if (userPhone != null && !userPhone.getId().equals(secUser.getId())) {
				log.error("SecUserController --> addUser() error!", "该用户电话已被绑定，请更换");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PHONE_HAS_ONE_ERROR, "");
			}
			secUser.setAdminFlag(user.getAdminFlag());
			secUser.setObjectType(user.getObjectType());
			secUser.setObjectId(secUser.getCompanyId());
			secUser.setStatus(user.getStatus());
			secUser.setCreateTime(user.getCreateTime());
			secUser.setUpdateTime(new Date());
			secUserService.modifyUser(secUser);
			return ResponseMsgUtil.success(null);
		} catch (Exception e) {
			log.error("SecUserController --> addUser() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "删除用户")
	public ResponseData deleteUser(Long userId) {
		try {
			if (userId == null) {
				log.error("SecUserController --> deleteUser() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			SecUser user = secUserService.findById(userId);
			user.setStatus(0);
			secUserService.modifyUser(user);
			return ResponseMsgUtil.success(user);
		} catch (Exception e) {
			log.error("SecUserController --> deleteUser() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/getUserView", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取用户详情")
	public ResponseData getUserView(Long userId) {
		try {
			if (userId == null) {
				log.error("SecUserController --> getUserView() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			SecUser user = secUserService.findById(userId);
			if (user != null) {
				List<SecUserLabel> labelList = userLabelService.getLabelByUser(user.getId());
				List<Long> labelIdArray = new ArrayList<>();
				List<String> labelNameArray = new ArrayList<>();

				for (SecUserLabel label : labelList) {
					labelIdArray.add(label.getLabelId());
				}
				user.setLabelIdArray(labelIdArray);

				for (SecUserLabel label : labelList) {
					labelNameArray.add(label.getLabelName());
				}
				user.setLabelNameArray(labelNameArray);
			}
			SecRole role = secRoleService.getRoleByUserId(userId);
			user.setRoleId(role.getId());
			return ResponseMsgUtil.success(user);
		} catch (Exception e) {
			log.error("SecUserController --> getUserView() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value = "/getUserRole", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取用户角色关系")
	public ResponseData getUserRole(Long userId) {
		try {
			if (userId == null) {
				log.error("SecUserController --> getUserRole() error!", "参数错误");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			SecRole role = secRoleService.getRoleByUserId(userId);
			return ResponseMsgUtil.success(role);
		} catch (Exception e) {
			log.error("SecUserController --> getUserRole() error!", e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="/findAuditUserTree",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "查询审批人员树")
	public ResponseData findAuditUserTree(HttpServletRequest request){
		try {
			// 登录人员
			SessionObject sessionObject = userCenter.getSessionObject(request);
			if(sessionObject == null){
				log.error("SecUserController --> findAuditUserTree() error!", "");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
			}
			UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
			if (userInfoModel.getSecUser() == null
					|| userInfoModel.getSecUser().getObjectType() != 1
					|| userInfoModel.getBsOrganization() == null
					|| userInfoModel.getBsCompany() == null) {
				log.error("SecUserController --> findAuditUserTree() error!", "");
				throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
			}
			BsOrganization organization = userInfoModel.getBsOrganization();
			if (organization.getParentId() != null) {
					organization = bsOrganizationService.findTopByCompany(userInfoModel.getBsCompany().getId());
			}
			UserTreeModel userTree = secUserService.findAttendUserTree(userInfoModel.getBsCompany().getId(),organization);
			return ResponseMsgUtil.success(userTree);
		} catch (Exception e) {
			log.error("SecUserController --> findAuditUserTree() error!",e);
			return ResponseMsgUtil.exception(e);
		}
	}
}
