package com.diagbot.facade;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.AuthStatusEnum;
import com.diagbot.enums.OrganizationTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.UserAuthenticationServiceImpl;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.UserAuthenticationVO;

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

    /**
     * @Description:用户认证
     * @author: zhaops
     * @time: 2018/9/13 19:30
     */
    public UserAuthenticationDTO userAuthentication(UserAuthenticationVO userAuthenticationVO) {
        UserAuthenticationDTO userAuthenticationDTO = new UserAuthenticationDTO();
        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 (user.getId() != userId) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "登录用户【" + user_old.getUsername() + "】与验证用户【" + user.getUsername() + "】不符，不允许验证");
        }

        //判断该用户是否有关联机构
        Organization organization_old = organizationFacade.getByUserId(userId);
        if (organization_old == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "当前用户没有关联机构，不允许验证");
        }
        //更新机构信息
        Organization organization = organizationFacade.getByName(userAuthenticationVO.getOrganization());
        if (organization == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "找不到机构【" + userAuthenticationVO.getOrganization() + "】");
        } else if (organization.getId() != 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);

        //更新验证信息
        UserAuthentication userAuthentication = this.getByUserId(userId);
        if (userAuthentication == null) {
            userAuthentication = new UserAuthentication();
            userAuthentication.setCreator(userId.toString());
            userAuthentication.setGmtCreate(new Date());
            userAuthentication.setUserId(userId);
        } else if (userAuthentication.getStatus().equals(AuthStatusEnum.Authorized.getKey())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "用户【" + user.getUsername() + "】已认证，不允许重复认证");
        } else if (userAuthentication.getStatus().equals(AuthStatusEnum.Authorizing.getKey())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "认证申请已提交，无需重复提交");
        }
        userAuthentication.setModifier(userId.toString());
        userAuthentication.setGmtModified(new Date());
        userAuthentication.setPosition(userAuthenticationVO.getPosition());
        userAuthentication.setStatus(AuthStatusEnum.Authorizing.getKey());  //状态设为认证中
        this.saveOrUpdate(userAuthentication);

        userAuthenticationDTO.setUser(user);
        userAuthenticationDTO.setOrganization(organization);
        userAuthenticationDTO.setUserAuthentication(userAuthentication);
        return userAuthenticationDTO;
    }

    /**
     * @Description:获取用户认证信息
     * @author: zhaops
     * @time: 2018/9/13 19:30
     */
    public UserAuthenticationDTO getuserAuthenticationInfo() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        User user = userFacade.getById(userId);
        Organization organization = organizationFacade.getByUserId(userId);
        UserAuthentication userAuthentication = this.getByUserId(userId);
        UserAuthenticationDTO userAuthenticationDTO = new UserAuthenticationDTO();
        userAuthenticationDTO.setUser(user);
        userAuthenticationDTO.setOrganization(organization);
        userAuthenticationDTO.setUserAuthentication(userAuthentication);
        Map<Integer, Object> organizationType = new HashMap<>();
        for (OrganizationTypeEnum item : OrganizationTypeEnum.values()) {
            organizationType.put(item.getKey(), item.getName());
        }
        userAuthenticationDTO.setOrganizationType(organizationType);
        return userAuthenticationDTO;
    }

    /**
     * @Description:获取用户认证状态
     * @author: zhaops
     * @time: 2018/9/13 19:30
     */
    public Map<Integer, Object> getUserAuthenticationStatus() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        UserAuthentication userAuthentication = this.getByUserId(userId);
        Map<Integer, Object> map = new HashMap<>();
        if (userAuthentication == null) {
            map.put(99, "当前用户没有认证信息");
        } else {
            Integer status = userAuthentication.getStatus();
            String statusName = AuthStatusEnum.getName(status);
//            switch (status) {
//                case 0:
//                    statusName = AuthStatusEnum.Unauthorized.getName();
//                    break;
//                case 1:
//                    statusName = AuthStatusEnum.Authorized.getName();
//                    break;
//                case 2:
//                    statusName = AuthStatusEnum.Authorizing.getName();
//                    break;
//                default:
//                    break;
//            }
            map.put(status, statusName);
        }
        return map;
    }

    public QueryAuthProgressDTO queryAuthProgress() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        UserAuthentication userAuthentication = this.getByUserId(userId);

        QueryAuthProgressDTO queryAuthProgressDTO = new QueryAuthProgressDTO();
        queryAuthProgressDTO.setStatus(userAuthentication.getStatus());
        queryAuthProgressDTO.setIsReject(userAuthentication.getIsReject());
        queryAuthProgressDTO.setRejectComment(userAuthentication.getRejectComment());

        return queryAuthProgressDTO;
    }
    
    public WaitAuthenDTO waitAuthen(){
    	WaitAuthenDTO waitAuthenDTO = new WaitAuthenDTO();
    	waitAuthenDTO.setCount(baseMapper.getAllWaitAuthCou());
    	return waitAuthenDTO;
    }
}
