package jnpf.attendance.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.attendance.AttendanceUserApi;
import jnpf.attendance.dto.GroupUpdateByUserDTO;
import jnpf.attendance.service.AttendanceDayStatisticsService;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.attendance.service.AttendanceUserService;
import jnpf.base.ActionResult;
import jnpf.entity.AttendanceGroup;
import jnpf.entity.AttendanceGroupUser;
import jnpf.exception.HandleException;
import jnpf.model.attendance.dto.ExportUserTemplateDto;
import jnpf.model.attendance.dto.GroupUserQueryDto;
import jnpf.model.attendance.dto.JoinUserDto;
import jnpf.model.attendance.dto.UserSortModel;
import jnpf.model.attendance.vo.AttendanceGroupUserVo;
import jnpf.model.attendance.vo.attendance.JoinGroupVo;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.CustomTenantUtil;
import jnpf.util.EasyExcelUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考勤组/成员管理
 *
 * @author yier
 * @Time 2023-11-23
 */
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class AttendanceGroupUserController implements AttendanceUserApi {

    @Resource
    private AttendanceUserService attendanceUserService;
    @Resource
    private AttendanceGroupService attendanceGroupService;
    @Resource
    private AttendanceDayStatisticsService dayStaService;
    @Resource
    private CustomTenantUtil customTenantUtil;

    /**
     * 成员管理-查询系统用户（附带考勤组名称）
     *
     * @param orgId 部门id
     * @param name  用户姓名 字段模糊搜索
     * @return ActionResult<AttendanceGroupUserVo>
     */
    @GetMapping("/getSysUsers")
    public ActionResult<List<AttendanceGroupUserVo>> get(String orgId, String name) {
        List<AttendanceGroupUserVo> voList = attendanceUserService.querySysUserList(orgId, name);
        return ActionResult.success(voList);
    }


    /**
     * 用户排序
     *
     * @param userSortModel
     */
    @PutMapping("/sort")
    public ActionResult sort(@RequestBody UserSortModel userSortModel) {
        Assert.isFalse(CollUtil.isEmpty(userSortModel.getUserSortList()), "未传入用户数据");
        attendanceUserService.sort(userSortModel);
        return ActionResult.success();
    }

    /**
     * 用户加入考勤组
     *
     * @param joinUserDto
     * @return ActionResult<Void>
     * @throws Exception
     */
    @PostMapping
    public ActionResult<Void> addUsers(@RequestBody JoinUserDto joinUserDto) throws Exception {
        ParamUtil.checkParam(joinUserDto);
        attendanceUserService.joinUsers(joinUserDto);
        return ActionResult.success();
    }

    /**
     * 批量移除考勤组成员
     *
     * @param joinUserDto
     * @return
     */
    @DeleteMapping
    public ActionResult<Void> batchRemove(@RequestBody JoinUserDto joinUserDto) {
        attendanceUserService.batchDeleteUsersForSendNotice(joinUserDto);
        return ActionResult.success();
    }

    /**
     * 花名册考勤组变更
     *
     * @param groupUpdateByUserDTO
     * @return
     */
    @PostMapping("groupUpdateByPersonnel")
    @NoDataSourceBind
    @Deprecated
    public ActionResult<Void> groupUpdateByPersonnel(@RequestBody GroupUpdateByUserDTO groupUpdateByUserDTO) {
        customTenantUtil.checkOutTenant(groupUpdateByUserDTO.getTenantId());
        attendanceUserService.groupUpdateByPersonnel(groupUpdateByUserDTO);
        return ActionResult.success();
    }

    /**
     * 检查用户是否已经加入
     *
     * @param userIds
     * @return ActionResult<List < String>>
     */
    @GetMapping("/checkUserJoinGroup")
    public ActionResult<List<String>> checkUserJoinGroup(String userIds) throws HandleException {
        List<String> userNameList = attendanceUserService.checkUserGroup(userIds);
        return ActionResult.success(userNameList);
    }


    /**
     * 检查用户是否已经加入1.9
     * @param userIds 用户ids
     * @return ActionResult<List < String>>
     */
    @PostMapping("/checkUserJoinGroupToObject")
    public ActionResult<List<JoinGroupVo>> checkUserJoinGroupToObject(@RequestBody String userIds) throws HandleException {
        List<JoinGroupVo> userNameList = attendanceUserService.checkUserJoinGroupToObject(userIds);
        return ActionResult.success(userNameList);
    }

    /**
     * 导出用户模版
     */
    @GetMapping("/downloadTemplate")
    @NoDataSourceBind
    public void downloadTemplate(HttpServletResponse response, @RequestParam String tenantId) throws Exception {
        customTenantUtil.checkOutTenant(tenantId);
        EasyExcelUtil.export(response, "考勤组成员.xlsx", "考勤组成员", ExportUserTemplateDto.class, null);
    }

    /**
     * 筛选考勤组下成员，去重，入参考勤组ids 出参用户集合 借调用户也要查询出来
     *
     * @param groupUserQueryDto 考勤组信息
     * @return
     */
    @PostMapping("/getUsersByGroupIds")
    public ActionResult<List<AttendanceGroupUserVo>> getUsersByGroupIds(@RequestBody @Valid GroupUserQueryDto groupUserQueryDto) {
        List<UserBoundVO> voList = dayStaService.getUserIdArr(groupUserQueryDto.getFilterList(),
                groupUserQueryDto.getStartTime(), groupUserQueryDto.getEndTime(), groupUserQueryDto.getUserIds(), "0");
        List<AttendanceGroupUserVo> userVoList = CollectionUtil.isEmpty(voList) ? new ArrayList<>() :
                voList.stream().map(vo -> {
                    AttendanceGroupUserVo userVo = new AttendanceGroupUserVo();
                    userVo.setUserId(vo.getId());
                    userVo.setRealName(vo.getUserName());
                    userVo.setNickname(vo.getNickname());
                    return userVo;
                }).collect(Collectors.toList());
        return ActionResult.success(userVoList);
    }

    @Operation(summary = "借调考勤组变动通知")
    @GetMapping(value = "/userGroupUpdateBySecondNotice")
    public ActionResult<Boolean> userGroupUpdateBySecondNotice(@RequestParam(value = "tenantId") String tenantId) {
        try {
            log.info("执行借调考勤组变动通知");
            return ActionResult.success(attendanceUserService.userGroupUpdateBySecondNotice(tenantId));
        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.success(Boolean.FALSE);
        }
    }

    /**
     * 指定考勤组成员列表
     *
     * @param id 考勤组Id
     * @param isPermissions 是否权限控制
     */
    @GetMapping("/getGroupUserList")
    public ActionResult<List<AttendanceGroupUserVo>> getGroupUserList(@RequestParam(value = "id") String id,
                                                                      @RequestParam(value = "isPermissions") Boolean isPermissions) {
        List<AttendanceGroupUserVo> voList = attendanceUserService.getGroupUserList(id, isPermissions);
        return ActionResult.success(voList);
    }

    /**
     * 获取现在考勤组成员列表包含借调不含权限
     * @param id 考勤组Id
     */
    @GetMapping("/getGroupNowAllUserList")
    public ActionResult<List<AttendanceGroupUserVo>> getGroupNowAllUserList(@RequestParam(value = "id") String id) {
        List<AttendanceGroupUserVo> attendanceGroupUsersOfSecondment = attendanceUserService.getGroupNowAllUserList(id);
        return ActionResult.success(attendanceGroupUsersOfSecondment);
    }

    /**
     * 根据用户ID查询当前时间所在考勤组（包含借调）
     *
     * @param userId 用户ID
     * @return ActionResult<List<AttendanceGroup>>
     */
    @GetMapping("/getUserCurrentGroup")
    public ActionResult<List<AttendanceGroup>> getUserCurrentGroup(@RequestParam String userId) {
        Assert.isFalse(StrUtil.isBlank(userId), "用户ID不能为空");
        List<AttendanceGroup> groups = attendanceGroupService.getUserCurrentGroups(userId);
        return ActionResult.success(groups);
    }


}
