package com.ruoyi.web.controller.system;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.annotation.Dev;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;

    private final WxMaService wxMaService;
    private final RuoYiConfig config;

    private final ISysConfigService configService;
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<?> login(@Validated @RequestBody LoginBody loginBody) {
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
            loginBody.getUuid());
        return R.map().put(Constants.TOKEN, token);
    }

    /**
     * 短信登录(示例)
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/smsLogin")
    public R<?> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        String token = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
        return R.map().put(Constants.TOKEN,token);
    }

    /**
     * 小程序登录(示例)
     *
     * @param xcxCode 小程序code
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/xcxLogin")
    public R<?> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
        String token = loginService.xcxLoginByOpenId(xcxCode);
        return R.map().put(Constants.TOKEN,token);
    }


    @SaIgnore
    @PostMapping("/openid")
    @Dev
    public R<?> xcxOpenid(@NotBlank(message = "{xcx.code.not.blank}") String openid) {
        String token = loginService.xcxLoginByOpenId(openid);
        return R.map().put(Constants.TOKEN,token);
    }


    @SaIgnore
    @PostMapping("/xcxRegLogin")
    public R<?> xcxRegLogin(@NotBlank(message = "{xcx.code.not.blank}") String code,
                            MultipartFile avatar,
                            @NotBlank(message = "{not.null}") String nickname,
                            @NotBlank(message = "邀请码不能为空") String regCode
                            ) {
        if(!regCode.equals(configService.selectConfigByKey("reg.code"))){
          throw new RuntimeException("邀请码不正确");
        }
        String token = loginService.xcxRegLoginByOpenid(code,avatar,nickname);
        return R.map().put(Constants.TOKEN,token);
    }


    @SaIgnore
    @PostMapping("/xcxRegLoginByOpenid")
    @Dev
    public R<?> xcxRegLoginByOpenid(String openid, MultipartFile avatar, String nickname) {
        String token = loginService.xcxRegLoginByOpenid(openid,avatar,nickname);
        return R.map().put(Constants.TOKEN,token);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout",method = {RequestMethod.POST,RequestMethod.GET})
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R<?> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        return R.map().put("user", user)
            .put("roles", loginUser.getRolePermission())
            .put("permissions", loginUser.getMenuPermission());
    }

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


    @Log(title = "获取微信手机号码", businessType = BusinessType.GRANT)
    @PostMapping("xcxPhone")
    @SaIgnore
    public R<?> xcxPhone(@NotBlank(message = "{xcx.code.not.blank}") String code) {
        try {

            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getNewPhoneNoInfo(code);
            WxMaConfigHolder.remove();//清理ThreadLocal
            return R.ok(phoneNoInfo);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }
}
