package com.ruoyi.file.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.qiwenshare.common.anno.MyLog;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.file.api.IUserLoginInfoService;
import com.ruoyi.file.component.JwtComp;
import com.ruoyi.file.domain.UserLoginInfo;
import com.ruoyi.file.vo.user.UserLoginVo;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.LocaleResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


//@Tag(name = "user", description = "该接口为用户接口，主要做用户登录，注册和校验token")
@Api(tags = "4 网盘用户接口")
@ApiSupport(order = 4)
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysLoginService loginService;

    @Resource
    ISysUserService userService;

    @Resource
    IUserLoginInfoService userLoginInfoService;

    @Resource
    JwtComp jwtComp;

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    public static Map<String, String> verificationCodeMap = new HashMap<>();


    public static final String CURRENT_MODULE = "用户管理";

    /*@Operation(summary = "用户注册", description = "注册账号", tags = {"user"})
    @PostMapping(value = "/register")
    @MyLog(operation = "用户注册", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> addUser(@Valid @RequestBody RegisterDTO registerDTO) {
        RestResult<String> restResult = null;
        UserBean userBean = new UserBean();
        BeanUtil.copyProperties(registerDTO, userBean);
        restResult = userService.registerUser(userBean);

        return restResult;
    }*/

    //@Operation(summary = "用户登录", description = "用户登录认证后才能进入系统", tags = {"user"})
    @ApiOperation(value = "4.1 用户登录")
    @ApiOperationSupport(order = 1)
    @GetMapping("/login")
    @MyLog(operation = "用户登录", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UserLoginVo> userLogin(
            @Parameter(description = "登录手机号") String telephone,
            @Parameter(description = "登录密码") String password,
            HttpServletRequest request,
            HttpServletResponse response){
        RestResult<UserLoginVo> restResult = new RestResult<UserLoginVo>();

        // 生成令牌
        String token = loginService.login(telephone, password, null, null, request);

        //读取配置文件
        if (com.ruoyi.common.utils.StringUtils.isNotNull(token) && com.ruoyi.common.utils.StringUtils.isNotEmpty(token)){
            SysUser sysUser = userService.selectUserByUserName(telephone);
            if (sysUser != null) {
                String langStr  = sysUser.getLanguage();
                if (langStr == null || langStr == ""){
                    langStr = "zh";
                }
                Locale locale = new Locale(langStr);
                localeResolver.setLocale(request, response, locale);
                // 保存用户语言到redis中
                redisCache.setCacheObject(Constants.USER_LANGUAGE_KEY + sysUser.getUserId(), langStr);

                UserLoginVo userLoginVo = new UserLoginVo();
                BeanUtil.copyProperties(sysUser, userLoginVo);
                //userLoginVo.setToken("Bearer " + token);
                userLoginVo.setToken(token);
                restResult.setData(userLoginVo);
                restResult.setSuccess(true);
                restResult.setCode(200001);
            }
        }

        return restResult;

    }

    //@Operation(summary = "检查用户登录信息", description = "验证token的有效性", tags = {"user"})
    @ApiOperation(value = "4.2 检查用户登录信息")
    @ApiOperationSupport(order = 2)
    @GetMapping("/checkuserlogininfo")
    @ResponseBody
    public RestResult<UserLoginVo> checkUserLoginInfo(@RequestHeader("token") String token) {
        UserLoginVo userLoginVo = new UserLoginVo();
        LoginUser loginUser = tokenService.getLoginUserByToken(token);
        if (loginUser != null) {
            Long userId = loginUser.getUserId();
//            LambdaQueryWrapper<UserLoginInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(UserLoginInfo::getUserId, loginUser);
//            lambdaQueryWrapper.likeRight(UserLoginInfo::getUserloginDate, DateUtil.getCurrentTime().substring(0, 10));
//            userLoginInfoService.remove(lambdaQueryWrapper);
//            UserLoginInfo userLoginInfo = new UserLoginInfo();
//            userLoginInfo.setUserId(userId);
//            userLoginInfo.setUserloginDate(DateUtil.getCurrentTime());
//            userLoginInfoService.save(userLoginInfo);
            SysUser user = userService.selectUserById(userId);
            /*BeanUtil.copyProperties(user, userLoginVo);*/
            if (StringUtils.isEmpty(user.getWxOpenId())) {
                userLoginVo.setHasWxAuth(false);
            } else {
                userLoginVo.setHasWxAuth(true);
            }
            userLoginVo.setUserId(user.getUserId());
            userLoginVo.setUsername(user.getUserName());
            userLoginVo.setHasWxAuth(false);

            return RestResult.success().data(userLoginVo);

        } else {
            return RestResult.fail().message("用户暂未登录");
        }

    }

    //@Operation(summary = "检查微信认证", description = "检查微信认证", tags = {"user"})
    @GetMapping("/checkWxAuth")
    @ResponseBody
    public RestResult<Boolean> checkWxAuth() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        if (loginUser != null && !"anonymousUser".equals(loginUser.getUsername())) {
            SysUser user = userService.selectUserById(loginUser.getUserId());

            if (StringUtils.isEmpty(user.getWxOpenId())) {
                return RestResult.success().data(false);
            } else {
                return RestResult.success().data(true);
            }

        } else {
            return RestResult.fail().message("用户暂未登录");
        }

    }

}
