package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiStaffRecruitmentAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffRecruitmentEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffRecruitmentQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiStaffRecruitmentExcel;
import com.ruoyi.info.collection.domain.excel.CcdiStaffRecruitmentWorkExcel;
import com.ruoyi.info.collection.domain.vo.CcdiStaffRecruitmentVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.RecruitmentImportFailureVO;
import com.ruoyi.info.collection.service.ICcdiStaffRecruitmentImportService;
import com.ruoyi.info.collection.service.ICcdiStaffRecruitmentService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 员工招聘信息Controller
 *
 * @author ruoyi
 * @date 2025-02-05
 */
@Tag(name = "员工招聘信息管理")
@RestController
@RequestMapping("/ccdi/staffRecruitment")
public class CcdiStaffRecruitmentController extends BaseController {

    @Resource
    private ICcdiStaffRecruitmentService recruitmentService;

    @Resource
    private ICcdiStaffRecruitmentImportService recruitmentImportService;

    /**
     * 查询招聘信息列表
     */
    @Operation(summary = "查询招聘信息列表")
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiStaffRecruitmentQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiStaffRecruitmentVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiStaffRecruitmentVO> result = recruitmentService.selectRecruitmentPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 获取招聘信息详细信息
     */
    @Operation(summary = "获取招聘信息详细信息")
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(recruitmentService.selectRecruitmentById(id));
    }

    /**
     * 新增招聘信息
     */
    @Operation(summary = "新增招聘信息")
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:add')")
    @Log(title = "员工招聘信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiStaffRecruitmentAddDTO addDTO) {
        return toAjax(recruitmentService.insertRecruitment(addDTO));
    }

    /**
     * 修改招聘信息
     */
    @Operation(summary = "修改招聘信息")
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:edit')")
    @Log(title = "员工招聘信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiStaffRecruitmentEditDTO editDTO) {
        return toAjax(recruitmentService.updateRecruitment(editDTO));
    }

    /**
     * 删除招聘信息
     */
    @Operation(summary = "删除招聘信息")
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:remove')")
    @Log(title = "员工招聘信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(recruitmentService.deleteRecruitmentByIds(ids));
    }

    /**
     * 下载带字典下拉框的导入模板
     * 使用@DictDropdown注解自动添加下拉框
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(
            response,
            CcdiStaffRecruitmentExcel.class,
            "招聘信息",
            CcdiStaffRecruitmentWorkExcel.class,
            "历史工作经历",
            "招聘信息管理导入模板"
        );
    }

    /**
     * 异步导入招聘信息
     */
    @Operation(summary = "异步导入招聘信息")
    @Parameter(name = "file", description = "导入文件", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:import')")
    @Log(title = "员工招聘信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@Parameter(description = "导入文件") MultipartFile file) throws Exception {
        List<CcdiStaffRecruitmentExcel> recruitmentList = EasyExcelUtil.importExcel(
            file.getInputStream(),
            CcdiStaffRecruitmentExcel.class,
            "招聘信息"
        );
        List<CcdiStaffRecruitmentWorkExcel> workList = EasyExcelUtil.importExcel(
            file.getInputStream(),
            CcdiStaffRecruitmentWorkExcel.class,
            "历史工作经历"
        );

        boolean hasRecruitmentRows = recruitmentList != null && !recruitmentList.isEmpty();
        boolean hasWorkRows = workList != null && !workList.isEmpty();
        if (!hasRecruitmentRows && !hasWorkRows) {
            return error("至少需要一条数据");
        }

        String taskId = recruitmentService.importRecruitment(recruitmentList, workList);

        ImportResultVO result = new ImportResultVO();
        result.setTaskId(taskId);
        result.setStatus("PROCESSING");
        result.setMessage("导入任务已提交,正在后台处理");

        return AjaxResult.success("导入任务已提交,正在后台处理", result);
    }

    /**
     * 查询导入状态
     */
    @Operation(summary = "查询导入状态")
    @Parameter(name = "taskId", description = "任务ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO statusVO = recruitmentImportService.getImportStatus(taskId);
        return success(statusVO);
    }

    /**
     * 查询导入失败记录
     */
    @Operation(summary = "查询导入失败记录")
    @Parameter(name = "taskId", description = "任务ID", required = true)
    @Parameter(name = "pageNum", description = "页码", required = false)
    @Parameter(name = "pageSize", description = "每页条数", required = false)
    @PreAuthorize("@ss.hasPermi('ccdi:staffRecruitment:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        List<RecruitmentImportFailureVO> failures = recruitmentImportService.getImportFailures(taskId);

        // 手动分页
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, failures.size());

        // 检查 fromIndex 是否超出范围
        if (fromIndex >= failures.size()) {
            return getDataTable(new ArrayList<>(), failures.size());
        }

        List<RecruitmentImportFailureVO> pageData = failures.subList(fromIndex, toIndex);

        return getDataTable(pageData, failures.size());
    }
}
