package com.cico.nest.lcdp.boot.core.system.controller.admin.user;

import cn.hutool.core.collection.CollUtil;
import com.cico.nest.lcdp.boot.api.system.enums.common.SexEnum;
import com.cico.nest.lcdp.boot.core.system.controller.admin.user.vo.user.*;
import com.cico.nest.lcdp.boot.core.system.convert.user.UserConvert;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.dept.DeptDO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.permission.UserRoleDO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.user.AdminUserDO;
import com.cico.nest.lcdp.boot.core.system.dal.mysql.permission.UserRoleMapper;
import com.cico.nest.lcdp.boot.core.system.service.dept.DeptService;
import com.cico.nest.lcdp.boot.core.system.service.logger.LoginLogService;
import com.cico.nest.lcdp.boot.core.system.service.user.AdminUserService;
import com.cico.nest.lcdp.framework.common.enums.CommonStatusEnum;
import com.cico.nest.lcdp.framework.common.pojo.CommonResult;
import com.cico.nest.lcdp.framework.common.pojo.PageParam;
import com.cico.nest.lcdp.framework.common.pojo.PageResult;
import com.cico.nest.lcdp.framework.excel.core.util.ExcelUtils;
import com.cico.nest.lcdp.framework.operatelog.core.annotations.OperateLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.cico.nest.lcdp.framework.common.pojo.CommonResult.success;
import static com.cico.nest.lcdp.framework.common.util.collection.CollectionUtils.convertList;


@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user/v2")
@Validated
public class UserV2Controller {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private LoginLogService loginLogService;

    @PostMapping("/create")
    @Operation(summary = "新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @Operation(summary = "修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        userService.updateUserV2(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除用户")
    @Parameter(name = "ids", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestBody  List<Long> ids) {
        userService.deleteUsers(ids);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-password')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public CommonResult<PageResult<UserRespVO>> getUserPage(@Valid UserPageReqVO pageReqVO) {
        // 获得用户分页列表
        PageResult<UserRespVO> pageResult = userService.getUserPageV2(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        //查询用户登录次数
        List<Long> userIds = pageResult.getList().stream().map(UserRespVO::getId).collect(Collectors.toList());
        Map<Long,Long> userLoginNumMap = loginLogService.countLoginNumsByUsers(userIds);
        pageResult.getList().forEach(a->{
            a.setLoginNum(userLoginNumMap.getOrDefault(a.getId(),0l));
        });
        return success(pageResult);
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        Map<String, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));
        return success(UserConvert.INSTANCE.convertSimpleList(list, deptMap));
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUser(id);
        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());
        List<UserRoleDO> userRoleDOList = userRoleMapper.selectListByUserId(user.getId());
        UserRespVO userRespVO = UserConvert.INSTANCE.convert(user, dept);
        userRespVO.setRoleIds(userRoleDOList.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList()));
        return success(userRespVO);
    }

}
