package com.example.demo.admin.module.admin;

import com.example.demo.admin.common.ResponseDTO;
import com.example.demo.admin.interceptor.AdminInterceptor;
import com.example.demo.admin.table.AdminUser;
import org.springframework.web.bind.annotation.*;
import pers.jc.engine.JCEngine;
import pers.jc.util.JCUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * 后台控制器-管理员相关
 */
@CrossOrigin
@RestController
@RequestMapping("admin/admin")
public class AdminController {

    @PostMapping("login")
    public ResponseDTO login(String username, String password, String userMsg) {
        ResponseDTO responseDTO = new ResponseDTO();
        AdminUser superAdmin = AdminService.ins.getSuperAdmin();
        if (
            superAdmin.getUsername().equals(username) &&
            superAdmin.getPassword().equals(password)
        ) {
            //更新token
            superAdmin.setToken(JCUtil.uuid());
            AdminService.ins.updateSuperAdmin(superAdmin);
            //返回结果-登录成功
            responseDTO.setCode(0);
            responseDTO.setMsg("登录成功");
            responseDTO.setData(superAdmin.getToken());
            //记录使用者登入信息
            JCEngine.asyncService.execute(() -> {
                try {
                    String msg = new Timestamp(System.currentTimeMillis()) + " " + userMsg + "\n";
                    String path = new File("").getCanonicalPath() + File.separator + "admin-login-msg.txt";
                    FileWriter fileWriter = new FileWriter(path, true);
                    fileWriter.write(msg);
                    fileWriter.flush();
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            return responseDTO;
        }
        //返回结果-登录失败
        responseDTO.setCode(-1);
        responseDTO.setMsg("账号密码错误");
        return responseDTO;
    }

    @PostMapping("checkToken")
    public ResponseDTO checkToken(HttpServletRequest request) {
        //拦截-预处理
        ResponseDTO responseDTO = AdminInterceptor.preHandle(request);
        if (responseDTO != null) return responseDTO;
        return new ResponseDTO();
    }
}
