package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiStaffTransferAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffTransferEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffTransferQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiStaffTransferExcel;
import com.ruoyi.info.collection.domain.vo.CcdiStaffTransferVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.StaffTransferImportFailureVO;
import com.ruoyi.info.collection.service.ICcdiStaffTransferImportService;
import com.ruoyi.info.collection.service.ICcdiStaffTransferService;
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 2026-02-10
 */
@Tag(name = "员工调动记录管理")
@RestController
@RequestMapping("/ccdi/staffTransfer")
public class CcdiStaffTransferController extends BaseController {

    @Resource
    private ICcdiStaffTransferService transferService;

    @Resource
    private ICcdiStaffTransferImportService transferImportService;

    /**
     * 查询员工调动记录列表
     */
    @Operation(summary = "查询员工调动记录列表")
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiStaffTransferQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiStaffTransferVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiStaffTransferVO> result = transferService.selectTransferPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 获取员工调动记录详细信息
     */
    @Operation(summary = "获取员工调动记录详细信息")
    @Parameter(name = "id", description = "主键ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(transferService.selectTransferById(id));
    }

    /**
     * 新增员工调动记录
     */
    @Operation(summary = "新增员工调动记录")
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:add')")
    @Log(title = "员工调动记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiStaffTransferAddDTO addDTO) {
        return toAjax(transferService.insertTransfer(addDTO));
    }

    /**
     * 修改员工调动记录
     */
    @Operation(summary = "修改员工调动记录")
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:edit')")
    @Log(title = "员工调动记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiStaffTransferEditDTO editDTO) {
        return toAjax(transferService.updateTransfer(editDTO));
    }

    /**
     * 删除员工调动记录
     */
    @Operation(summary = "删除员工调动记录")
    @Parameter(name = "ids", description = "主键ID数组", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:remove')")
    @Log(title = "员工调动记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(transferService.deleteTransferByIds(ids));
    }

    /**
     * 下载带字典下拉框的导入模板
     * 使用@DictDropdown注解自动添加下拉框
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiStaffTransferExcel.class, "员工调动记录信息");
    }

    /**
     * 异步导入员工调动记录
     */
    @Operation(summary = "异步导入员工调动记录")
    @Parameter(name = "file", description = "导入文件", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffTransfer:import')")
    @Log(title = "员工调动记录", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@Parameter(description = "导入文件") MultipartFile file) throws Exception {
        List<CcdiStaffTransferExcel> list = EasyExcelUtil.importExcel(file.getInputStream(), CcdiStaffTransferExcel.class);

        if (list == null || list.isEmpty()) {
            return error("至少需要一条数据");
        }

        // 提交异步任务
        String taskId = transferService.importTransfer(list);

        // 立即返回,不等待后台任务完成
        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:staffTransfer:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO statusVO = transferImportService.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:staffTransfer:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        List<StaffTransferImportFailureVO> failures = transferImportService.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<StaffTransferImportFailureVO> pageData = failures.subList(fromIndex, toIndex);

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