package com.ruoyi.bar;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.ruoyi.bar.domain.BindBarUserVO;
import com.ruoyi.bar.domain.BindPhoneVO;
import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyWechatUser;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.bar.service.IWyBarUserService;
import com.ruoyi.bar.service.IWyWechatUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.WyBarUser;
import com.ruoyi.common.core.domain.model.BarLoginUser;
import com.ruoyi.common.core.domain.model.BarUserRegisterVO;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.config.WxMaProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;

/**
 * 酒吧Controller
 *
 * @author ruoyi
 * @date 2025-01-02
 */
@Api(tags = "酒吧方登录注册")
@RestController
@RequestMapping("/bar")
public class BarLoginController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(BarLoginController.class);
    @Resource
    private WxMaService wxMaService;
    @Resource
    private WxMaProperties wxMaProperties;
    @Resource
    private IWyWechatUserService wyWechatUserService;
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Resource
    private IWyBarService barService;

    @Resource
    private IWyBarUserService wyBarUserService;

//    @ApiOperation("酒吧方微信登录")
//    @PostMapping("/wxLogin")
//    public AjaxResult wxLogin(@RequestBody LoginBody loginBody)
//    {
//        AjaxResult ajax = AjaxResult.success();
//        // 生成令牌
//        String token = loginService.barLogin(loginBody.getUsername(), loginBody.getPassword());
//        ajax.put(Constants.TOKEN, token);
//        return ajax;
//    }

    @ApiOperation(value = "通过code获取小程序openId", notes = "通过code获取小程序openId")
    @GetMapping("/getOpenId")
    public AjaxResult getOpenId(@RequestParam(value = "code") String code) {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isBlank(code)) {
            return error("code不能为空");
        }
        try {
            final WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            log.info("code=" + code);
            log.info(sessionInfo.getSessionKey());
            final String openid = sessionInfo.getOpenid();
            log.info(openid);
            WyWechatUser wyWechatUser = wyWechatUserService.selectWyWechatUserByOpenId(openid);
            if (wyWechatUser == null) {
                log.warn("用户不存在,创建新微信用户");
                wyWechatUser = new WyWechatUser();
                wyWechatUser.setOpenId(openid);
                final WxMaProperties.Config config = wxMaProperties.getConfigs().get(0);
                wyWechatUser.setAppId(config.getAppid());
                wyWechatUserService.insertWyWechatUser(wyWechatUser);
            }
            final String token = loginService.wechatLogin(openid);
            ajax.put("openId", openid);
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 酒吧方登录(手机号、密码)
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("酒吧方登录(手机号、密码)")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.barLogin(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation(value = "手机号code登录", notes = "手机号code登录")
    @PostMapping("/phoneCodeLogin")
    public AjaxResult bindStudent(@Validated @RequestBody BindPhoneVO bind) {
        AjaxResult ajax = AjaxResult.success();
        try {
            final WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(bind.getCode());
            if (phoneNoInfo == null) {
                return AjaxResult.error("获取手机号失败");
            }
            String token = loginService.wechatPhoneLogin(phoneNoInfo.getPhoneNumber());
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 酒吧方注册
     *
     * @param registerVO 酒吧方注册
     * @return 结果
     */
    @ApiOperation("酒吧方注册")
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(@Validated @RequestBody BarUserRegisterVO registerVO) {
        log.debug("registerVo===================================: {} " ,registerVO);
        HashMap<String, Object> map = new HashMap<>();
        log.debug("开始认证==============================================");
        final WyBar register = barService.register(registerVO);
        //修改认证状态
        map.put("register", register);
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        log.debug("loginUser:======================================={}", loginUser);
        log.debug("openId:==============================={}",loginUser.getUser().getOpenId());
        final String barToken = loginService.wechatLogin(loginUser.getUser().getOpenId());
        map.put("token", barToken);
        return success(map);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("酒吧获取用户信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        WyBarUser user = loginUser.getUser();
        if (Objects.equals(user.getUserType(), UserType.WECHAT_USER.getCode())) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("user", user);
            ajax.put("roles", null);
            return ajax;
        }
        // 角色集合
        Set<String> roles = permissionService.getBarRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getBarMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshBarToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @ApiOperation(value = "绑定用户信息", notes = "绑定用户信息")
    @PostMapping("/bindBarUser")
    public AjaxResult bindStudent(@Validated @RequestBody BindBarUserVO bind) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        if (loginUser.getUser() == null) {
            return AjaxResult.error("未登录");
        }
        final WyBarUser user = loginUser.getUser();
        if (!Objects.equals(user.getUserType(), UserType.WECHAT_USER.getCode())) {
            return AjaxResult.error("非微信用户");
        }
        try {
            final WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(bind.getCode());
            if (phoneNoInfo == null) {
                return AjaxResult.error("获取手机号失败");
            }
            WyBarUser barUser = wyBarUserService.selectWyBarUserByPhoneNumber(phoneNoInfo.getPhoneNumber());
            if (barUser != null) {
                if (StringUtils.isNotBlank(barUser.getOpenId())) {
                    return AjaxResult.error("已绑定用户，请勿重复绑定");
                } else {
                    barUser.setOpenId(user.getUserName()); //未绑定用户前，用户的username就是openId
                    wyBarUserService.updateWyBarUser(barUser);
                }
                loginUser.setUser(barUser);
                loginUser.setPermissions(permissionService.getBarMenuPermission(barUser));
                tokenService.refreshBarToken(loginUser);
                return AjaxResult.success("绑定成功");
            } else {
//                barUser.setOpenId(user.getUserName()); //未绑定用户前，用户的username就是openId
//                barUser.setPhonenumber(phoneNoInfo.getPhoneNumber());
//                barUser.setNickName(phoneNoInfo.getPhoneNumber());
//                barUser.setUserName(phoneNoInfo.getPhoneNumber());
//                barUser.setBarId(0L);
//                barUser.setPassword(barService.getEncryptPassword(phoneNoInfo.getPhoneNumber()));
//                barUser.setUserType(UserType.WECHAT_USER.getCode());
//                wyBarUserService.insertWyBarUser(barUser);
                return AjaxResult.error("用户信息不存在，请联系管理员");
            }

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
//    @ApiOperation("品牌方获取路由信息")
//    @GetMapping("/getRouters")
//    public AjaxResult getRouters()
//    {
//        BreweryLoginUser loginUser = SecurityUtils.getBreweryLoginUser();
//        WyBreweryUser user = loginUser.getUser();
//        Long userId = user.getUserId();
//        List<WyBreweryMenu> menus = wyBreweryMenuService.selectMenuTreeByUserId(userId);
//        return AjaxResult.success(wyBreweryMenuService.buildMenus(menus));
//    }

}
