package com.bcrjl.miwifi.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.bcrjl.miwifi.common.response.R;
import com.bcrjl.miwifi.common.util.MiWifiUtil;
import com.bcrjl.miwifi.model.param.LoginParam;
import com.bcrjl.miwifi.service.DeviceDayTrafficService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 鉴权服务
 *
 * @author yanqs
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private DeviceDayTrafficService deviceDayTrafficService;
    @Resource
    private MiWifiUtil miWifiUtil;

    /**
     * 系统密码
     */
    @Value("${bmw.web-password:123456}")
    private String PASSWORD;

    /**
     * 系统登录
     *
     * @param param 密码
     * @return token
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginParam param) {
        if (SecureUtil.md5(PASSWORD).equals(param.getPassword())) {
            Map<String, Object> loginInfo = miWifiUtil.getLoginInfo();
            if (Objects.isNull(loginInfo)) {
                return R.fail("无法链接路由器信息");
            }
            StpUtil.login(10001);
            deviceDayTrafficService.initTraffic();
            return R.data(StpUtil.getTokenInfo());
        } else {
            return R.fail("密码错误：");
        }
    }
}
