package com.patzn.lims.sys.controller;

import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.common.IpHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.PtConstants;
import com.patzn.lims.core.api.PtResult;
import com.patzn.lims.core.toolkit.JacksonUtils;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.web.ServiceController;
import com.patzn.lims.sys.dto.SysUserDTO;
import com.patzn.lims.sys.entity.SysUser;
import com.patzn.lims.sys.entity.SysUserRelOrg;
import com.patzn.lims.sys.entity.SysUserRelRole;
import com.patzn.lims.sys.service.ISysUserRelOrgService;
import com.patzn.lims.sys.service.ISysUserRelRoleService;
import com.patzn.lims.sys.service.ISysUserService;
import com.patzn.lims.sys.vo.SysUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author patzn
 * @since 2017-07-20
 */
@Api(tags = "用户表")
@RestController
@RequestMapping("/v1/user")
public class SysUserController extends ServiceController<ISysUserService, SysUser> {

    @Autowired
    private ISysUserRelRoleService sysUserRelRoleService;
    @Autowired
    private ISysUserRelOrgService sysUserRelOrgService;


    @ApiOperation(value = "分页列表", notes = "分页查询数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
    })
    @PostMapping("/page")
    public PtResult<Page<SysUser>> getPage(SysUserVO vo) {
        // 超级管理员可以查看所有
        if (!LoginHelper.isSysAdmin()) {
            vo.setCompanyId(getAccount().getCompanyId());
        }
        return success(baseService.page(getPage(), vo));
    }


    @ApiOperation(value = "导出用户信息", notes = "导出用户信息数据内容")
    @PostMapping("/export")
    public void exportUser(@RequestParam String request) {
        SysUserVO vo;
        if (StringUtils.isNotBlank(request)) {
            vo = JacksonUtils.readValue(request, SysUserVO.class);
        } else {
            vo = new SysUserVO();
        }
        baseService.exportUser(response, currentCompanyId(), vo);
    }


    @ApiOperation(value = "未发送指定 ID 消息分页列表", notes = "分页查询未发送指定 ID 消息用户数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "messageId", value = "消息ID", required = true, paramType = "path", dataType = "long"),
    })
    @PostMapping("/page-not-send-message/{messageId}")
    public PtResult<Page<SysUser>> pageNotSendMessage(@PathVariable("messageId") Long messageId, SysUser sysUser) {
        sysUser.setCompanyId(currentCompanyId());
        return success(baseService.pageNotSendMessage(getPage(), messageId, sysUser));
    }


    @ApiOperation(value = "分页列表", notes = "分页查询机构组工作流关联数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "orgId", value = "机构主键", required = true, paramType = "path", dataType = "long"),
            @ApiImplicitParam(name = "activation", value = "查询待激活用户", paramType = "query", dataType = "Boolean"),
            @ApiImplicitParam(name = "realname", value = "真实姓名", paramType = "query", dataType = "String"),
    })
    @PostMapping("/page-org/{orgId}")
    public PtResult<Page<SysUser>> getPageByOrgId(@PathVariable("orgId") Long orgId, Boolean activation, String realname) {
        return success(sysUserRelOrgService.pageByOrgId(getPage(), orgId, getAccount().getCompanyId(), activation, realname));
    }


    @ApiOperation(value = "查询列表", notes = "查询机构组工作流关联数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构主键", required = true, paramType = "path", dataType = "long"),
            @ApiImplicitParam(name = "realname", value = "真实姓名", paramType = "query", dataType = "String"),
    })
    @PostMapping("/list-org/{orgId}")
    public PtResult<List<SysUser>> getListByOrgId(@PathVariable("orgId") Long orgId, String realname) {
        return success(sysUserRelOrgService.listByOrgId(orgId, getAccount().getCompanyId(), realname));
    }


    @ApiOperation(value = "查询列表", notes = "查询当前企业的所有用户数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realname", value = "真实姓名", paramType = "query", dataType = "String"),
    })
    @PostMapping("/list-company")
    public PtResult<List<SysUser>> getListByCompanyId(String realname) {
        return success(sysUserRelOrgService.listByCompanyId(getAccount().getCompanyId(), realname));
    }


    @ApiOperation(value = "分页列表", notes = "分页查询机构组工作流关联数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "groupId", value = "机构组主键", required = true, paramType = "path", dataType = "String"),
    })
    @PostMapping("/page-flow-member-ship/{groupId}")
    public PtResult<Page<SysUser>> getPageFlowMemberShip(@PathVariable("groupId") String groupId, SysUserVO vo) {
        vo.setCompanyId(currentCompanyId());
        return success(baseService.pageFlowMemberShip(getPage(), groupId, vo));
    }


    @ApiOperation(value = "分页列表", notes = "分页查询机构组工作流未关联数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "groupId", value = "机构组主键", required = true, paramType = "path", dataType = "long"),
    })
    @PostMapping("/page-flow-exclude-member-ship/{groupId}")
    public PtResult<Page<SysUser>> getPageFlowExcludeMemberShip(@PathVariable("groupId") String groupId, SysUserVO vo) {
        vo.setCompanyId(currentCompanyId());
        return success(baseService.pageFlowExcludeMemberShip(getPage(), groupId, vo));
    }


    @ApiOperation(value = "查询列表", notes = "查询数据列表")
    @PostMapping("/list")
    public PtResult<List<SysUser>> getList(SysUser sysUser) {
        sysUser.setCompanyId(currentCompanyId());
        return success(baseService.list(sysUser));
    }


    @ApiOperation(value = "查询列表", notes = "根据角色名称查询数据列表")
    @PostMapping("/list-{roleName}")
    public PtResult<List<SysUser>> getListByRoleName(@PathVariable("roleName") String roleName) {
        return success(baseService.listByRoleName(currentCompanyId(), roleName));
    }


    @ApiOperation(value = "分配角色", notes = "添加用户角色关联关系")
    @PostMapping("/rel-role/{userId}")
    public PtResult<Boolean> addRelRole(@PathVariable("userId") Long userId, @RequestParam("roleIds") List<Long> roleIds) {
        return success(sysUserRelRoleService.saveRelRole(userId, roleIds));
    }


    @ApiOperation(value = "关联角色", notes = "查询用户已经关联的角色列表")
    @GetMapping("/get-rel-role/{userId}")
    public PtResult<List<SysUserRelRole>> getRelRole(@PathVariable("userId") Long userId) {
        return success(sysUserRelRoleService.getRelRole(userId));
    }


    @ApiOperation(value = "分配机构", notes = "添加用户机构关联关系")
    @PostMapping("/rel-org/{userId}")
    public PtResult<Boolean> addRelOrg(@PathVariable("userId") Long userId, @RequestParam("orgIds") List<Long> orgIds) {
        return success(sysUserRelOrgService.saveRelOrg(userId, orgIds));
    }


    @ApiOperation(value = "关联机构", notes = "查询用户已经关联的机构列表")
    @GetMapping("/get-rel-org/{userId}")
    public PtResult<List<SysUserRelOrg>> getRelOrg(@PathVariable("userId") Long userId) {
        return success(sysUserRelOrgService.getRelOrg(userId));
    }

    @Login(action = Action.Skip)
    @ApiOperation(value = "查询 id 信息", notes = "查询指定 id 的数据内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long"),
    })
    @GetMapping("/{id}")
    @Override
    public PtResult<SysUser> get(@PathVariable("id") Long id) {
        SysUser sysUser = baseService.getById(id);
        if (null != sysUser) {
            sysUser.setPassword(null);
        }
        return success(sysUser);
    }


    @ApiOperation(value = "查询当前用户信息", notes = "查询当前登录用户的数据内容")
    @GetMapping("/info")
    public PtResult<SysUserVO> info() {
        return success(baseService.getAllowInfoById(currentUserId()));
    }


    @ApiOperation(value = "根据 id 修改信息", notes = "根据指定 id 修改该条数据内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long"),
    })
    @PutMapping("/{id}")
    public PtResult<Boolean> edit(@PathVariable("id") Long id, SysUserDTO dto) {
        dto.setId(id);
        return success(baseService.updateDtoById(dto));
    }


    @ApiOperation(value = "添加", notes = "添加一条数据")
    @PostMapping("/")
    public PtResult<Boolean> add(SysUserDTO dto) {
        dto.setCompanyId(currentCompanyId());
        dto.setRegip(IpHelper.getIpAddr(request));
        return success(baseService.saveDto(dto));
    }


    @ApiOperation(value = "添加管理员", notes = "添加一条管理员数据")
    @PostMapping("/manager/{companyId}")
    public PtResult<Boolean> addManager(@PathVariable("companyId") Long companyId, SysUserDTO dto) {
        dto.setCompanyId(companyId);
        dto.setRegip(IpHelper.getIpAddr(request));
        return success(baseService.saveManager(dto));
    }


    @ApiOperation(value = "修改当前用户的密码", notes = "修改当前用户的密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, paramType = "query", dataType = "String"),
    })
    @PutMapping("/password")
    public PtResult<Boolean> password(String oldPwd, String newPwd) {
        return success(baseService.changePassword(currentUserId(), oldPwd, newPwd));
    }


    @ApiOperation(value = "管理员信息查询", notes = "查询管理员数据")
    @PostMapping("/manager-info/{companyId}")
    public PtResult<Map<String, Object>> managerInfo(@PathVariable("companyId") Long companyId) {
        return success(baseService.managerInfo(companyId));
    }


    @ApiOperation(value = "设置头像", notes = "设置用户头像")
    @PostMapping("/avatar")
    public PtResult<String> saveLogo(MultipartFile file) {
        return success(baseService.saveAvatar(currentUserId(), file));
    }


    @ApiOperation(value = "导入用户", notes = "导入用户数据内容")
    @PostMapping("/import")
    public PtResult<Boolean> importUser(MultipartFile file) {
        return success(baseService.importUser(file, getAccount()));
    }


    @ApiOperation(value = "OTP 二次认证开通和关闭", notes = "开通和关闭二次认证 code 正确关闭")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户 ID", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "code", value = "OTP 验证码", paramType = "query", dataType = "Integer"),
    })
    @PostMapping("/otp")
    public PtResult<Boolean> otpOnOff(Long id, Integer code) {
        return success(baseService.otpOnOff(id, code));
    }
}
