package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
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.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.*;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.*;
import org.dromara.common.json.utils.JsonUtils;
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.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysClientVo;
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.domain.vo.WxLoginVo;
import org.dromara.web.domain.vo.dto.UserLoginDTO;
import org.dromara.web.domain.vo.dto.WxRegisterDTO;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.dromara.web.service.SysRegisterService;
import org.dromara.zhishu.service.SignGeneratorService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
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")
@CrossOrigin(origins = "https://erp.newadmin.buzhiyushu.cn",maxAge = 3600)
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 ISysUserService userService;
    private final SignGeneratorService signGeneratorService;
    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.jscode2session-url}")
    private String loginUrl;


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    //@ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
//        System.out.println("body:" + body);
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        long timestamp1 = System.currentTimeMillis() / 1000;
        String sign = null;
        if (loginBody != null) {
            sign = signGeneratorService.generateCallbackSign(loginBody.getLogin_code(), timestamp1, "erp_callback_sk_7f8a9b2c4d5e6f1a3b7c9d2e4f5a6b8c");
        }


        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
//        System.out.println("===============" + grantType);
        SysClientVo client = clientService.queryByClientId(clientId);
//        System.out.println(client);
        // 查询不到 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 (SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        loginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);

        if (!StringUtils.isEmpty(loginBody.getLogin_code())){
            // 调用 ERP 回调 API
            try {
                //入口层
                String callbackUrl = "https://wallet.api.buzhiyushu.cn/api/oauth/erp/callback";
                URL url = new URL(callbackUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                connection.setRequestProperty("Accept", "application/json");

                // URL编码所有参数值
                StringBuilder postData = new StringBuilder();
                postData.append("login_code=").append(URLEncoder.encode(
                        String.valueOf(loginBody.getLogin_code()), "UTF-8"));
                postData.append("&erp_user_id=").append(URLEncoder.encode(
                        String.valueOf(LoginHelper.getUserId()), "UTF-8"));

                postData.append("&erp_token=").append(URLEncoder.encode(
                        String.valueOf(loginVo.getAccessToken()), "UTF-8"));
                postData.append("&erp_username=").append(URLEncoder.encode(
                        String.valueOf(userService.selectUserById(LoginHelper.getUserId()).getUserName()), "UTF-8"));
                postData.append("&timestamp=").append(URLEncoder.encode(
                        String.valueOf(timestamp1), "UTF-8"));
                postData.append("&sign=").append(URLEncoder.encode(
                        String.valueOf(sign), "UTF-8"));

                // 打印请求信息用于调试
                log.info("发送请求到: {}, 参数: {}", callbackUrl, postData.toString());

                byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
                connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

                try (OutputStream os = connection.getOutputStream()) {
                    os.write(postDataBytes);
                    os.flush();
                }

                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    log.error("ERP 回调 API 调用失败，状态码: {}", responseCode);

                    // 读取错误信息
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        log.error("错误响应: {}", response.toString());
                    }
                } else {
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        log.info("ERP 回调 API 调用成功，响应: {}", response.toString());
                    }
                }
                connection.disconnect();
            } catch (Exception e) {
                log.error("调用 ERP 回调 API 时发生异常", e);
            }
        }

        Long userId = LoginHelper.getUserId();
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage("欢迎登录知书图书助理后台管理系统");
            dto.setUserIds(List.of(userId));
            SseMessageUtils.publishMessage(dto);
        }, 5, TimeUnit.SECONDS);
