package com.diagbot.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.annotation.SysLogger;
import com.diagbot.dto.RespDTO;
import com.diagbot.dto.UserInfoDTO;
import com.diagbot.entity.Organization;
import com.diagbot.entity.User;
import com.diagbot.entity.UserAuthentication;
import com.diagbot.entity.UserOrganization;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.facade.OrganizationFacade;
import com.diagbot.facade.UserAuthenticationFacade;
import com.diagbot.facade.UserFacade;
import com.diagbot.facade.UserOrganizationFacade;
import com.diagbot.util.DateUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.OrganizationVO;
import com.diagbot.vo.UserAndOrganizationVO;
import com.diagbot.vo.UserInfoAuditVO;
import com.diagbot.vo.UserInfoOrganizationsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 外部用户信息
 * @author: wangfeng
 * @time: 2018年9月17日 下午1:53:53
 */
@RestController
@Api(value = "用户信息和机构信息API[by:wangfeng]", tags = { "用户信息和机构信息API" })
@RequestMapping("/userInfo")
@SuppressWarnings("unchecked")
public class UserInfoController {

	@Autowired
	private UserFacade userFacade;
	@Autowired
	OrganizationFacade organizationFacade;
	@Autowired
	UserOrganizationFacade userOrganizationFacade;
	@Autowired
	UserAuthenticationFacade userAuthenticationFacade;

	@ApiOperation(value = "分页查询获取用户信息[by:wangfeng]", notes = "根据每页显示条数，默认 10，和当前页")
	@PostMapping("/getUserInfoPag")
	@SysLogger("getUserInfoPag")
	// @ApiIgnore
	public RespDTO<UserInfoDTO> getUserInfoPag(Page page, String orgName, Integer autStatus) {
		UserInfoDTO userInfo = new UserInfoDTO();
		userInfo.setOrgName(orgName);
		userInfo.setAutStatus(autStatus);
		IPage<UserInfoDTO> user = userFacade.selectUserInfoListPage(page, userInfo);
		return RespDTO.onSuc(user);
	}

	@ApiOperation(value = "修改用户信息和机构信息[by:wangfeng]", notes = "用户信息和机构信息")
	@PostMapping("/updateUserInfoAll")
	@SysLogger("updateUserInfoAll")
	@Transactional
	public RespDTO<UserInfoOrganizationsVO> updateUserInfoAll(
			@Valid @RequestBody UserInfoOrganizationsVO userInfoOrganizationsVO) {
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("modifier",UserUtils.getCurrentPrincipleID());
		userMap.put("gmtModified", DateUtil.now());
		userMap.put("email", userInfoOrganizationsVO.getEmail());
		userMap.put("principal", userInfoOrganizationsVO.getPrincipal());
		userMap.put("address", userInfoOrganizationsVO.getAddress());
		userMap.put("type", userInfoOrganizationsVO.getType());
		userMap.put("position", userInfoOrganizationsVO.getPosition());
		userMap.put("userId", userInfoOrganizationsVO.getUserId());
		boolean res = userFacade.updateUserInfoAll(userMap);
		if (!res){
			throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
		}
		return RespDTO.onSuc(res);
	}

	@ApiOperation(value = "审核用户信息和机构信息[by:wangfeng]", notes = "审核用户信息和机构信息")
	@PostMapping("/auditUserInfoAll")
	@SysLogger("auditUserInfoAll")
	@Transactional
	public RespDTO<Boolean> auditUserInfoAll(@Valid @RequestBody UserInfoAuditVO userInfoAuditVO) {
		Map<String, Object> auditMap = new HashMap<String, Object>();
		auditMap.put("userId", userInfoAuditVO.getUserId());
		auditMap.put("modifier",UserUtils.getCurrentPrincipleID());
		auditMap.put("gmtModified", DateUtil.now());
		auditMap.put("isReject", userInfoAuditVO.getIsReject());
		auditMap.put("rejectComment", userInfoAuditVO.getRejectComment());
		auditMap.put("rejectType", userInfoAuditVO.getRejectType());
		// TODO 审核前先验证该用户的的认证状态
		boolean res = userFacade.auditUserInfoAll(auditMap);

		if (!res){
			throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
		}
		return RespDTO.onSuc(res);
	}

	@ApiOperation(value = "删除用户信息和机构信息[by:wangfeng]", notes = "用户信息和机构信息")
	@PostMapping("/updateDeleted")
	@SysLogger("updateDeleted")
	@Transactional
	public RespDTO updateDeleted(@RequestParam String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("modifier",UserUtils.getCurrentPrincipleID());
		map.put("gmtModified", DateUtil.now());
		boolean res = userFacade.updateDeleted(map);
		if (!res){
			throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
		}
		return RespDTO.onSuc(res);
	}

