package com.taais.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 com.taais.common.core.constant.UserConstants;
import com.taais.common.core.core.domain.CommonResult;
import com.taais.common.core.core.domain.model.LoginBody;
import com.taais.common.core.core.domain.model.RegisterBody;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.MessageUtils;
import com.taais.common.core.utils.StreamUtils;
import com.taais.common.core.utils.StringUtils;
import com.taais.common.core.utils.ValidatorUtils;
import com.taais.common.encrypt.annotation.ApiEncrypt;
import com.taais.common.json.utils.JsonUtils;
import com.taais.system.domain.SysClient;
import com.taais.system.domain.bo.SysTenantBo;
import com.taais.system.domain.vo.SysTenantVo;
import com.taais.system.service.ISysClientService;
import com.taais.system.service.ISysTenantService;
import com.taais.web.domain.vo.LoginTenantVo;
import com.taais.web.domain.vo.LoginVo;
import com.taais.web.domain.vo.TenantListVo;
import com.taais.web.service.IAuthStrategy;
import com.taais.web.service.SysLoginService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 static com.taais.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;

    /**
     * 登录方法
     *
     * @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());

        // 登录
        return CommonResult.success(IAuthStrategy.login(body, client, grantType));
    }

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

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult<Void> register(@Validated @RequestBody RegisterBody user) {
        log.info(user.getUserType());
        //if (!configService.selectRegisterEnabled(user.getTenantId()))
        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);
    }
}
