package com.qmth.distributed.print.api;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.annotation.BOOL;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.entity.TBSyncTask;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.templete.execute.AsyncSysUserDataImportService;
import com.qmth.distributed.print.business.templete.execute.AsyncUserPushService;
import com.qmth.teachcloud.common.bean.params.UserSaveParams;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.PushTypeEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.service.SysUserService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Map;
import java.util.Objects;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "用户Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.sys}/user")
@Validated
//@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE)
public class SysUserController {
    private final static Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private AsyncSysUserDataImportService asyncSysUserDataImportService;
    @Resource
    private AsyncUserPushService asyncUserPushService;

    /**
     * 查询
     *
     * @param loginName
     * @param roleId
     * @param enable
     * @return
     */
    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@RequestParam(value = "loginName", required = false) String loginName,
                       @RequestParam(value = "roleId", required = false) String roleId,
                       @RequestParam(value = "enable", required = false) Boolean enable,
                       @RequestParam(value = "realName", required = false) String realName,
                       @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.list(loginName, roleId, enable, realName, pageNumber, pageSize));
    }

    /**
     * 查询
     *
     * @param realName
     * @param enable
     * @return
     */
    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list_customer", method = RequestMethod.POST)
    public Result listCustomer(@RequestParam(value = "realName", required = false) String realName,
                               @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.listCustomer(realName, enable, pageNumber, pageSize));
    }

    /**
     * 根据科目查询命题老师
     *
     * @param courseCode
     * @param param
     * @return
     */
    @ApiOperation(value = "根据科目查询命题老师")
    @RequestMapping(value = "/user_list", method = RequestMethod.POST)
    public Result userQuery(@RequestParam(value = "courseCode", required = false) String courseCode,
                            @RequestParam(value = "param", required = false) String param) {
        return ResultUtil.ok(sysUserService.listUser(courseCode, param));
    }

    /**
     * 新增/修改
     *
     * @param userSaveParams
     * @return
     */
    @ApiOperation(value = "新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    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 userSaveParams
     * @return
     */
    @ApiOperation(value = "新增客服")
    @RequestMapping(value = "/save_customer", method = RequestMethod.POST)
    public Result saveCustomer(@ApiParam(value = "用户信息", required = true) @Valid @RequestBody UserSaveParams userSaveParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(sysUserService.saveCustomer(userSaveParams));
    }

    /**
     * 启用/禁用
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "启用/禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    public Result enable(@RequestBody SysUser user) throws NoSuchAlgorithmException, IllegalAccessException {
        return ResultUtil.ok(sysUserService.enable(user));
    }

    /**
     * 重置密码
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "重置密码")
    @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    public Result resetPassword(@RequestBody SysUser user) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysUserService.resetPassword(user.getId()));
    }

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

    /**
     * 绑定角色
     *
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "绑定角色")
    @RequestMapping(value = "/bind_roles", method = RequestMethod.POST)
    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 sysUserImportAysnc(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws Exception {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Map<String, Object> map = printCommonService.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("创建任务失败");
    }

    @ApiOperation(value = "用户管理-用户推送（异步）")
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    public Result sysUserPush() throws Exception {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Map<String, Object> map = printCommonService.savePush(PushTypeEnum.USER_PUSH);
        map.put(SystemConstant.SYS_USER, sysUser);

        asyncUserPushService.pushTask(map);
        TBSyncTask tbSyncTask = Objects.nonNull(map.get(SystemConstant.TB_SYNC_TASK)) ? (TBSyncTask) map.get(SystemConstant.TB_SYNC_TASK) : null;
        return Objects.nonNull(tbSyncTask) ? ResultUtil.ok(tbSyncTask.getId()) : ResultUtil.error("创建同步推送任务失败");
    }
}