	@ApiOperation(value = "模糊查询机构信息[by:wangfeng]", notes = "机构信息")
	@PostMapping("/findOrganization")
	@SysLogger("findOrganization")
	public RespDTO findOrganization(@RequestParam String organizationName) {
		// TODO 返回机构Id和机构
		List<Organization> organization = organizationFacade.findOrganization(organizationName);

		return RespDTO.onSuc(organization);
	}

	@ApiOperation(value = "添加构信息[by:wangfeng]", notes = "机构信息")
	@PostMapping("/addOrganization")
	@SysLogger("addOrganization")
	@Transactional
	public RespDTO<Boolean> addOrganization(@Valid @RequestBody OrganizationVO organizationVO) {

		String organizationName = organizationVO.getOrganizationName();
		List<Organization> organizationList = organizationFacade.findOrganization(organizationName);
		if (organizationList.size() > 0) {
			return RespDTO.onSuc("该机构存在");
		}
		Organization organization = new Organization();
		organization.setName(organizationVO.getOrganizationName());
		organization.setType(organizationVO.getType());
		organization.setPrincipal(organizationVO.getPrincipal());
		organization.setSubNum(organizationVO.getSubNum());
		organization.setAddress(organizationVO.getAddress());
		organization.setGmtCreate(DateUtil.now());
		organization.setModifier(UserUtils.getCurrentPrincipleID());
		// organization.setCreator("5");

		boolean res = organizationFacade.save(organization);

		// System.out.println(GsonUtil.toJson(organization));
		if (!res){
			throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
		}
		return RespDTO.onSuc(res);
	}

	@ApiOperation(value = "添加用户信息和机构信息管理员[by:wangfeng]", notes = "用户信息和机构信息的绑定")
	@PostMapping("/addUserInfo")
	@SysLogger("addUserInfo")
	@Transactional
	public RespDTO<UserAndOrganizationVO> addUserInfo(@Valid @RequestBody UserAndOrganizationVO userAndOrganizationVO) {
		// TODO 先查找机构，获取机构id,再注册用户,返回用户id, 取到用户id和 机构id ,查询用户机构关联表，在进行绑定
		// User user = new User();
		// 验证用户是否存在
		String username = userAndOrganizationVO.getUserName();
		User userData = userFacade.getUserInfo(username);
		// System.out.println(user);
		if (userData != null) {
			return RespDTO.onSuc("该用户存在");
		}
		// 验证机构是否被绑定
		UserOrganization userORG = new UserOrganization();
		userORG.setOrganizationId(userAndOrganizationVO.getOrganizationid());

		List<UserOrganization> userOrganizationData = userOrganizationFacade.getAgencyPersonnel(userORG);
		if (userOrganizationData.size() > 0) {
			return RespDTO.onSuc("该机构绑定了用户！");
		}

		User user = new User();
		user.setCreator(UserUtils.getCurrentPrincipleID());
		user.setUsername(userAndOrganizationVO.getUserName());
		PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		String entryPassword = passwordEncoder.encode(userAndOrganizationVO.getPassWord());
		user.setPassword(entryPassword);
		user.setLinkman(userAndOrganizationVO.getLinkman());
		user.setGmtCreate(DateUtil.now());
		user.setEmail(userAndOrganizationVO.getEmail());
		boolean res = userFacade.save(user);
		if (res == true) {
			Long userId = user.getId();
			// 用户信息的认证
			UserAuthentication userAuthentication = new UserAuthentication();
			userAuthentication.setCreator(UserUtils.getCurrentPrincipleID());//
			// 创建人Id
			userAuthentication.setGmtCreate(DateUtil.now());// 记录创建时间
			userAuthentication.setPosition(userAndOrganizationVO.getPosition());// 岗位信息
			userAuthentication.setUserId(userId);// 用户id
			userAuthentication.setIsReject(1);// 是否通过认证 0:未通过，1:已通过
			userAuthentication.setStatus(1);// 认证状态（0：未认证，1：已认证，2：认证中）
			userAuthenticationFacade.save(userAuthentication);

			// 用户信息和机构信息的绑定
			UserOrganization userOrganization = new UserOrganization();
			userOrganization.setCreator(UserUtils.getCurrentPrincipleID());//
			// 创建人Id
			userOrganization.setGmtCreate(DateUtil.now());
			userOrganization.setOrganizationId(userAndOrganizationVO.getOrganizationid());// 机构id
			userOrganization.setUserId(userId);// 用户id

			userOrganizationFacade.save(userOrganization);
		}

		return RespDTO.onSuc("绑定成功");
	}

}
