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

import cn.iocoder.yudao.module.attendance.controller.admin.info.vo.*;
import cn.iocoder.yudao.module.attendance.dal.dataobject.info.AttendanceInfoDO;
import cn.iocoder.yudao.module.attendance.service.info.AttendanceInfoService;
import io.swagger.v3.oas.annotations.Parameters;
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.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.io.IOException;

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.exception.util.ServiceExceptionUtil.exception;
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 org.springframework.web.multipart.MultipartFile;

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

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.attendance.enums.ErrorCodeConstants.ATTENDANCE_EXCEL_FORMAT_ERROR;

@Tag(name = "管理后台 - 考勤信息")
@RestController
@RequestMapping("/personnel/attendance/info")
@Validated
public class AttendanceInfoController {

    @Resource
    private AttendanceInfoService infoService;

    @PostMapping("/create")
    @Operation(summary = "创建考勤信息")
    @PreAuthorize("@ss.hasPermission('attendance:info:create')")
    public CommonResult<Long> createInfo(@Valid @RequestBody AttendanceInfoSaveReqVO createReqVO) {
        return success(infoService.createInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新考勤信息")
    @PreAuthorize("@ss.hasPermission('attendance:info:update')")
    public CommonResult<Boolean> updateInfo(@Valid @RequestBody AttendanceInfoSaveReqVO updateReqVO) {
        infoService.updateInfo(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得考勤信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('attendance:info:query')")
    public CommonResult<AttendanceInfoRespVO> getInfo(@RequestParam("id") Long id) {
        AttendanceInfoDO info = infoService.getInfo(id);
        return success(BeanUtils.toBean(info, AttendanceInfoRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得考勤信息分页")
    @PreAuthorize("@ss.hasPermission('attendance:info:query')")
    public CommonResult<PageResult<AttendanceInfoRespVO>> getInfoPage(@Valid AttendanceInfoPageReqVO pageReqVO) {
        PageResult<AttendanceInfoDO> pageResult = infoService.getInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AttendanceInfoRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出考勤信息 Excel")
    @PreAuthorize("@ss.hasPermission('attendance:info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInfoExcel(@Valid AttendanceInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AttendanceInfoDO> list = infoService.getInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "考勤信息.xls", "数据", AttendanceInfoRespVO.class,
                        BeanUtils.toBean(list, AttendanceInfoRespVO.class));
    }

    @PostMapping("/get-import-template")
    @PermitAll
    @Operation(summary = "获得导入考勤模板")
    @ApiAccessLog(operateType = EXPORT)
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<AttendanceInfoImportExcelVO> list = Arrays.asList(
                AttendanceInfoImportExcelVO.builder().employeeName("张三").employeeMobile("13555556666")
                        .deptName("人事部").position("人事专员").attendanceDate(LocalDate.now()).attendanceMonth("2024-07")
                        .workStartTime(LocalTime.of(8, 0)).workEndTime(LocalTime.of(17, 30))
                        .build(),
                AttendanceInfoImportExcelVO.builder().employeeName("李四").employeeMobile("13555556666")
                        .deptName("财务部").position("财务经理").attendanceDate(LocalDate.now()).attendanceMonth("2024-07")
                        .workStartTime(LocalTime.of(9, 0)).workEndTime(LocalTime.of(18, 30))
                        .build()
        );
        // 导出 Excel
        ExcelUtils.write(response, "考勤导入模板.xls", "数据", AttendanceInfoImportExcelVO.class, list);
    }

    @PostMapping("/import-excel")
    @Operation(summary = "导入考勤信息 Excel")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true)
    })
    @PreAuthorize("@ss.hasPermission('attendance:info:import')")
    public CommonResult<Boolean> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<AttendanceInfoImportExcelVO> list;
        try {
            list = ExcelUtils.read(file, AttendanceInfoImportExcelVO.class);
        } catch (Exception e) {
            throw exception(ATTENDANCE_EXCEL_FORMAT_ERROR);
        }

        return success(true).setMsg(infoService.importAttendanceInfoList(list));
    }

    @GetMapping("/dailyPage")
    @Operation(summary = "获得每日考勤信息分页")
    @PreAuthorize("@ss.hasPermission('attendance:info:query')")
    public CommonResult<PageResult<AttendanceDailyInfoRespVO>> getDailyInfoPage(@Valid AttendanceDailyInfoPageReqVO pageReqVO) {
        return success(infoService.getDailyInfoPage(pageReqVO));

    }

    @GetMapping("/export-daily-excel")
    @Operation(summary = "导出每日考勤信息 Excel")
    @PreAuthorize("@ss.hasPermission('attendance:info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDailyExcel(@Valid AttendanceDailyInfoPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AttendanceDailyInfoRespVO> list = infoService.getDailyInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "每日考勤信息.xls", "数据", AttendanceDailyInfoRespVO.class,
                list);
    }

    @GetMapping("/monthlyPage")
    @Operation(summary = "获得月度考勤信息分页")
    @PreAuthorize("@ss.hasPermission('attendance:info:query')")
    public CommonResult<PageResult<AttendanceMonthlyInfoRespVO>> getMonthlyInfoPage(@Valid AttendanceMonthlyInfoPageReqVO pageReqVO) {
        return success(infoService.getMonthlyInfoPage(pageReqVO));
    }

    @GetMapping("/export-monthly-excel")
    @Operation(summary = "导出月度考勤信息 Excel")
    @PreAuthorize("@ss.hasPermission('attendance:info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMonthlyExcel(@Valid AttendanceMonthlyInfoPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AttendanceMonthlyInfoRespVO> list = infoService.getMonthlyInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "月度考勤信息.xls", "数据", AttendanceMonthlyInfoRespVO.class,
                list);
    }



}