package com.njyunzhi.pet_identity.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.njyunzhi.pet_identity.common.*;
import com.njyunzhi.pet_identity.entity.SysUser;
import com.njyunzhi.pet_identity.service.ISysSettingService;
import com.njyunzhi.pet_identity.vo.ChangePassword;
import com.njyunzhi.pet_identity.vo.LoginParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@Api(tags = "登入/登出")
@RestController
public class LoginController extends BaseController {

    @Autowired
    ISysSettingService iSysSettingService;

    @PostMapping("/admin/login")
    @ApiOperation(value="登录", notes = "登录", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean login(@ApiParam("登录参数") @RequestBody LoginParam loginParam) throws Exception {
        if (null == loginParam) {
            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        String userName = loginParam.getUserName();
        String password = loginParam.getPassword();

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return ResponseBean.error("账户或密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        SysUser sysUser = iSysUserService.getExistBy("login_name", userName, false, true);
        if (null == sysUser) {
            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        if (sysUser.getStatus() != Constants.STATUS_NORMAL) {
            return ResponseBean.error("账户异常", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        if (!checkPassword(password, sysUser.getPassword(), sysUser.getUserId())) {
            return ResponseBean.error("账户或密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        sysUser.setPassword(null);

        Map<String, Object> res = new HashMap<>();
        res.put("user", sysUser);

        // 生成 token
        StpUtil.login(sysUser.getUserId(), Constants.LOGIN_TYPE_ADMIN);
        res.put("token", StpUtil.getTokenValue());

        return ResponseBean.success(res);
    }

    @GetMapping("/admin/currentUser")
    @ApiOperation(value="当前用户", notes = "当前用户", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean getCurrentUser() throws Exception {
        Map<String, Object> res = new HashMap<>();

        SysUser sysUser = currentUser();

        if (sysUser.getStatus() != Constants.STATUS_NORMAL) {
            return ResponseBean.error("账户异常", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        sysUser.setPassword(null);
        res.put("user", sysUser);

        return ResponseBean.success(res);
    }

    @PostMapping("/admin/logout")
    @ApiOperation(value="登出", notes = "登出", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean logout() throws Exception {
        StpUtil.logout();
        return ResponseBean.success("success");
    }

    @GetMapping("/401")
    @ApiOperation(value="401无权限", notes = "401无权限", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean unAuth(@RequestParam(value = "msg", defaultValue = "未登录或暂无权限") String msg) throws Exception {
        return ResponseBean.error(msg, ResponseBean.ERROR_AUTH_FAIL);
    }

    @PutMapping("/admin/change-password")
    @ApiOperation(value="修改密码", notes = "修改密码", httpMethod = "PUT", response = ResponseBean.class)
    public ResponseBean changePassword(@ApiParam("修改密码参数") @RequestBody ChangePassword param) throws Exception {
        if (StringUtils.isEmpty(param.getOriginPassword()) || StringUtils.isEmpty(param.getNewPassword())) {
            return ResponseBean.error("原始密码或新密码不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        SysUser currentUser = currentUser();

        if (!checkPassword(param.getOriginPassword(), currentUser.getPassword(), currentUser.getUserId())) {
            return ResponseBean.error("原始密码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        currentUser.setPassword(EncryptUtils.md5(param.getNewPassword(), currentUser.getUserId()));
        iSysUserService.updateById(currentUser);

        return ResponseBean.success("密码修改成功");
    }

    private boolean checkPassword(String src, String targ, String salt) {
        return EncryptUtils.md5(src, salt).equals(targ);
    }
}
