package com.reyun.controller;

import com.reyun.model.Account;
import com.reyun.repository.AccountRepository;
import com.reyun.security.TokenManager;
import com.reyun.security.annotation.CurrentAccount;
import com.reyun.service.LoginService;
import com.reyun.util.ResultModel;
import com.reyun.util.ResultStatus;
import com.reyun.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("account")
public class AccountController {

	@Autowired
	AccountRepository accountRepository;

	@Autowired
	LoginService loginService;

	@Autowired
	TokenManager tokenManager;
	
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel register(HttpServletResponse response,
			@RequestBody Account account) {
		return ResultModel.OK(loginService.save(account));
	}
	
	@RequestMapping(value = "find/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel findone(HttpServletResponse response,
			@PathVariable Long id) {
		return ResultModel.OK(accountRepository.findOne(id));
	}

    /**
     * 查询账户详情和登陆日志
     */
    @RequestMapping(value = "detail", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findAccountAndLog(@CurrentAccount Account loginAccount) {

        return ResultModel.OK(loginService.findAccountDetailAndLog(loginAccount));

    }

    /**
     * 更新账户基本信息
     */
    @RequestMapping(value = "updateBase", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel updateAccountInfo(HttpServletRequest request, @CurrentAccount Account loginAccount, @RequestBody Account updateAccount) {

        updateAccount.setId(loginAccount.getId());
        updateAccount.setEmail(loginAccount.getEmail());

        return ResultModel.OK(loginService.updateAccountInfo(updateAccount, request));
    }

    /**
     * 更新账户密码
     */
    @RequestMapping(value = "updatePwd", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel updateAccountPwd(@CurrentAccount Account loginAccount, @RequestParam String newPassword,
                                        @RequestParam String oldPassword) {

        if (StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword) || oldPassword.equals(newPassword)) {

            return ResultModel.OK(0);

        } else {

            ResultStatus resultStatus = loginService.updateAccountPwd(newPassword, oldPassword, loginAccount);

            return new ResultModel(resultStatus.getCode(),resultStatus.getMessage(),1);

        }
    }
}
