package com.qmth.sop.server.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.dto.UserDto;
import com.qmth.sop.business.entity.SysSupplier;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.service.SysSupplierService;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

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.Objects;
import java.util.Optional;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Api(tags = "用户Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_USER)
public class SysUserController {

    @Resource
    SysUserService sysUserService;

    @Resource
    SysSupplierService supplierService;

    @ApiOperation(value = "查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = UserDto.class)})
    public Result list(@ApiParam(value = "登录名或真实姓名或手机号") @RequestParam(required = false) String userInfo,
                       @ApiParam(value = "机构id") @RequestParam(required = false) Long orgId,
                       @ApiParam(value = "角色id") @RequestParam(required = false) Long roleId,
                       @ApiParam(value = "是否启用") @RequestParam(required = false) Boolean enable,
                       @ApiParam(value = "页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                       @ApiParam(value = "页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(sysUserService.query(new Page<>(pageNumber, pageSize), userInfo, orgId, roleId, enable));
    }

    @ApiOperation(value = "新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.EDIT)
    public Result save(@Valid @ApiParam(value = "用户保存信息", required = true) @RequestBody SysUser sysUser, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(sysUserService.saveUser(sysUser, null));
    }

    @ApiOperation(value = "启用/禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.UPDATE)
    public Result enable(@RequestBody SysUser sysUser) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysUserService.enable(sysUser));
    }

    @ApiOperation(value = "初始化密码")
    @RequestMapping(value = "/init_password", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.UPDATE)
    public Result initPassword(@RequestBody SysUser sysUser) throws NoSuchAlgorithmException {
        return ResultUtil.ok(sysUserService.initPassword(sysUser));
    }

    @ApiOperation(value = "查询绑定供应商")
    @RequestMapping(value = "/query/supplier", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = SysSupplier.class)})
    public Result querySupplier(@ApiParam(value = "用户id", required = true) @RequestParam Long id) {
        SysUser sysUser = sysUserService.getById(id);
        Optional.ofNullable(sysUser).orElseThrow(() -> ExceptionResultEnum.USER_NO_EXISTS.exception());
        SysSupplier sysSupplier = Objects.nonNull(sysUser.getSupplierId()) ? supplierService.getById(sysUser.getSupplierId()) : null;
        return ResultUtil.ok(sysSupplier);
    }

    @ApiOperation(value = "绑定供应商")
    @RequestMapping(value = "/band/supplier", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.EDIT)
    public Result bandSupplier(@ApiParam(value = "用户id", required = true) @RequestParam Long id,
                               @ApiParam(value = "供应商id", required = true) @RequestParam Long supplierId) {
        SysUser sysUser = sysUserService.getById(id);
        Optional.ofNullable(sysUser).orElseThrow(() -> ExceptionResultEnum.USER_NO_EXISTS.exception());
        SysUser requestSysUser = (SysUser) ServletUtil.getRequestUser();
        sysUser.setSupplierId(supplierId);
        sysUser.updateInfo(requestSysUser.getId());
        return ResultUtil.ok(sysUserService.updateById(sysUser));
    }
}
