package org.dromara.web.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResource;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.zhyd.oauth.model.AuthCallback;
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 me.zhyd.oauth.utils.UuidUtils;
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.domain.model.LoginUser;
import org.dromara.common.core.domain.model.RegisterBody;
import org.dromara.common.core.domain.model.SocialLoginBody;
import org.dromara.common.core.utils.*;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
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.common.websocket.utils.WebSocketUtils;
import org.dromara.system.domain.SysClient;
import org.dromara.system.domain.bo.SysSocialBo;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysSocialVo;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.*;
import org.dromara.web.domain.vo.LoginTenantVo;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.domain.vo.TenantListVo;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.dromara.web.service.SysRegisterService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 认证
 *
 * @author Lion Li
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final SocialProperties socialProperties;
    private final SysLoginService loginService;
    private final SysRegisterService registerService;
    private final ISysConfigService configService;
    private final ISysTenantService tenantService;
    private final ISysSocialService socialUserService;
    private final ISysClientService clientService;
    private final ScheduledExecutorService scheduledExecutorService;
    private final ISysDeptService deptService;

    private final WxMaService wxMaService;
    private final ISysSocialService sysSocialService;
    private final ISysUserService sysUserService;

    private final ISysRoleService roleService;






    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClient client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        loginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);

        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            WebSocketUtils.sendMessage(userId, "欢迎登录RuoYi-Vue-Plus后台管理系统");
        }, 3, TimeUnit.SECONDS);
        return R.ok(loginVo);
    }

    /**
     * 第三方登录请求
     *
     * @param source 登录来源
     * @return 结果
     */
    @GetMapping("/binding/{source}")
    public R<String> authBinding(@PathVariable("source") String source,@RequestParam(required = false) String code) {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (ObjectUtil.isNull(obj)) {
            return R.fail(source + "平台账号暂不支持");
        }
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);

        if(source.equals("wechat_mini_program")){
            if(code==null) return  R.fail("请填写小程序code");
            AuthResponse<AuthUser> response = authRequest.login(AuthCallback.builder().code(code).build());
            AuthUser authUserData = response.getData();
            if (!response.ok()) {
                return R.fail(response.getMsg());
            }
            loginService.socialRegister(authUserData);
            return R.ok("操作成功");
        }
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        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());
        }
        loginService.socialRegister(authUserData);
        return R.ok();
    }


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


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

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


    @PostMapping("/loginByPhoneCodeAndLoginCode")
    public R<LoginVo> registerByPhonecode(@RequestBody String loginbody) throws WxErrorException {
        JSONObject jsonObject = JSONUtil.parseObj(loginbody);
        String logincode = jsonObject.getStr("logincode");
        String phonecode = jsonObject.getStr("phonecode");



        AuthRequest authRequest = SocialUtils.getAuthRequest("wechat_mini_program", socialProperties);
        AuthResponse<AuthUser> response = authRequest.login(AuthCallback.builder().code(logincode).build());
        AuthUser authUserData = response.getData();
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }

        wxMaService.switchover(socialProperties.getType().get("wechat_mini_program").getClientId());
        WxMaPhoneNumberInfo phone = wxMaService.getUserService().getPhoneNumber(phonecode);
        SysUserVo userVo = sysUserService.selectUserByUserName(phone.getPhoneNumber());
        if(userVo==null){
            //注册
            RegisterBody user = new RegisterBody();
            user.setUsername(phone.getPhoneNumber());
            user.setPassword(UuidUtils.getUUID().substring(0,6));
            user.setUserType("app_user");
            user.setPhonenumber(phone.getPhoneNumber());
            registerService.register(user);
            userVo =  sysUserService.selectUserByUserName(phone.getPhoneNumber());
        }

        try {
            SysUserBo bo = BeanUtil.toBean(userVo, SysUserBo.class);
            if (bo.getRoleIds() == null) {
                bo.setRoleIds(new Long[]{1763484977044361217L});
                bo.setPassword(null);
                bo.setUserType(null);
            } else {
                List<Long> a = Arrays.stream(bo.getRoleIds()).toList();
                if(!a.contains(1763484977044361217L)){
                    a.add(1763484977044361217L);
                }
                bo.setPassword(null);
                bo.setUserType(null);
                bo.setRoleIds((Long[]) a.toArray());

            }
            DataPermissionHelper.ignore(() -> sysUserService.updateUser(bo));
        }catch (Exception e){}

        //绑定微信
        SysSocialBo bo = BeanUtil.toBean(authUserData, SysSocialBo.class);
        String authId = authUserData.getSource() + authUserData.getUuid();
        BeanUtil.copyProperties(authUserData.getToken(), bo);
        bo.setUserId(userVo.getUserId());
        bo.setAuthId(authId);
        bo.setOpenId(authUserData.getUuid());
        bo.setUserName(authUserData.getUsername());
        bo.setNickName(authUserData.getNickname());
        // 查询是否已经绑定用户
        List<SysSocialVo> list = sysSocialService.selectByAuthId(authId);
        if (CollUtil.isEmpty(list)) {
            // 没有绑定用户, 新增用户信息
            sysSocialService.insertByBo(bo);
        } else {
            // 更新用户信息
            bo.setId(list.get(0).getId());
            sysSocialService.updateByBo(bo);
        }

        SysClient client = clientService.queryByClientId("e5cd7e4891bf95d1d19206ce24a7b32e");
        LoginUser loginUser = loginService.buildLoginUser(userVo);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());

        return R.ok(loginVo);

    }


    @PostMapping("/BC/loginByPhoneCodeAndLoginCode")
    public R<LoginVo> BcregisterByPhonecode(@RequestBody String loginbody) throws WxErrorException {
        JSONObject jsonObject = JSONUtil.parseObj(loginbody);
        String logincode = jsonObject.getStr("logincode");
        String phonecode = jsonObject.getStr("phonecode");



        AuthRequest authRequest = SocialUtils.getAuthRequest("wechat_mini_program_1", socialProperties);
        AuthResponse<AuthUser> response = authRequest.login(AuthCallback.builder().code(logincode).build());
        AuthUser authUserData = response.getData();
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }

        wxMaService.switchover(socialProperties.getType().get("wechat_mini_program_1").getClientId());
        WxMaPhoneNumberInfo phone = wxMaService.getUserService().getPhoneNumber(phonecode);
        SysUserVo userVo = sysUserService.selectUserByUserName(phone.getPhoneNumber());
        if(userVo==null){
            //注册
            RegisterBody user = new RegisterBody();
            user.setUsername(phone.getPhoneNumber());
            user.setPassword(UuidUtils.getUUID().substring(0,6));
            user.setUserType("app_user");
            user.setPhonenumber(phone.getPhoneNumber());
            registerService.register(user);
            userVo =  sysUserService.selectUserByUserName(phone.getPhoneNumber());
        }


        //定制班车普通用户角色
        Long roleId = 1889878542601625601L;

        try {
            SysUserBo bo = BeanUtil.toBean(userVo, SysUserBo.class);
            if (bo.getRoleIds() == null) {
                bo.setRoleIds(new Long[]{roleId});
                bo.setPassword(null);
                bo.setUserType(null);
            } else {
                List<Long> a = Arrays.stream(bo.getRoleIds()).toList();
                if(!a.contains(roleId)){
                    a.add(roleId);
                }
                bo.setPassword(null);
                bo.setUserType(null);
                bo.setRoleIds((Long[]) a.toArray());

            }
            DataPermissionHelper.ignore(() -> sysUserService.updateUser(bo));
        }catch (Exception e){}

        //绑定微信
        SysSocialBo bo = BeanUtil.toBean(authUserData, SysSocialBo.class);
        String authId = authUserData.getSource() + authUserData.getUuid();
        BeanUtil.copyProperties(authUserData.getToken(), bo);
        bo.setUserId(userVo.getUserId());
        bo.setAuthId(authId);
        bo.setSource("WECHAT_MINI_PROGRAM_1");
        bo.setOpenId(authUserData.getUuid());
        bo.setUserName(authUserData.getUsername());
        bo.setNickName(authUserData.getNickname());
        // 查询是否已经绑定用户
        List<SysSocialVo> list = sysSocialService.selectByAuthId(authId);
        if (CollUtil.isEmpty(list)) {
            // 没有绑定用户, 新增用户信息
            sysSocialService.insertByBo(bo);
        } else {
            // 更新用户信息
            bo.setId(list.get(0).getId());
            sysSocialService.updateByBo(bo);
        }

        SysClient client = clientService.queryByClientId("e5cd7e4891bf95d1d19206ce24a7b32e");
        LoginUser loginUser = loginService.buildLoginUser(userVo);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());

        return R.ok(loginVo);

    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        List<SysTenantVo> tenantList = tenantService.queryList(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.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        vo.setTenantEnabled(TenantHelper.isEnable());
        return R.ok(vo);
    }

}
