package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.dto.AuthStatusDTO;
import com.diagbot.dto.QueryAuthProgressDTO;
import com.diagbot.dto.UserAuthenticationDTO;
import com.diagbot.dto.WaitAuthenDTO;
import com.diagbot.entity.Organization;
import com.diagbot.entity.User;
import com.diagbot.entity.UserAuthentication;
import com.diagbot.enums.AccdenEnum;
import com.diagbot.enums.AuthHandleEnum;
import com.diagbot.enums.AuthStatusEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.VisibleIdTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.idc.VisibleIdCreater;
import com.diagbot.service.impl.UserAuthenticationServiceImpl;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.UserAuthenticationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @Description:用户认证业务层
 * @author: zhaops
 * @time: 2018/9/13 19:30
 */
@Component
public class UserAuthenticationFacade extends UserAuthenticationServiceImpl {
    @Autowired
    private UserFacade userFacade;
    @Autowired
    private OrganizationFacade organizationFacade;
    @Autowired
    private VisibleIdCreater visibleIdCreater;

    /**
     * 用户认证
     *
     * @param userAuthenticationVO
     * @return
     */
    public AuthStatusDTO userAuthentication(UserAuthenticationVO userAuthenticationVO) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user_old = userFacade.getById(userId);
        User user = userFacade.findByName(userAuthenticationVO.getUsername());
        if (user == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "用户【" + userAuthenticationVO.getUsername() + "】不存在，不允许验证");
        } else if (!userId.equals(user.getId())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "登录用户【" + user_old.getUsername() + "】与验证用户【" + user.getUsername() + "】不符，不允许验证");
        }

        if (user.getAuthStatus().equals(AuthStatusEnum.Authorized.getKey())) {
            throw new CommonException(CommonErrorCode.IS_EXISTS,
                    "用户【" + user.getUsername() + "】已认证，不允许重复认证");
        } else if (user.getAuthStatus().equals(AuthStatusEnum.Authorizing.getKey())) {
            throw new CommonException(CommonErrorCode.IS_EXISTS,
                    "认证申请已提交，无需重复提交");
        }

        //判断该用户是否有关联机构
        Organization organization_old = organizationFacade.getByUserId(userId);
        if (organization_old == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "当前用户没有关联机构，不允许验证");
        }
        //更新机构信息
        QueryWrapper<Organization> qwOrganization = new QueryWrapper<>();
        qwOrganization.eq("name", userAuthenticationVO.getOrganization()).
                eq("is_deleted", IsDeleteEnum.N.getKey());
        Organization organization = organizationFacade.getOne(qwOrganization);
        if (organization == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "找不到机构【" + userAuthenticationVO.getOrganization() + "】");
        } else if (!organization.getId().equals(organization_old.getId())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "当前用户已关联到机构【" + organization_old.getName() + "】,不允许修改机构");
        }
        organization.setAddress(userAuthenticationVO.getOrganizationAddress());
        organization.setPrincipal(userAuthenticationVO.getOrganizationPrincipal());
        organization.setType(userAuthenticationVO.getOrganizationType());
        organization.setModifier(userId.toString());
        organization.setGmtModified(new Date());
        organization.setSubNum(userAuthenticationVO.getSubOrganizationNum());
        organizationFacade.updateById(organization);

        //更新验证信息
        QueryWrapper<UserAuthentication> qwAuthentication = new QueryWrapper<>();
        qwAuthentication.eq("user_id", userId).
                eq("status", AuthHandleEnum.UNHandle.getKey()).
                eq("is_deleted", IsDeleteEnum.N.getKey());
        UserAuthentication userAuthentication = this.getOne(qwAuthentication);
        //有未处理的认证信息，先做已处理
        if (userAuthentication != null) {
            userAuthentication.setStatus(AuthHandleEnum.Handled.getKey());
            this.updateById(userAuthentication);
        }
        //更新用户状态
        user.setPosition(userAuthenticationVO.getPosition());
        user.setAuthStatus(AuthStatusEnum.Authorizing.getKey());
        userFacade.updateById(user);

        //插入新的认证信息
        userAuthentication = new UserAuthentication();
        userAuthentication.setCreator(userId.toString());
        userAuthentication.setGmtCreate(new Date());
        userAuthentication.setUserId(userId);
        userAuthentication.setModifier(userId.toString());
        userAuthentication.setGmtModified(new Date());
        userAuthentication.setStatus(AuthHandleEnum.UNHandle.getKey());  //状态设为未处理
        userAuthentication.setOrderNum(visibleIdCreater.getNextId(VisibleIdTypeEnum.IS_AUTH.getKey()).toString()); //认证申请单号

        this.saveOrUpdate(userAuthentication);

        AuthStatusDTO authStatusDTO = new AuthStatusDTO();
        authStatusDTO.setAuthStatus(userAuthentication.getStatus());
        authStatusDTO.setAuthStatusName(AuthStatusEnum.Authorizing.getName());
        return authStatusDTO;
    }

    /**
     * 获取待认证用户信息
     *
     * @return
     */
    public UserAuthenticationDTO getUserAuthenticationInfo() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = userFacade.getById(userId);
        //密码置空
        user.setPassword(null);
        Organization organization = organizationFacade.getByUserId(userId);
        QueryWrapper<UserAuthentication> qw = new QueryWrapper<>();
        qw.eq("user_id", userId).
                eq("status", AuthHandleEnum.Handled.getKey()).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                orderByDesc("gmt_create");
        UserAuthentication userAuthentication = this.getOne(qw);
        UserAuthenticationDTO userAuthenticationDTO = new UserAuthenticationDTO();
        userAuthenticationDTO.setUserId(user.getId());
        userAuthenticationDTO.setUsername(user.getUsername());
        userAuthenticationDTO.setLinkman(user.getLinkman());
        userAuthenticationDTO.setEmail(user.getEmail());
        userAuthenticationDTO.setUserType(user.getType());
        userAuthenticationDTO.setPosition(user.getPosition());
        userAuthenticationDTO.setAuthStatus(user.getAuthStatus());
        userAuthenticationDTO.setAuthStatusName(AuthStatusEnum.getName(user.getAuthStatus()));
        userAuthenticationDTO.setOrganizationId(organization.getId());
        userAuthenticationDTO.setOrganizationName(organization.getName());
        userAuthenticationDTO.setOrganizationType(organization.getType());
        userAuthenticationDTO.setPrincipal(organization.getPrincipal());
        userAuthenticationDTO.setSubNum(organization.getSubNum());
        userAuthenticationDTO.setAddress(organization.getAddress());
        if (userAuthentication != null) {
            userAuthenticationDTO.setIsReject(userAuthentication.getIsReject());
            userAuthenticationDTO.setRejectType(userAuthentication.getRejectType());
            userAuthenticationDTO.setRejectComment(userAuthentication.getRejectComment());
        }
        return userAuthenticationDTO;
    }

    /**
     * 获取用户认证状态
     *
     * @return
     */
    public AuthStatusDTO getUserAuthenticationStatus() {
        Map<String, Object> map = this.getUserAuthentication();
        User user = (User) map.get("user");
        AuthStatusDTO authStatusDTO = new AuthStatusDTO();
        Integer status = user.getAuthStatus();
        String statusName = AuthStatusEnum.getName(status);
        authStatusDTO.setAuthStatus(status);
        authStatusDTO.setAuthStatusName(statusName);
        return authStatusDTO;
    }

    /**
     * 控制台-获取用户账号的认证进度
     *
     * @return 包含当前账号的认证状态
     */
    public QueryAuthProgressDTO queryAuthProgress() {
        Map<String, Object> map = this.getUserAuthentication();
        User user = (User) map.get("user");
        UserAuthentication userAuthentication = (UserAuthentication) map.get("userAuthentication");

        QueryAuthProgressDTO queryAuthProgressDTO = new QueryAuthProgressDTO();
        queryAuthProgressDTO.setUserStatus(user.getAuthStatus());
        queryAuthProgressDTO.setUserStatusMsg(AuthStatusEnum.getName(user.getAuthStatus()));
        if (userAuthentication != null) {
            queryAuthProgressDTO.setIsReject(userAuthentication.getIsReject());
            if (userAuthentication.getRejectType() != null) {
                queryAuthProgressDTO.setRejectType(AccdenEnum.getName(userAuthentication.getRejectType()));
            }
            queryAuthProgressDTO.setRejectComment(userAuthentication.getRejectComment());
        }


        return queryAuthProgressDTO;
    }

    /**
     * 获取用户认证信息
     *
     * @return 用户认证信息
     */
    private Map<String, Object> getUserAuthentication() {
        Map<String, Object> map = new HashMap<>();
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = userFacade.getById(userId);
        if (user.getIsDeleted().equals(IsDeleteEnum.Y.getKey()) || user == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "用户不存在");
        } else {
            map.put("user", user);
        }
        QueryWrapper<UserAuthentication> qw = new QueryWrapper<>();
        qw.eq("user_id", userId).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                orderByDesc("gmt_create");
        UserAuthentication userAuthentication = this.getOne(qw);
        if (userAuthentication != null) {
            map.put("userAuthentication", userAuthentication);
        }
        return map;
    }

    /**
     * 控制台-获取待认证的账号数量
     *
     * @return 待认证的账号个数
     */
    public WaitAuthenDTO waitAuthen() {
        WaitAuthenDTO waitAuthenDTO = new WaitAuthenDTO();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("auth_status", AuthStatusEnum.Authorizing.getKey());
        Integer count = userFacade.list(qw).size();
        waitAuthenDTO.setCount(count);
        return waitAuthenDTO;
    }
    
    public List<Integer> getAuthInfoCount(Long userId){
    	List<Integer> ret = new ArrayList<>();
    	Integer authIngCount = 0;
    	Integer authRejectCount = 0;
    	User user = userFacade.getById(userId);
    	if(user.getAuthStatus()==2){
    		authIngCount = 1;
    	}else if(user.getAuthStatus()==0){
    		 QueryWrapper<UserAuthentication> qw = new QueryWrapper<>();
    	     qw.eq("user_id", userId).
    	                eq("is_deleted", IsDeleteEnum.N.getKey()).
    	                orderByDesc("gmt_create");
    	     UserAuthentication userAuthentication = this.getOne(qw);
    	     if(userAuthentication!=null&&userAuthentication.getIsReject()==0){
    	    	 authRejectCount = 1;
    	     }
    	}
    	
    	ret.add(authIngCount);
    	ret.add(authRejectCount);
    
    	return ret;
    }
}
