package org.dromara.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.auth.domain.vo.LoginTenantVo;
import org.dromara.auth.domain.vo.LoginVo;
import org.dromara.auth.domain.vo.TenantListVo;
import org.dromara.auth.form.RegisterBody;
import org.dromara.auth.form.SocialLoginBody;
import org.dromara.auth.service.IAuthStrategy;
import org.dromara.auth.service.SxzwfwLoginService;
import org.dromara.auth.service.SysLoginService;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginBody;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.*;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.social.config.properties.SocialLoginConfigProperties;
import org.dromara.common.social.config.properties.SocialProperties;
import org.dromara.common.social.utils.SocialUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.resource.api.RemoteMessageService;
import org.dromara.system.api.*;
import org.dromara.system.api.domain.vo.RemoteClientVo;
import org.dromara.system.api.domain.vo.RemoteTenantVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.rmi.server.ServerCloneException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class TokenController {

    private final SocialProperties socialProperties;
    private final SysLoginService sysLoginService;
    private final ScheduledExecutorService scheduledExecutorService;

    @DubboReference(timeout = 20000)
    private final RemoteConfigService remoteConfigService;
    @DubboReference(timeout = 20000)
    private final RemoteTenantService remoteTenantService;
    @DubboReference(timeout = 20000)
    private final RemoteClientService remoteClientService;
    @DubboReference(timeout = 20000)
    private final RemoteSocialService remoteSocialService;
    @DubboReference(stub = "true",timeout = 20000)
    private final RemoteMessageService remoteMessageService;
    @DubboReference(timeout = 20000)
    private final RemoteDictService remoteDictService;
    @DubboReference(timeout = 20000)
    private final RemoteUserService remoteUserService;

    @Autowired
    private SxzwfwLoginService sxzwfwLoginService;


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) throws ServerCloneException {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo) || !StringUtils.contains(clientVo.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(clientVo.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        //租户由委办局通过字典获取
        String wbjKey = loginBody.getWbjKey();
        if (wbjKey != null) {
            List<RemoteTenantVo> remoteTenantVos = remoteTenantService.queryList();
            for (RemoteTenantVo remoteTenantVo : remoteTenantVos) {
                if (wbjKey.equals(remoteTenantVo.getDomain())) {
                    loginBody.setTenantId(remoteTenantVo.getTenantId());
                }
            }
        }
        // 校验租户
        sysLoginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, clientVo, grantType);
        RedisUtils.setCacheObject("loginUrl" + LoginHelper.getUserId(), loginBody.getLoginUrl());
        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            remoteMessageService.publishMessage(userId, "欢迎登录专家库集约化管理平台");
        }, 3, TimeUnit.SECONDS);
        return R.ok(loginVo);
    }


    @PostMapping("tenant/login")
    public R<LoginVo> loginByTenantId(@RequestBody String body) throws ServerCloneException {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);

        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(clientVo)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(clientVo.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        sysLoginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, clientVo, grantType);
        RedisUtils.setCacheObject("loginUrl" + LoginHelper.getUserId(), loginBody.getLoginUrl());
        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            remoteMessageService.publishMessage(userId, "欢迎登录专家库集约化管理平台");
        }, 3, TimeUnit.SECONDS);
        return R.ok(loginVo);
    }

    @RequestMapping("/userCenter/callback")
    public R<LoginVo> userCenter(
                                 @RequestParam String clientId,
                                 @RequestParam String accessLink,
                                 @RequestParam Integer acctType, String tenantId, String wbjKey) {

        log.error("山西政务服务平台回调成功==========》");
        log.error("clientId：{}", clientId);
        log.error("accessLink：{}", accessLink);
        log.error("acctType：{}", acctType);
        log.error("tenantId：{}", tenantId);
        log.error("wbj：{}", wbjKey);


        if (StringUtils.isEmpty(clientId) || StringUtils.isEmpty(accessLink)) {
            return null;
        }
        if (acctType == null || acctType != 10) {
            throw new ServiceException("法人无法登陆此系统。");
        }
        try {
            //租户由委办局通过字典获取
            if (!StringUtils.isBlank(wbjKey)) {
                List<RemoteTenantVo> remoteTenantVos = remoteTenantService.queryList();
                for (RemoteTenantVo remoteTenantVo : remoteTenantVos) {
                    if (wbjKey.equals(remoteTenantVo.getDomain())) {
                        tenantId = remoteTenantVo.getTenantId();
                    }
                }
            }
            return R.ok(sxzwfwLoginService.sxzwfwUserInfo(null, clientId, accessLink, acctType, tenantId));
        } catch (Exception e) {
            throw new ServiceException("登陆失败请重试"+e.getMessage());
        }

    }

    @GetMapping("/goto-sxzwfw")
    public R<String> gotoSxzwfw(String gotourl) {
        String s = sxzwfwLoginService.gotoSxzwfw(gotourl);
        return R.ok("", s);
    }


    /**
     * 第三方登录请求
     *
     * @param source 登录来源
     * @return 结果
     */
    @GetMapping("/binding/{source}")
    public R<String> authBinding(@PathVariable("source") String source,
                                 @RequestParam String tenantId, @RequestParam String domain) {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (ObjectUtil.isNull(obj)) {
            return R.fail(source + "平台账号暂不支持");
        }
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
        Map<String, String> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("domain", domain);
        map.put("state", AuthStateUtils.createState());
        String authorizeUrl = authRequest.authorize(Base64.encode(JsonUtils.toJsonString(map), StandardCharsets.UTF_8));
        return R.ok("操作成功", authorizeUrl);
    }

    /**
     * 第三方登录回调业务处理 绑定授权
     * @param loginBody 请求体
     * @return 结果
     */
    @PostMapping("/social/callback")
    public R<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
        // 获取第三方登录信息
        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
            loginBody.getSource(), loginBody.getSocialCode(),
            loginBody.getSocialState(), socialProperties);
        AuthUser authUserData = response.getData();
        // 判断授权响应是否成功
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }
        sysLoginService.socialRegister(authUserData);
        return R.ok();
    }


    /**
     * 取消授权
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock/{socialId}")
    public R<Void> unlockSocial(@PathVariable Long socialId) {
        Boolean rows = remoteSocialService.deleteWithValidById(socialId);
        return rows ? R.ok() : R.fail("取消授权失败");
    }

    /**
     * 登出方法
     */
    @PostMapping("logout")
    public R<String> logout() {
        sxzwfwLoginService.loginOut();
        String logout = sysLoginService.logout();
        return R.ok("成功", logout);
    }

    /**
     * 用户注册
     */
    @ApiEncrypt
    @PostMapping("register")
    public R<Void> register(@RequestBody RegisterBody registerBody) {
        if (!remoteConfigService.selectRegisterEnabled(registerBody.getTenantId())) {
            return R.fail("当前系统没有开启注册功能！");
        }
        // 用户注册
        sysLoginService.register(registerBody);
        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @SaIgnore
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        // 返回对象
        LoginTenantVo result = new LoginTenantVo();
        boolean enable = TenantHelper.isEnable();
        result.setTenantEnabled(enable);
        // 如果未开启租户这直接返回
        if (!enable) {
            return R.ok(result);
        }

        List<RemoteTenantVo> tenantList = remoteTenantService.queryList();
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        try {
            // 如果只超管返回所有租户
            if (LoginHelper.isSuperAdmin()) {
                result.setVoList(voList);
                return R.ok(result);
            }
        } catch (NotLoginException ignored) {
        }
        String username = LoginHelper.getUsername();
        if (!ObjectUtil.isEmpty(username)) {
            List<String> tenantIdList = remoteUserService.selectTenantIdsByUserName(username);
            assert voList != null;
            voList.removeIf(s ->
                tenantIdList.contains(s.getTenantId())
            );
        }

        // 获取域名
        String host;
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(request.getRequestURL().toString()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo ->
            StringUtils.equals(vo.getDomain(), host));
        result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return R.ok(result);
    }

}
