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.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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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);
        return BeanUtil.copyProperties(userEntity, MyResult.class)
                .setRoles(strings)
                .setMenus(menuResources)
                .setEndpoints(endpointResources)
                .setCompany(company)
                .setWechatOpenid(wechatOpenid != null ? wechatOpenid : "");
    }

}
