package com.sy.coinage.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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 com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.constants.ResponseEnum;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.vo.CacheUserVO;
import com.sy.coinage.core.aop.annotation.Operation;
import com.sy.coinage.core.util.MD5Util;
import com.sy.coinage.sys.model.User;
import com.sy.coinage.sys.req.SelfUpdateReq;
import com.sy.coinage.sys.req.UpPwdReq;
import com.sy.coinage.sys.service.IUserService;
import com.sy.coinage.sys.vo.UserVO;

/**
 * 个人信息Controller
 *
 * @author lug 2017-3-21
 */
@Api(value = "个人信息接口", tags = "019_个人信息")
@RestController
@RequestMapping(value = "/self")
public class SelfController {

    @Autowired
    private IUserService userService;

    /**
     * 修改个人密码
     */
    @ApiOperation(value = "修改个人密码")
    @Operation(value = "修改个人密码")
    @PostMapping("/updatePwd")
    public Object updatePwd(@RequestBody @Valid UpPwdReq req, @CurrentUser CacheUserVO user) {
        User model = this.userService.getById(user.getId());
        // 密码加盐加密
        String pwd = MD5Util.MD5(req.getOldPassword() + model.getSalt());
        // 密码校验
        if (!model.getPassword().equals(pwd)) {
            // 密码错误
            throw new RetException(ResponseEnum.PWD_ERROR);
        }
        model.setPassword(MD5Util.MD5(req.getNewPassword() + model.getSalt()));
        this.userService.updateById(model);
        return "";
    }

    /**
     * 个人详情
     */
    @ApiOperation(value = "个人详情")
    @GetMapping(value = "/get")
    public UserVO get(@CurrentUser CacheUserVO user) {
        UserVO data = null;
        User model = this.userService.getById(user.getId());
        data = new UserVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    /**
     * 修改个人信息
     */
    @ApiOperation(value = "修改个人信息")
    @Operation(value = "修改个人信息")
    @PostMapping("/update")
    public Object update(@RequestBody @Valid SelfUpdateReq req, @CurrentUser CacheUserVO user) {
        User model = this.userService.getById(user.getId());
        BeanUtils.copyProperties(req, model);
        this.userService.updateById(model);
        return "";
    }

    @ApiOperation(value = "获取仓库")
    @GetMapping("/getWareId")
    public Integer getWareId(@CurrentUser CacheUserVO user) {
        return user.getSelfWareId();
    }

}
