package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiBaseStaffAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiBaseStaffEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiBaseStaffQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiBaseStaffAssetInfoExcel;
import com.ruoyi.info.collection.domain.excel.CcdiBaseStaffExcel;
import com.ruoyi.info.collection.domain.vo.*;
import com.ruoyi.info.collection.service.ICcdiBaseStaffImportService;
import com.ruoyi.info.collection.service.ICcdiBaseStaffService;
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.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-01-28
 */
@Tag(name = "员工信息管理")
@RestController
@RequestMapping("/ccdi/baseStaff")
public class CcdiBaseStaffController extends BaseController {

    @Resource
    private ICcdiBaseStaffService baseStaffService;

    @Resource
    private ICcdiBaseStaffImportService importAsyncService;

    /**
     * 查询员工列表
     */
    @Operation(summary = "查询员工列表")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiBaseStaffQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiBaseStaffVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiBaseStaffVO> result = baseStaffService.selectBaseStaffPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 查询员工下拉列表
     */
    @Operation(summary = "查询员工下拉列表")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:list')")
    @GetMapping("/options")
    public AjaxResult getStaffOptions(@RequestParam(required = false) String query) {
        List<CcdiBaseStaffOptionVO> list = baseStaffService.selectStaffOptions(query);
        return success(list);
    }

    /**
     * 获取员工详细信息
     */
    @Operation(summary = "获取员工详细信息")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:query')")
    @GetMapping(value = "/{staffId}")
    public AjaxResult getInfo(@PathVariable Long staffId) {
        return success(baseStaffService.selectBaseStaffById(staffId));
    }

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

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

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

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

    /**
     * 导入员工信息(异步)
     */
    @Operation(summary = "导入员工信息")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:import')")
    @Log(title = "员工信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        List<CcdiBaseStaffExcel> staffList = EasyExcelUtil.importExcel(
                file.getInputStream(),
                CcdiBaseStaffExcel.class,
                "员工信息"
        );
        List<CcdiBaseStaffAssetInfoExcel> assetList = EasyExcelUtil.importExcel(
                file.getInputStream(),
                CcdiBaseStaffAssetInfoExcel.class,
                "员工资产信息"
        );

        boolean hasStaffRows = staffList != null && !staffList.isEmpty();
        boolean hasAssetRows = assetList != null && !assetList.isEmpty();

        if (!hasStaffRows && !hasAssetRows) {
            return error("至少需要一条数据");
        }

        BaseStaffImportSubmitResultVO result = baseStaffService.importBaseStaffWithAssets(staffList, assetList);

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

    /**
     * 查询导入状态
     */
    @Operation(summary = "查询员工导入状态")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        try {
            ImportStatusVO status = importAsyncService.getImportStatus(taskId);
            return success(status);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询导入失败记录
     */
    @Operation(summary = "查询导入失败记录")
    @PreAuthorize("@ss.hasPermi('ccdi:baseStaff:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

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

}
