package io.renren.modules.app.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.commons.lang.StringUtils;
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.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
 * 用户接口
 *
 * @author huwhois sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app/user")
@Api("个人中心接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Login
    @GetMapping("/info")
    @ApiOperation("获取用户信息")
    public R userInfo(@LoginUser UserEntity user){
        return R.ok().put("user", user);
    }

    /**
     * 修改
     */
    @Login
    @PostMapping("/update")
    @ApiOperation("修改")
    public R update(@RequestBody UserEntity user){
    
        user.setModifyTime(new Date());
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 订单列表
     */
    @Login
    @GetMapping("/orderlist")
    @ApiOperation("获取订单列表")
    public R orderList(@RequestAttribute("userId") Integer userId){
        // System.out.println(userId);
        Long memberId = Long.valueOf(userId);        

        List<Map<String, Object>> orderList = userService.queryOrderList(memberId);        

        return R.ok().put("orderList", orderList);
    }
    /**
     * 重置密码
     */
    @Login
    @PostMapping("newpassword")
    @ApiOperation("重置密码")
    public R newpassword(@RequestBody Map<String, Object> params, @LoginUser UserEntity user) {
        Long id = user.getUserId();
        String password = (String) params.get("password");
        String newpassword = (String) params.get("newpassword");
        if (StringUtils.isBlank(newpassword)) {
            return R.error("新密码不能为空");
        }
        if(!user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())){
			return R.error("原密码不正确");
		}

        userService.updatePassWord(id, newpassword);
        return R.ok();
    }
}
