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

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
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 cn.iocoder.yudao.module.system.api.dicttenant.DictDataTenantApi;
import cn.iocoder.yudao.module.system.api.dicttenant.dto.DictDataTenantRespDTO;
import cn.iocoder.yudao.module.system.enums.dicttenant.DictTypeTenantEnum;
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;
    @Resource
    private DictDataTenantApi dictDataTenantApi;

    @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());
            }
        }
        // 请假类型
        if (StrUtil.isNotBlank(respVO.getLeaveType())) {
            List<DictDataTenantRespDTO> dictDataList = dictDataTenantApi.getDictDataList(DictTypeTenantEnum.TENANT_LEAVE_TYPE.getType());
            Map<String, String> dictDataMap = CollectionUtils.convertMap(dictDataList, DictDataTenantRespDTO::getValue, DictDataTenantRespDTO::getLabel);
            String leaveTypeDesc = dictDataMap.get(respVO.getLeaveType());
            if (StrUtil.isNotBlank(leaveTypeDesc)) {
                respVO.setLeaveTypeDesc(leaveTypeDesc);
            }
        }
        // 附件列表
        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);
        // 请假类型
        List<DictDataTenantRespDTO> dictDataList = dictDataTenantApi.getDictDataList(DictTypeTenantEnum.TENANT_LEAVE_TYPE.getType());
        Map<String, String> dictDataMap = CollectionUtils.convertMap(dictDataList, DictDataTenantRespDTO::getValue, DictDataTenantRespDTO::getLabel);
        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());
                    }
                }
                // 请假类型
                if (StrUtil.isNotBlank(respVO.getLeaveType())) {
                    String leaveTypeDesc = dictDataMap.get(respVO.getLeaveType());
                    if (StrUtil.isNotBlank(leaveTypeDesc)) {
                        respVO.setLeaveTypeDesc(leaveTypeDesc);
                    }
                }
            });
        }
        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);
        PageResult<AttendanceLeaveDO> pageResult = leaveService.getLeavePage(pageReqVO);
        PageResult<AttendanceLeaveRespVO> result = BeanUtils.toBean(pageResult, AttendanceLeaveRespVO.class);
        // 请假类型
        List<DictDataTenantRespDTO> dictDataList = dictDataTenantApi.getDictDataList(DictTypeTenantEnum.TENANT_LEAVE_TYPE.getType());
        Map<String, String> dictDataMap = CollectionUtils.convertMap(dictDataList, DictDataTenantRespDTO::getValue, DictDataTenantRespDTO::getLabel);
        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());
                    }
                }
                // 请假类型
                if (StrUtil.isNotBlank(respVO.getLeaveType())) {
                    String leaveTypeDesc = dictDataMap.get(respVO.getLeaveType());
                    if (StrUtil.isNotBlank(leaveTypeDesc)) {
                        respVO.setLeaveTypeDesc(leaveTypeDesc);
                    }
                }
            });
        }
        // 导出 Excel
        ExcelUtils.write(response, "请假信息.xls", "数据", AttendanceLeaveRespVO.class,
                result.getList());
    }

}