/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.sql.admin.sys.modular.rest.controller;

import com.sql.admin.base.auth.context.LoginContextHolder;
import com.sql.admin.base.consts.ConstantsContext;
import com.sql.admin.base.log.BussinessLog;
import com.sql.admin.base.pojo.page.LayuiPageFactory;
import com.sql.admin.sys.core.constant.Const;
import com.sql.admin.sys.core.constant.dictmap.UserDict;
import com.sql.admin.sys.core.constant.state.ManagerStatus;
import com.sql.admin.sys.core.exception.enums.BizExceptionEnum;
import com.sql.admin.sys.core.util.SaltUtil;
import com.sql.admin.sys.modular.rest.entity.RestUser;
import com.sql.admin.sys.modular.rest.model.UserQueryParam;
import com.sql.admin.sys.modular.rest.service.RestUserService;
import com.sql.admin.sys.modular.system.model.UserDto;
import com.sql.admin.sys.modular.system.warpper.UserWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.datascope.DataScope;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.stylefeng.roses.kernel.model.response.SuccessResponseData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;
import java.util.UUID;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@RestController
@RequestMapping("/rest/mgr")
public class RestUserMgrController extends BaseController {

    @Autowired
    private RestUserService restUserService;

    /**
     * 通过用户id获取用户的信息
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @RequestMapping("/getUserById")
    public ResponseData getUserById(@RequestParam("userId") Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Map<String, Object> user = restUserService.getUserInfo(userId);
        return new SuccessResponseData(user);
    }

    /**
     * 获取用户详情
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @RequestMapping("/getUserInfo")
    public SuccessResponseData getUserInfo(@RequestParam("userId") Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new RequestEmptyException();
        }
        this.restUserService.assertAuth(userId);
        return new SuccessResponseData(restUserService.getUserInfo(userId));
    }

    /**
     * 修改当前用户的密码
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @RequestMapping("/changePwd")
    public Object changePwd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        if (ToolUtil.isOneEmpty(oldPassword, newPassword)) {
            throw new RequestEmptyException();
        }
        this.restUserService.changePwd(oldPassword, newPassword);
        return SUCCESS_TIP;
    }

    /**
     * 查询管理员列表
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:43
     */
    @RequestMapping("/list")
    public Object list(@RequestBody UserQueryParam userQueryParam) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (ToolUtil.isNotEmpty(userQueryParam.getTimeLimit())) {
            String[] split = userQueryParam.getTimeLimit().split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

        if (LoginContextHolder.getContext().isAdmin()) {
            Page<Map<String, Object>> users = restUserService.selectUsers(null, userQueryParam.getName(), beginTime, endTime, userQueryParam.getDeptId());
            Page wrapped = new UserWrapper(users).wrap();
            return LayuiPageFactory.createPageInfo(wrapped);
        } else {
            DataScope dataScope = new DataScope(LoginContextHolder.getContext().getDeptDataScope());
            Page<Map<String, Object>> users = restUserService.selectUsers(dataScope, userQueryParam.getName(), beginTime, endTime, userQueryParam.getDeptId());
            Page wrapped = new UserWrapper(users).wrap();
            return LayuiPageFactory.createPageInfo(wrapped);
        }
    }

    /**
     * 添加管理员
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/add")
    @BussinessLog(value = "添加管理员", key = "account", dict = UserDict.class)
    public ResponseData add(@RequestBody UserDto user) {
        this.restUserService.addUser(user);
        return SUCCESS_TIP;
    }

    /**
     * 修改管理员
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改管理员", key = "account", dict = UserDict.class)
    public ResponseData edit(@RequestBody UserDto user) {
        this.restUserService.editUser(user);
        return SUCCESS_TIP;
    }

    /**
     * 删除管理员（逻辑删除）
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/delete")
    @BussinessLog(value = "删除管理员", key = "userId", dict = UserDict.class)
    public ResponseData delete(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.restUserService.deleteUser(userId);
        return SUCCESS_TIP;
    }

    /**
     * 重置管理员的密码
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/reset")
    @BussinessLog(value = "重置管理员密码", key = "userId", dict = UserDict.class)
    public ResponseData reset(@RequestParam Long userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.restUserService.assertAuth(userId);
        RestUser restUser = this.restUserService.getById(userId);
        restUser.setSalt(SaltUtil.getRandomSalt());
        restUser.setPassword(SaltUtil.md5Encrypt(ConstantsContext.getDefaultPassword(), restUser.getSalt()));
        this.restUserService.updateById(restUser);
        return SUCCESS_TIP;
    }

    /**
     * 冻结用户
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/changeStatus")
    public ResponseData changeStatus(@RequestParam("userId") Long userId, @RequestParam("status") String status) {

        //冻结用户
        if (status.equals("freeze")) {

            if (ToolUtil.isEmpty(userId)) {
                throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
            }

            //不能冻结超级管理员
            if (userId.equals(Const.ADMIN_ID)) {
                throw new ServiceException(BizExceptionEnum.CANT_FREEZE_ADMIN);
            }

            this.restUserService.assertAuth(userId);
            this.restUserService.setStatus(userId, ManagerStatus.FREEZED.getCode());

            return SUCCESS_TIP;

        } else if (status.equals("unfreeze")) {

            //解除冻结用户
            if (ToolUtil.isEmpty(userId)) {
                throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
            }

            this.restUserService.assertAuth(userId);
            this.restUserService.setStatus(userId, ManagerStatus.OK.getCode());

            return SUCCESS_TIP;

        } else {

            return SUCCESS_TIP;

        }
    }

    /**
     * 分配角色
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/setRole")
    @BussinessLog(value = "分配角色", key = "userId,roleIds", dict = UserDict.class)
    public ResponseData setRole(@RequestParam("userId") Long userId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(userId, roleIds)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能修改超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new ServiceException(BizExceptionEnum.CANT_CHANGE_ADMIN);
        }
        this.restUserService.assertAuth(userId);
        this.restUserService.setRoles(userId, roleIds);
        return SUCCESS_TIP;
    }

    /**
     * 上传图片
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    public ResponseData upload(@RequestPart("file") MultipartFile picture) {

        String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
        try {
            String fileSavePath = ConstantsContext.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return new SuccessResponseData(pictureName);
    }
}
