package com.njzscloud.supervisory.sys.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.security.module.password.PasswordLoginForm;
import com.njzscloud.common.security.module.wechat.mini.WechatMiniLoginForm;
import com.njzscloud.common.security.support.*;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.pojo.entity.BizDriverEntity;
import com.njzscloud.supervisory.biz.pojo.result.SearchCompanyResult;
import com.njzscloud.supervisory.sys.auth.mapper.AuthMapper;
import com.njzscloud.supervisory.sys.auth.pojo.result.MyResult;
import com.njzscloud.supervisory.sys.user.pojo.entity.UserEntity;
import com.njzscloud.supervisory.sys.user.pojo.param.UserRegisterParam;
import com.njzscloud.supervisory.sys.user.service.UserService;
import com.njzscloud.supervisory.wxPay.contant.WxApiConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService implements IUserService, IRoleService {
    private final AuthMapper authMapper;

    private final UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetail selectUser(PasswordLoginForm form) {
        JSONObject registerData = form.getRegisterData();
        if (registerData != null) {
            UserRegisterParam userRegisterParam = registerData.toJavaObject(UserRegisterParam.class);
            UserRegisterParam.Account account = userRegisterParam.getAccount();
            if (StrUtil.isBlank(userRegisterParam.getPhone())) {
                userRegisterParam.setPhone(account.getPhone());
                account.setPhone(null);
            }
            userService.register(userRegisterParam);
        }

        return authMapper.selectUser(Wrappers.query().eq("a.username", form.getAccount()).eq("a.deleted", 0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetail selectUser(WechatMiniLoginForm form) {
        String openid = form.getOpenid();
        String unionid = form.getUnionid();
        JSONObject registerData = form.getRegisterData();
        if (registerData != null) {
            UserRegisterParam userRegisterParam = registerData.toJavaObject(UserRegisterParam.class);
            UserRegisterParam.Account account = userRegisterParam.getAccount();
            account.setWechatOpenid(openid)
                    .setWechatUnionid(unionid);
            if (StrUtil.isBlank(userRegisterParam.getPhone())) {
                userRegisterParam.setPhone(account.getPhone());
            }
            userService.register(userRegisterParam);
        }
        return authMapper.selectUser(Wrappers.query().eq("a.wechat_openid", openid)
                .eq(StrUtil.isNotBlank(unionid), "a.wechat_unionid", unionid)
                .eq("a.deleted", 0));
    }

    @Override
    public Set<String> selectRoleByUserId(Long userId) {
        return authMapper.selectRoleByUserId(userId);
    }

    /**
     * 获取当前登录人信息
     */
    public UserDetail my() {
        Long userId = SecurityUtil.currentUserId();
        UserEntity userEntity = userService.getById(userId);
        List<MenuResource> menuResources = authMapper.selectUserMenu(userId);
        List<EndpointResource> endpointResources = authMapper.selectUserEndpoint(userId);
        SearchCompanyResult company = authMapper.selectCompanyInfo(userId);
        Set<String> strings = authMapper.selectRoleByUserId(userId);
        String wechatOpenid = authMapper.selectWechatOpenidByUserId(userId);
        BizDriverEntity driver = authMapper.getDriver(userId);
        return BeanUtil.copyProperties(userEntity, MyResult.class)
                .setRoles(strings)
                .setMenus(menuResources)
                .setEndpoints(endpointResources)
                .setCompany(company)
                .setDriver(driver)
                .setWechatOpenid(wechatOpenid != null ? wechatOpenid : "")
                .setWxAuthUrl(wxAuthUrl());
    }

    public String wxAuthUrl() {
        // 参数说明
        // 对回调地址进行URL编码至关重要[citation:1]
        String redirectUri = null;
        try {
            redirectUri = URLEncoder.encode(WxApiConfig.REDIRECT_URI, WxApiConfig.ENC);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 将authUrl返回给前端，引导用户跳转
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + WxApiConfig.APP_ID +
                "&redirect_uri=" + redirectUri +
                "&response_type=code" +
                "&scope=" + WxApiConfig.SCOPE +
                "&state=STATE#wechat_redirect";
    }

}
