package com.bs.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bs.common.annotation.Anonymous;
import com.bs.common.annotation.Log;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.entity.*;
import com.bs.common.core.domain.model.LoginBody;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.StringUtils;
import com.bs.framework.web.service.SysLoginService;
import com.bs.framework.web.service.SysPermissionService;
import com.bs.framework.web.service.TokenService;
import com.bs.system.domain.SysUserRole;
import com.bs.system.mapper.SysRoleMapper;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.mapper.SysUserRoleMapper;
import com.bs.system.service.ISysMenuService;
import com.bs.system.service.ITenantConfigService;
import com.bs.web.utils.WeiXinUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author bs
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ITenantConfigService tenantConfigService;

    @Resource
    private WeiXinUtil weiXinUtil;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        TenantConfig tenantConfig = tenantConfigService.getOne(new LambdaQueryWrapper<TenantConfig>().eq(TenantConfig::getId, user.getTenantId()));
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if(tenantConfig==null){
            tenantConfig  = new TenantConfig();
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("tenantConfig", tenantConfig);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 登录方法
     * 传 微信Code：wxCode
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/getOpenId")
    @Log(title = "用户获取公众号id", businessType = BusinessType.GRANT)
    @ApiOperation(value = "获取openId，暂时无用")
    public AjaxResult getGzhOpenId(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        if (StringUtils.isEmpty(loginBody.getWxCode())) {
            return AjaxResult.error("请传入微信Code");
        }
        if (StringUtils.isEmpty(loginBody.getGzhCode())) {
            return AjaxResult.error("请传ghzCode");
        }
        JSONObject xcxJo = weiXinUtil.getXCXOpenId(loginBody.getWxCode());
        if (StringUtils.isEmpty(xcxJo.getString("openId"))) {
            return AjaxResult.error("code错误");
        }
        JSONObject gzhJo = null;
        gzhJo =  weiXinUtil.getGZHOpenId(loginBody.getGzhCode());
        return AjaxResult.success().put("openId", xcxJo.getString("openId"))
                .put("gzhOpenId", gzhJo.getString("openId")).put("unionId", xcxJo.getString("unionid"));

    }


    /**
     * 解绑微信信息
     * @return 结果
     */
    @PostMapping("/unbindWx")
    @ApiOperation(value = "解绑微信")
    @Log(title = "用户获取公众号id", businessType = BusinessType.GRANT)
    public AjaxResult unbindWx() {
        SysUser sysUser = sysUserMapper.selectById(SecurityUtils.getUserId());
        sysUser.setXcxOpenId("");
        sysUser.setGzhOpenId("");
        sysUser.setUnionId("");
        sysUserMapper.updateById(sysUser);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.getUser().setXcxOpenId("");
        loginUser.getUser().setGzhOpenId("");
        loginUser.getUser().setUnionId("");
        tokenService.refreshToken(loginUser);
        return AjaxResult.success("解绑成功").put("user",sysUser);
    }


    /**
     * 绑定微信信息
     * @return 结果
     */
    @PostMapping("/bindingWx")
    @ApiOperation(value = "绑定微信")
    @Log(title = "用户获取公众号id", businessType = BusinessType.GRANT)
    public AjaxResult bindingWx(@RequestBody LoginBody loginBody) {
        // 生成令牌
//        if (StringUtils.isEmpty(loginBody.getWxCode())) {
//            return AjaxResult.error("请传入微信Code");
//        }
        if (StringUtils.isEmpty(loginBody.getGzhCode())) {
            return AjaxResult.error("请传ghzCode");
        }
        JSONObject xcxJo = weiXinUtil.getXCXOpenId(loginBody.getWxCode());
//        if (StringUtils.isEmpty(xcxJo.getString("openId"))) {
//            return AjaxResult.error("微信code错误");
//        }
        JSONObject gzhJo = null;
        gzhJo =  weiXinUtil.getGZHOpenId(loginBody.getGzhCode());
        if (StringUtils.isEmpty(gzhJo.getString("openId"))) {
            return AjaxResult.error("公众号code错误");
        }
        //判断微信是否被其他用户绑定
        SysUser tempUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getGzhOpenId, gzhJo.getString("openId")));
        if (tempUser!=null) {
            return AjaxResult.error("此微信已被绑定");
        }
        SysUser updateUser = new SysUser();
        updateUser.setXcxOpenId("");
        if (StringUtils.isEmpty(loginBody.getWxCode())) {
            sysUserMapper.update(updateUser,new LambdaUpdateWrapper<SysUser>().eq(SysUser::getXcxOpenId, gzhJo.getString("openId")));
        } else {
            sysUserMapper.update(updateUser,new LambdaUpdateWrapper<SysUser>().eq(SysUser::getXcxOpenId, xcxJo.getString("openId")));
        }
        SysUser sysUser = sysUserMapper.selectById(SecurityUtils.getUserId());
        if(StringUtils.isNotEmpty(sysUser.getGzhOpenId())&&!sysUser.getGzhOpenId().equals(gzhJo.getString("openId"))){
            return AjaxResult.error("您的账号已经绑定过其他微信,请先解绑");
        }
        sysUser.setXcxOpenId(xcxJo.getString("openId"));
        sysUser.setGzhOpenId( gzhJo.getString("openId"));
        if (StringUtils.isEmpty(loginBody.getWxCode())) {
            sysUser.setUnionId(gzhJo.getString("unionid"));
        } else {
            sysUser.setUnionId(xcxJo.getString("unionid"));
        }
        sysUserMapper.updateById(sysUser);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.getUser().setXcxOpenId(sysUser.getXcxOpenId());
        loginUser.getUser().setGzhOpenId(sysUser.getGzhOpenId());
        loginUser.getUser().setUnionId(sysUser.getUnionId());
        tokenService.refreshToken(loginUser);
        return AjaxResult.success("绑定成功").put("user",sysUser);
    }

    /**
     * 登录方法
     * 传 微信Code：wxCode
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/wxlogin")
    @ApiOperation(value = "微信登入")
    @Anonymous
    public AjaxResult wxlogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        if (StringUtils.isEmpty(loginBody.getWxCode())) {
//            return AjaxResult.error("请传入微信Code");
        }
        SysUser sysUser;
        JSONObject xcxJo = new JSONObject();
        if (!StringUtils.isEmpty(loginBody.getWxCode())) {
            xcxJo = weiXinUtil.getXCXOpenId(loginBody.getWxCode());
        }
//        JSONObject xcxJo = weiXinUtil.getXCXOpenId(loginBody.getWxCode());
        if (StringUtils.isEmpty(xcxJo.getString("openId"))) {
//            return AjaxResult.error("code错误");
        }
        JSONObject gzhJo = new JSONObject();
        if(StringUtils.isNotEmpty(loginBody.getGzhCode())){
            gzhJo =  weiXinUtil.getGZHOpenId(loginBody.getGzhCode());
        }
        List<SysUser> lsUser = null;
        if (!StringUtils.isEmpty(loginBody.getWxCode())) {
            lsUser = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getXcxOpenId, xcxJo.getString("openId")));
        } else {
            lsUser = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getGzhOpenId, gzhJo.getString("openId")));
        }
//        List<SysUser> lsUser = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getXcxOpenId, xcxJo.getString("openId")));
        if (lsUser != null && lsUser.size() > 0) {
            sysUser = lsUser.get(0);
        } else {
            //没找到账号，需要手动绑定
            return AjaxResult.error("未查找到用户").put("code", "501").put("openId", xcxJo.getString("openId"))
                    .put("gzhOpenId", gzhJo.getString("openId")!=null?gzhJo.getString("openId"):"").put("unionId", xcxJo.getString("unionid"));
        }
        if(StringUtils.isEmpty(sysUser.getXcxOpenId())){
            if (StringUtils.isEmpty(loginBody.getWxCode())) {
                sysUser.setXcxOpenId(gzhJo.getString("openId"));
            } else {
                sysUser.setXcxOpenId(xcxJo.getString("openId"));
            }
        }
        if(StringUtils.isEmpty(sysUser.getGzhOpenId())){
            sysUser.setGzhOpenId(gzhJo.getString("openId")!=null?gzhJo.getString("openId"):"");
        }
        if(StringUtils.isEmpty(sysUser.getUnionId())){
            if (StringUtils.isEmpty(loginBody.getWxCode())) {
                sysUser.setUnionId(gzhJo.getString("unionid"));
            } else {
                sysUser.setUnionId(xcxJo.getString("unionid"));
            }
//            sysUser.setUnionId(xcxJo.getString("unionid"));
        }
        String token = setLoginUser(sysUser);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    public String setLoginUser(SysUser user) {
        LoginBody loginBody = new LoginBody();
        loginBody.setXcxOpenId(user.getXcxOpenId());
        //登入成功，查询租户配置
        if (null != user.getTenantId()) {
//            SysTenant tenant = tenantService.getById(user.getTenantId());
            SysTenant tenant = new SysTenant();
            TenantConfig config = tenantConfigService.getOne(new LambdaQueryWrapper<TenantConfig>().eq(TenantConfig::getId, "5"));
            if (config == null) {
                config = new TenantConfig();
                config.setIsUserAstrict("0");
                config.setIsOnLine("0");
                config.setIsDefinitionName("0");
                config.setIsDefinitionLogo("0");
                config.setIsDefinitionHue("0");
            }
            tenant.setTenantConfig(config);
            LoginUser loginUser = createLoginUser(user, tenant);
            loginService.recordLoginInfo(user.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        }
        LoginUser loginUser = createLoginUser(user, null);
        loginService.recordLoginInfo(user.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public LoginUser createLoginUser(SysUser user, SysTenant tenant) {
        //查询用户下的权限
        LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.select(SysUserRole::getRoleId);
        userRoleWrapper.eq(SysUserRole::getUserId,user.getUserId());
        List<Object> roleIds = sysUserRoleMapper.selectObjs(userRoleWrapper);
        //查询用户下的权限
        LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.in(SysRole::getRoleId,roleIds);
        user.setRoles(sysRoleMapper.selectList(roleWrapper));
        return new LoginUser(user.getUserId(),  user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    /**
     * 获取配置信息
     */
    @PostMapping("/getConfig")
    @Anonymous
    public AjaxResult getConfig(@RequestBody LoginBody loginBody)
    {
        Map<String, String> config = weiXinUtil.getConfig(loginBody.getUrl());
        return AjaxResult.success(config);
    }
}
