package cn.iocoder.yudao.module.attendance.controller.admin.leave;

import cn.iocoder.yudao.module.attendance.controller.admin.business.vo.AttendanceBusinessRespVO;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.attendance.controller.admin.leave.vo.*;
import cn.iocoder.yudao.module.attendance.dal.dataobject.leave.AttendanceLeaveDO;
import cn.iocoder.yudao.module.attendance.service.leave.AttendanceLeaveService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 请假信息")
@RestController
@RequestMapping("/personnel/attendance/leave")
@Validated
public class AttendanceLeaveController {

    @Resource
    private AttendanceLeaveService leaveService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private FileApi fileApi;

    @PostMapping("/create")
    @Operation(summary = "创建请假信息")
    @PreAuthorize("@ss.hasPermission('attendance:leave:create')")
    public CommonResult<Long> createLeave(@Valid @RequestBody AttendanceLeaveSaveReqVO createReqVO) {
        return success(leaveService.createLeave(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新请假信息")
    @PreAuthorize("@ss.hasPermission('attendance:leave:update')")
    public CommonResult<Boolean> updateLeave(@Valid @RequestBody AttendanceLeaveSaveReqVO updateReqVO) {
        leaveService.updateLeave(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除请假信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('attendance:leave:delete')")
    public CommonResult<Boolean> deleteLeave(@RequestParam("id") Long id) {
        leaveService.deleteLeave(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得请假信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('attendance:leave:query')")
    public CommonResult<AttendanceLeaveRespVO> getLeave(@RequestParam("id") Long id) {
        AttendanceLeaveDO leave = leaveService.getLeave(id);
        AttendanceLeaveRespVO respVO = BeanUtils.toBean(leave, AttendanceLeaveRespVO.class);
        // 部门
        if (respVO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(respVO.getDeptId());
            respVO.setDeptName(dept.getName());
            if (dept != null && StringUtils.isNotBlank(dept.getName())) {
                respVO.setDeptName(dept.getName());
            }
        }
        // 附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(respVO.getLeaveId());
        respVO.setFileList(fileList);
        List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
        respVO.setFileIdList(fileIdList);
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得请假信息分页")
    @PreAuthorize("@ss.hasPermission('attendance:leave:query')")
    public CommonResult<PageResult<AttendanceLeaveRespVO>> getLeavePage(@Valid AttendanceLeavePageReqVO pageReqVO) {
        PageResult<AttendanceLeaveDO> pageResult = leaveService.getLeavePage(pageReqVO);
        PageResult<AttendanceLeaveRespVO> result = BeanUtils.toBean(pageResult, AttendanceLeaveRespVO.class);
        if (result != null && result.getList() != null && result.getList().size() > 0) {
            result.getList().forEach(respVO -> {
                // 部门
                if (respVO.getDeptId() != null) {
                    DeptRespDTO dept = deptApi.getDept(respVO.getDeptId());
                    if (dept != null && StringUtils.isNotBlank(dept.getName())) {
                        respVO.setDeptName(dept.getName());
                    }
                }
            });
        }
        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出请假信息 Excel")
    @PreAuthorize("@ss.hasPermission('attendance:leave:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportLeaveExcel(@Valid AttendanceLeavePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AttendanceLeaveDO> list = leaveService.getLeavePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "请假信息.xls", "数据", AttendanceLeaveRespVO.class,
                        BeanUtils.toBean(list, AttendanceLeaveRespVO.class));
    }

}