package com.system.oauth.system.controller;

import com.system.framework.core.response.StarBosResult;
import com.system.oauth.system.entity.SysUserAccount;
import com.system.oauth.system.service.ISysRoleService;
import com.system.oauth.system.service.ISysUserService;
import com.system.oauth.utils.JacksonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "用户账号管理")
@RestController
@Slf4j
@RequestMapping("userAccount")
public class SysUserAccountController {

    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("findRoleByUser")
    @ApiOperation(value = "userAccount-查询账号角色", notes = "userAccount-查询账号角色")
    public StarBosResult<List<String>> findRoleByUser(@RequestParam(name = "userId") Long userId) {
        StarBosResult<List<String>> result = new StarBosResult<>();
        SysUserAccount byId = userService.getById(userId);
        if (byId == null) {
            result.error500("未找到对应实体");
        } else {
            List<String> maps = roleService.selectRoleByUserId(userId);
            System.out.println(maps);
            result.successOk(maps);
        }
        return result;
    }

    @PostMapping("reset_password")
    public Object resetByMobile(@RequestBody String body, HttpServletRequest request) {
        String password = JacksonUtil.parseString(body, "password");
        String account = JacksonUtil.parseString(body, "account");

        if (account == null || password == null) {
            return StarBosResult.badArgument();
        }

        //判断验证码是否正确
//        String cacheCode = CaptchaCodeManager.getCachedCaptcha(mobile);
//        if (cacheCode == null || cacheCode.isEmpty() || !cacheCode.equals(code)) {
//            return ResponseUtil.fail(AUTH_CAPTCHA_UNMATCH, "验证码错误");
//        }
        SysUserAccount accountUser = userService.findByUsername(account);
        SysUserAccount user = null;
        if (accountUser == null) {
            return StarBosResult.fail(500, "账号不存在");
        } else {
            user = accountUser;
        }
        String encodedPassword = passwordEncoder.encode(password);
        SysUserAccount sysUserAccount = new SysUserAccount();
        sysUserAccount.setId(user.getId());
        sysUserAccount.setPassword(encodedPassword);

        if (!userService.updateById(sysUserAccount)) {
            return StarBosResult.fail("数据更新失败");
        }

        return StarBosResult.ok();
    }


}
