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

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.business.vo.*;
import cn.iocoder.yudao.module.attendance.dal.dataobject.business.AttendanceBusinessDO;
import cn.iocoder.yudao.module.attendance.service.business.AttendanceBusinessService;

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

@Tag(name = "管理后台 - 出差信息")
@RestController
@RequestMapping("/personnel/attendance/business")
@Validated
public class AttendanceBusinessController {

    @Resource
    private AttendanceBusinessService businessService;
    @Resource
    private DeptApi deptApi;
    @Resource
    private FileApi fileApi;

    @PostMapping("/create")
    @Operation(summary = "创建出差信息")
    @PreAuthorize("@ss.hasPermission('attendance:business:create')")
    public CommonResult<Long> createBusiness(@Valid @RequestBody AttendanceBusinessSaveReqVO createReqVO) {
        return success(businessService.createBusiness(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新出差信息")
    @PreAuthorize("@ss.hasPermission('attendance:business:update')")
    public CommonResult<Boolean> updateBusiness(@Valid @RequestBody AttendanceBusinessSaveReqVO updateReqVO) {
        businessService.updateBusiness(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得出差信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('attendance:business:query')")
    public CommonResult<AttendanceBusinessRespVO> getBusiness(@RequestParam("id") Long id) {
        AttendanceBusinessDO business = businessService.getBusiness(id);
        AttendanceBusinessRespVO respVO = BeanUtils.toBean(business, AttendanceBusinessRespVO.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.getBusinessId());
        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:business:query')")
    public CommonResult<PageResult<AttendanceBusinessRespVO>> getBusinessPage(@Valid AttendanceBusinessPageReqVO pageReqVO) {
        PageResult<AttendanceBusinessDO> pageResult = businessService.getBusinessPage(pageReqVO);
        PageResult<AttendanceBusinessRespVO> result = BeanUtils.toBean(pageResult, AttendanceBusinessRespVO.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:business:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBusinessExcel(@Valid AttendanceBusinessPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AttendanceBusinessDO> list = businessService.getBusinessPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "出差信息.xls", "数据", AttendanceBusinessRespVO.class,
                        BeanUtils.toBean(list, AttendanceBusinessRespVO.class));
    }

}