package quant.rich.emoney.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import quant.rich.emoney.controller.common.BaseController;
import quant.rich.emoney.entity.config.PlatformConfig;
import quant.rich.emoney.exception.RException;
import quant.rich.emoney.pojo.dto.R;
import quant.rich.emoney.service.AuthService;
import quant.rich.emoney.service.ConfigService;
import quant.rich.emoney.util.EncryptUtils;

@Controller
@RequestMapping("/admin/v1")
public class IndexControllerV1 extends BaseController {
    
    @Autowired
    PlatformConfig platformConfig;
    
    @Autowired
    ConfigService configService;
    
    @Autowired
    AuthService authService;

    @GetMapping({ "", "/", "/index" })
    public String index() {
        return "admin/v1/index";
    }
    
    @GetMapping("/getUserInfo")
    @ResponseBody
    public R<?> getUserInfo() {
        ObjectNode node = new ObjectMapper().valueToTree(platformConfig);
        node.remove("password");
        node.remove("isInited");
        return R.ok(node);
    }
    
    @PostMapping("/changeUserInfo")
    @ResponseBody
    public R<?> changeUserInfo(
            String username,
            String password,
            String newPassword,
            String email,
            String apiToken) {
        
        if (EncryptUtils.passwordIsNotEmpty(newPassword)) {
            if (!platformConfig.getPassword().equals(password)) {
                throw RException.badRequest("密码错误");
            }
            platformConfig.setPassword(newPassword);
        }
        if (StringUtils.isNotEmpty(username)) {
            platformConfig.setUsername(username);
        }
        else {
            throw RException.badRequest("用户名不能为空");
        }
        platformConfig.setEmail(email).setApiToken(apiToken);
        return R.judge(() -> {
             if (configService.saveOrUpdate(platformConfig)) {
                 authService.setLogin(username, platformConfig.getPassword());
                 return true;
             }
             return false;
        });
    }
}
