package org.eco.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eco.common.core.constant.UserConstants;
import org.eco.common.core.core.domain.CommonResult;
import org.eco.common.core.core.domain.model.LoginBody;
import org.eco.common.core.core.domain.model.RegisterBody;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.common.core.utils.MessageUtils;
import org.eco.common.core.utils.StreamUtils;
import org.eco.common.core.utils.StringUtils;
import org.eco.common.core.utils.ValidatorUtils;
import org.eco.common.encrypt.annotation.ApiEncrypt;
import org.eco.common.json.utils.JsonUtils;
import org.eco.common.security.utils.LoginHelper;
import org.eco.common.websocket.dto.WebSocketMessageDto;
import org.eco.common.websocket.utils.WebSocketUtils;
import org.eco.system.domain.SysClient;
import org.eco.system.domain.bo.SysTenantBo;
import org.eco.system.domain.vo.SysTenantVo;
import org.eco.system.service.ISysClientService;
import org.eco.system.service.ISysTenantService;
import org.eco.web.domain.vo.LoginTenantVo;
import org.eco.web.domain.vo.LoginVo;
import org.eco.web.domain.vo.TenantListVo;
import org.eco.web.service.IAuthStrategy;
import org.eco.web.service.SysLoginService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static org.eco.system.domain.table.SysClientTableDef.SYS_CLIENT;


/**
 * So-token 认证
 *
 * @author wgk
 */
@Slf4j
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private SysLoginService loginService;
    @Resource
    private ISysClientService clientService;
    @Resource
    private ISysTenantService tenantService;
    @Resource
    private ScheduledExecutorService scheduledExecutorService;

    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public CommonResult<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        assert loginBody != null;
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        QueryWrapper query = QueryWrapper.create().from(SYS_CLIENT).where(SYS_CLIENT.CLIENT_ID.eq(clientId));
        SysClient client = clientService.getOne(query);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return CommonResult.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(client.getStatus())) {
            return CommonResult.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        loginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);
        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            WebSocketMessageDto dto = new WebSocketMessageDto();
            dto.setMessage("欢迎登录");
            dto.setSessionKeys(List.of(userId));
            WebSocketUtils.publishMessage(dto);
        }, 3, TimeUnit.SECONDS);
        // 登录
        return CommonResult.success(loginVo);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public CommonResult<Void> logout() {
        loginService.logout();
        return CommonResult.success("退出成功！");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult<Void> register(@Validated @RequestBody RegisterBody user) {
        //if (!configService.selectRegisterEnabled(user.getTenantId())) // TODO：注册代码
//        {
        log.info(user.getUserType());
        return CommonResult.fail("当前系统没有开启注册功能！");
//        }
//        registerService.register(user);
//        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @GetMapping("/tenant/list")
    public CommonResult<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        List<SysTenantVo> tenantList = tenantService.selectList(new SysTenantBo());
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        // 获取域名
        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));
        // 返回对象
        LoginTenantVo vo = new LoginTenantVo();
        vo.setTenantEnabled(true);
        vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return CommonResult.success(vo);
    }
}
