package com.zcxk.service.impl.thirdparty;

import com.alibaba.fastjson.JSONObject;
import com.zcxk.config.SsoConfig;
import com.zcxk.dao.AuthTenantMenuMapper;
import com.zcxk.dao.UserMapper;
import com.zcxk.dto.thirdparty.LoginQueryDto;
import com.zcxk.dto.thirdparty.XieDingResultDto;
import com.zcxk.entity.User;
import com.zcxk.exception.ServiceException;
import com.zcxk.model.LoginUser;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.ThirdPartyLoginService;
import com.zcxk.util.HttpClientPoolUtil;
import com.zcxk.util.MD5Util;
import com.zcxk.util.UserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;

/**
 * @ClassName XiedingLoginServiceImpl
 * @Description: 协鼎单点登录业务处理
 * @Author lihui
 * @Date 2021/4/7
 * @Version V1.0
 **/
@Service("xiedingLoginService")
public class XiedingLoginServiceImpl implements ThirdPartyLoginService {


    @Autowired
    private SsoConfig ssoConfig;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthTenantMenuMapper authMenuMapper;

    @Override
    public String getToken(LoginQueryDto queryDto) {
        return this.httpInfo(queryDto).getData().getToken();
    }

    @Override
    public String getLoginUrl(LoginQueryDto queryDto) {
        try {
            XieDingResultDto resultDto = this.httpInfo(queryDto);
            String token     = resultDto.getData().getToken();
            String prefixUrl = resultDto.getPrefixUrl();
            return String.format(ssoConfig.getLoginUrl(), prefixUrl, token, queryDto.getSystemType());
        } catch (NullPointerException e) {
            throw new ServiceException(ResultStatus.ERROR.getStatus(), "获取第三登录请求出错!");
        }
    }

    /**
    * @Author lihui
    * @Description 请求信息
    * @Date 15:01 2021/4/19
    * @Param [queryDto]
    * @return com.zcxk.dto.thirdparty.XieDingResultDto
    **/
    private XieDingResultDto httpInfo(LoginQueryDto queryDto){
        LoginUser currentUser = UserUtil.getCurrentUser();
        String prefixUrl  = authMenuMapper.findLinkPath(currentUser.getTenantId(), queryDto.getMenuId());
        if (StringUtils.isEmpty(prefixUrl)) {
            throw new ServiceException(ResultStatus.ERROR.getStatus(), "未设置请求地址");
        }
        User user = userMapper.findThirdPartytLoginInfo(currentUser.getId());
        if (user == null || StringUtils.isEmpty(user.getLoginAccount())){
            throw new ServiceException(ResultStatus.ERROR.getStatus(), "未设置登录账号");
        }
        // 登录账号、登录密钥、厂家编码、机构编码
        String account   = user.getLoginAccount();
        String secretKey = user.getLoginSecretKey();
        String code      = user.getLoginCode();
        String orgCode   = user.getLoginOrgCode();
        Charset charset  = Charset.forName("utf-8");
        // 1.根据账户获取密码
        String result = HttpClientPoolUtil.sendGet(String.format(ssoConfig.getPwdUrl(), prefixUrl, account, orgCode), charset);
        XieDingResultDto resultDto = JSONObject.parseObject(result, XieDingResultDto.class);
        if (StringUtils.isEmpty(resultDto.getData().getPassword())) {
            throw new ServiceException(ResultStatus.ERROR.getStatus(), resultDto.getMessage());
        }

        // 2.绑定单点登陆用户
        result    = HttpClientPoolUtil.sendGet(String.format(ssoConfig.getBindSingleUrl(), prefixUrl, account, resultDto.getData().getPassword(), orgCode), charset);
        resultDto = JSONObject.parseObject(result, XieDingResultDto.class);
        if (!resultDto.isSuccess()) {
            throw new ServiceException(ResultStatus.ERROR.getStatus(), resultDto.getMessage());
        }
        // 3.获取token
        String singleKey = resultDto.getData().getSingleKey();
        Long timestamp   = System.currentTimeMillis();
        String sign      = MD5Util.digest(resultDto.getData().getSingleKey() + timestamp + secretKey);
        result    = HttpClientPoolUtil.sendGet(String.format(ssoConfig.getTokenUrl(), prefixUrl, singleKey, timestamp, sign, code), charset);
        resultDto = JSONObject.parseObject(result, XieDingResultDto.class);
        if (!resultDto.isSuccess()) {
            throw new ServiceException(ResultStatus.ERROR.getStatus(), resultDto.getMessage());
        }
        // 设置请求的前缀
        resultDto.setPrefixUrl(prefixUrl);
        return resultDto;
    }
}
