package com.qmth.sop.business.sync;

import com.alibaba.fastjson.JSONObject;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.service.SysConfigService;
import com.qmth.sop.business.sync.been.rtzf.LoginTypeEnum;
import com.qmth.sop.business.sync.been.rtzf.RtzfResult;
import com.qmth.sop.business.sync.been.rtzf.RtzfToken;
import com.qmth.sop.business.sync.been.rtzf.RtzfUserInfo;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.util.HttpUtil;
import com.qmth.sop.common.util.JacksonUtil;
import io.swagger.annotations.ApiModelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 软通智服开放接口工具类
 * @Author: CaoZixuan
 * @Date: 2023-11-07
 */
@Component
public class RtzfApiUtils {
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private CommonUtils commonUtils;

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

    @ApiModelProperty("用户登录 url")
    final String loginUrl = "https://qmth.echo-isoftstone.com/tenant/login/password/or/code/login";

    @ApiModelProperty("接口访问默认账号")
    final String defaultAccount = "?";

    @ApiModelProperty("接口访问默认密码")
    final String defaultPassword = "";

    @ApiModelProperty("租户id")
    final String tenantId = "";

    /**
     * 获取软通token
     *
     * @param requestUser 当前请求用户
     * @param loginType   登录方式
     * @return token
     */
    public String getRtzfToken(SysUser requestUser, LoginTypeEnum loginType) {
        try {
            String account = null;
            String password = null;
            switch (loginType) {
                case API_LOGIN:
                    account = defaultAccount;
                    password = defaultPassword;
                    break;
                case SSO_LOGIN:
//                    account = String.valueOf(requestUser.getId());
//                    password = requestUser.getPassword();
                    account = "18903719928";
                    password = "zgFX6eUFrx89xEW1J8OpxAeVZ7uY2u4VVQsFQc9//sY=";
                    break;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("account", commonUtils.validParam(account, null, true, "账号"));
            map.put("password", commonUtils.validParam(password, null, true, "密码"));
            map.put("loginType", commonUtils.validParam(0L, 0L, true, "登录方式"));
            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(loginUrl, requestJson, null, null, false);
            RtzfResult rtzfResult = JSONObject.parseObject(result, RtzfResult.class);
            if (Objects.isNull(rtzfResult) || !"0".equals(rtzfResult.getCode())) {
                throw ExceptionResultEnum.ERROR.exception("用户登录获取token失败 : " + rtzfResult.getMsg());
            }
            JSONObject data = rtzfResult.getData();
            if (Objects.isNull(data)){
                throw ExceptionResultEnum.ERROR.exception("用户登录获取token失败 : 未能解析data数据");
            }
            String token = data.getString("token");
            if (token == null || token.length() == 0) {
                throw ExceptionResultEnum.ERROR.exception("用户登录获取token为空");
            }
            return token;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 批量推送用户
     *
     * @param requestUser      请求用户
     * @param rtzfUserInfoList 用户信息集合
     */
    public void pushUserBatch(SysUser requestUser, List<RtzfUserInfo> rtzfUserInfoList) {
        try {
            String token = this.getRtzfToken(requestUser, LoginTypeEnum.API_LOGIN);

            Map<String, Object> map = new HashMap<>();
            map.put("tenantId", commonUtils.validParam(tenantId, null, true, "租户 ID"));
            map.put("userList", rtzfUserInfoList);
            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(loginUrl, requestJson, token, null, false);
            RtzfResult rtzfResult = JSONObject.parseObject(result, RtzfResult.class);
            if (Objects.isNull(rtzfResult) || !"0".equals(rtzfResult.getCode())) {
                throw ExceptionResultEnum.ERROR.exception("账号信息批量同步失败 : " + rtzfResult.getMsg());
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }

    /**
     * 用户信息更新
     *
     * @param requestUser  请求用户
     * @param rtzfUserInfo 用户信息
     */
    public RtzfResult updateUser(SysUser requestUser, RtzfUserInfo rtzfUserInfo) {
        try {
            String token = this.getRtzfToken(requestUser, LoginTypeEnum.API_LOGIN);

            Map<String, Object> map = new HashMap<>();
            map.put("tenantId", commonUtils.validParam(tenantId, null, true, "租户 ID"));
            map.put("userInfo", rtzfUserInfo);
            String requestJson = JacksonUtil.parseJson(map);

            String result = HttpUtil.postJson(loginUrl, requestJson, token, null, false);
            RtzfResult rtzfResult = JSONObject.parseObject(result, RtzfResult.class);
            return rtzfResult;
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        }
    }
}
