/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.nl.system.controller.user;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.nl.common.base.TableDataInfo;
import org.nl.common.domain.query.PageQuery;
import org.nl.config.RsaProperties;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.RsaUtils;
import org.nl.common.utils.SecurityUtils;
import org.nl.common.logging.annotation.Log;
import org.nl.system.service.user.ISysUserService;
import org.nl.system.service.user.dao.SysUser;
import org.nl.system.service.user.dto.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.Set;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    @Autowired
    private ISysUserService userService;


    @ApiOperation("查询用户")
    @GetMapping
    public ResponseEntity<Object> query(UserQuery query, PageQuery page){
        return new ResponseEntity(TableDataInfo.build(userService.getUserDetail(query, page)),HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
//    @SaCheckPermission("user:add")
    public ResponseEntity<Object> create(@RequestBody Map user){
        userService.create(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
//    @SaCheckPermission("user:edit")
    public ResponseEntity<Object> update( @RequestBody Map resources) throws Exception {
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
//    @PutMapping(value = "center")
    public ResponseEntity<Object> center(@RequestBody SysUser resources){
        if(!resources.getUser_id().equals(StpUtil.getLoginIdAsLong())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.saveOrUpdate(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
//    @SaCheckPermission("user:del")
    public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
        userService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updatePass(@RequestBody JSONObject passVo) throws Exception {
        // 解密，得到字符密码
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getString("oldPass"));
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getString("newPass"));
        SysUser user = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, SecurityUtils.getCurrentUsername()));
        if (!SaSecureUtil.md5BySalt(user.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(oldPass, "salt"))) {
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if (!SaSecureUtil.md5BySalt(user.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(newPass, "salt"))) {
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        user.setPassword(SaSecureUtil.md5BySalt(newPass, "salt"));
        userService.updateById(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }

    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateEmail(@PathVariable String code,@RequestBody SysUser user) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
        SysUser userInfo = userService.getOne(new QueryWrapper<SysUser>().eq("username",SecurityUtils.getCurrentUsername()));
        if(!SaSecureUtil.md5BySalt(userInfo.getPassword(), "salt").equals(SaSecureUtil.md5BySalt(password, "salt"))){
            throw new BadRequestException("密码错误");
        }
        userService.update(new UpdateWrapper<SysUser>().set(userInfo.getUsername(),user.getEmail()));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     * @param resources /
     */

}
