package com.qmth.paper.library.api;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.paper.library.business.bean.result.EditResult;
import com.qmth.paper.library.business.service.PaperLibraryCommonService;
import com.qmth.paper.library.business.templete.execute.AsyncSysUserDataImportService;
import com.qmth.paper.library.common.bean.params.UserSaveParams;
import com.qmth.paper.library.common.contant.ApiPrefixConstant;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.entity.TBTask;
import com.qmth.paper.library.common.enums.TaskTypeEnum;
import com.qmth.paper.library.common.service.SysUserService;
import com.qmth.paper.library.common.util.Result;
import com.qmth.paper.library.common.util.ResultUtil;
import com.qmth.paper.library.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 */
@Api(tags = "用户Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + ApiPrefixConstant.PREFIX_SYS + "/user")
@Validated
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private PaperLibraryCommonService paperLibraryCommonService;

    @Resource
    private AsyncSysUserDataImportService asyncSysUserDataImportService;

    /**
     * 用户列表查询
     *
     * @param userInfo   用户信息（账号/姓名/手机号）
     * @param roleId     角色ID
     * @param orgId      机构ID
     * @param enable     是否启用
     * @param pageNumber 分页参数
     * @param pageSize   分页参数
     */
    @ApiOperation(value = "查询")
    @PostMapping("/list")
    public Result list(@RequestParam(value = "userInfo", required = false) String userInfo,
                       @RequestParam(value = "orgId", required = false) String orgId,
                       @RequestParam(value = "roleId", required = false) String roleId,
                       @RequestParam(value = "enable", required = false) Boolean enable,
                       @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                       @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(sysUserService.listForPrintSystem(userInfo, SystemConstant.convertIdToLong(orgId), roleId, enable, pageNumber, pageSize));
    }

    /**
     * 新增/修改
     *
     * @param userSaveParams 用户信息
     */
    @ApiOperation(value = "新增/修改")
    @PostMapping("/save")
    public Result save(@ApiParam(value = "用户信息", required = true) @Valid @RequestBody UserSaveParams userSaveParams, BindingResult bindingResult) throws IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(sysUserService.saveUser(userSaveParams));
    }

    /**
     * 启用/禁用
     *
     * @param user 用户信息
     */
    @ApiOperation(value = "启用/禁用")
    @PostMapping("/enable")
    public Result enable(@RequestBody SysUser user) throws NoSuchAlgorithmException, IllegalAccessException {
        return ResultUtil.ok(sysUserService.enable(user));
    }

    /**
     * 重置密码
     *
     * @param user 用户信息
     */
    @ApiOperation(value = "重置密码")
    @PostMapping("/reset_password")
    public Result resetPassword(@RequestBody SysUser user) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysUserService.resetPassword(user.getId()));
    }

    /**
     * 修改密码
     */
    @ApiOperation(value = "修改密码")
    @PostMapping("/update_password")
    @Aac(strict = false, auth = false)
    public Result updatePassword(@RequestBody SysUser user) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysUserService.updatePassword(user));
    }

    /**
     * 修改密码
     */
    @ApiOperation(value = "删除")
    @PostMapping("/remove")
    public Result remove(@RequestParam String ids) {
        String[] idsArray = ids.split(",");
        List<Long> longList = Stream.of(idsArray).map(Long::parseLong).collect(Collectors.toList());
        return ResultUtil.ok(sysUserService.delete(longList));
    }

    /**
     * 绑定角色
     *
     * @param sysUser 用户信息
     */
    @ApiOperation(value = "绑定角色")
    @PostMapping("/bind_roles")
    public Result bindRoles(@RequestBody SysUser sysUser) {
        return ResultUtil.ok(sysUserService.bindRoles(sysUser));
    }

    @ApiOperation(value = "用户管理-批量导入（异步）")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    public Result sysUserImportAsync(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws Exception {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Map<String, Object> map = paperLibraryCommonService.saveTask(file, TaskTypeEnum.USER_IMPORT);
        map.put(SystemConstant.SYS_USER, sysUser);

        asyncSysUserDataImportService.importTask(map);
        TBTask tbTask = Objects.nonNull(map.get(SystemConstant.TASK)) ? (TBTask) map.get(SystemConstant.TASK) : null;
        return Objects.nonNull(tbTask) ? ResultUtil.ok(tbTask.getId()) : ResultUtil.error("创建任务失败");
    }
}