//        System.out.println("000000000000" + loginVo);
        return R.ok(loginVo);
    }

    @PostMapping("/interFaceLogin")
    public R<LoginVo> interFaceLogin(InterfaceLoginBody loginBody){
//        System.out.println("body:" + loginBody);
        String clientId = loginBody.getClientId();
        SysClientVo client = clientService.queryByClientId(clientId);
        String phoneNumber = loginBody.getPhoneNumber();
        String password = loginBody.getPassword();
        SysUserVo userVo = userService.selectUserByPhonenumber(phoneNumber);
        if (userVo == null) {
            log.error("用户手机号 {} 未找到对应的用户记录", phoneNumber);
            throw new ServiceException("用户未找到对应的用户记录");
        }
        // 验证密码是否正确
        if (!BCrypt.checkpw(password, userVo.getPassword())) {
            log.error("用户密码不正确");
            throw new ServiceException("用户密码不正确");
        }
        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());
        loginVo.setPhoneNumber(phoneNumber);
        loginVo.setNickName(loginUser.getNickname());
        loginVo.setUserId(userVo.getUserId());
        return R.ok(loginVo);
    }


    /**
     * 获取跳转URL
     *
     * @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);
    }

    /**
     * 前端回调绑定授权(需要token)
     *
     * @param loginBody 请求体
     * @return 结果
     */
    @PostMapping("/social/callback")
    public R<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
        // 校验token
        StpUtil.checkLogin();
        // 获取第三方登录信息
        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();
    }


    /**
     * 取消授权(需要token)
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock/{socialId}")
    public R<Void> unlockSocial(@PathVariable Long socialId) {
        // 校验token
        StpUtil.checkLogin();
        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")
    @SaIgnore
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
//        if (!configService.selectRegisterEnabled(user.getTenantId())) {
//            return R.fail("当前系统没有开启注册功能！");
//        }
        registerService.register(user);
        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @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<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        try {
            // 如果只超管返回所有租户
            if (LoginHelper.isSuperAdmin()) {
                result.setVoList(voList);
                return R.ok(result);
            }
        } catch (NotLoginException ignored) {
        }

        // 获取域名
        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.equalsIgnoreCase(vo.getDomain(), host));
        result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return R.ok(result);
    }

    @SneakyThrows
    @PostMapping("/wxLogin")
    public ResponseEntity<WxLoginVo> wxLogin(@Valid @RequestBody UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        try {
            String requestUrl = loginUrl + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if (jsonObject.containsKey("openid") && jsonObject.containsKey("session_key")) {
                String openid = jsonObject.getString("openid");
                String sessionKey = jsonObject.getString("session_key");
                String token = generateToken(openid, sessionKey);
                WxLoginVo loginVo = new WxLoginVo();
                loginVo.setOpenid(openid);
                loginVo.setToken(token);
                return ResponseEntity.ok(loginVo);
            } else {
                return ResponseEntity.badRequest().build();
            }
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    private String generateToken(String openid, String sessionKey) {
        return openid + "_" + sessionKey;
    }

    @PostMapping("/wxRegister")
    @SaIgnore
    public R<Void> wxRegister(@RequestBody WxRegisterDTO wxRegisterDTO) {
        registerService.WxRegister(wxRegisterDTO);
        return R.ok();
    }

    @PostMapping("/getUserName")
    @SaIgnore
    public List<SysUserVo> getUserName() {
        return userService.selectUserName();
    }

    @GetMapping("/autoLogin")
    @SaIgnore
    public ModelAndView autoLoginGet(@RequestParam("userId") Long userId, HttpServletResponse response) throws IOException {
//        System.out.println("开始自动登录流程 - 用户ID: " + userId);
        // 1. 查询用户
        SysUserVo user = userService.selectUserByUserId(userId);
        System.out.println("获取用户信息结果: " + (user != null ? "成功" : "失败"));
//        System.out.println("用户信息: " + user);
        // 2. 构建LoginUser
        LoginUser loginUser = loginService.buildLoginUser(user);
        loginUser.setClientKey("pc");
        loginUser.setDeviceType("pc");
        SaLoginModel model = new SaLoginModel();
        model.setDevice("pc");
        model.setTimeout(604800);
        model.setActiveTimeout(1800);
        model.setExtra(LoginHelper.CLIENT_KEY, "e5cd7e4891bf95d1d19206ce24a7b32e");
        LoginHelper.login(loginUser, model);
        String token = StpUtil.getTokenValue();
        Cookie cookie = new Cookie("satoken", token);
        cookie.setPath("/");
        cookie.setMaxAge(604800);
        response.addCookie(cookie);
        response.setHeader("Authorization", "Bearer " + token);
//        System.out.println("登录完成，token: " + StpUtil.getTokenValue());
        System.out.println("====进行跳转");
        System.out.println("准备跳转到首页");
        return new ModelAndView(new RedirectView("https://api.buzhiyushu.cn/reigsn?token=" + token));
    }

    @GetMapping("/test")
    @SaIgnore
    public ModelAndView test(HttpServletResponse response) throws IOException {
        System.out.println("开始测试登录流程");

        Long userId = 1L;
        // 1. 查询用户
        // 1. 查询用户
        SysUserVo user = userService.selectUserByUserId(userId);
        System.out.println("获取用户信息结果: " + (user != null ? "成功" : "失败"));
//        System.out.println("用户信息: " + user);
        // 2. 构建LoginUser
        LoginUser loginUser = loginService.buildLoginUser(user);
        loginUser.setClientKey("pc");
        loginUser.setDeviceType("pc");
        SaLoginModel model = new SaLoginModel();
        model.setDevice("pc");
        model.setTimeout(604800);
        model.setActiveTimeout(1800);
        model.setExtra(LoginHelper.CLIENT_KEY, "e5cd7e4891bf95d1d19206ce24a7b32e");
        LoginHelper.login(loginUser, model);

        String token = StpUtil.getTokenValue();
        Cookie cookie = new Cookie("satoken", token);
        cookie.setPath("/");
        cookie.setMaxAge(604800);
        response.addCookie(cookie);
        response.setHeader("Authorization", "Bearer " + token);
//        System.out.println("登录完成，token: " + StpUtil.getTokenValue());
        System.out.println("====进行跳转");
        System.out.println("准备跳转到首页");
        return new ModelAndView(new RedirectView("https://erp.buzhiyushu.cn/index?token=" + token));
    }




}
