package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.info.collection.domain.dto.CcdiStaffFmyRelationAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffFmyRelationEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiStaffFmyRelationQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiAssetInfoExcel;
import com.ruoyi.info.collection.domain.excel.CcdiStaffFmyRelationExcel;
import com.ruoyi.info.collection.domain.vo.CcdiStaffFmyRelationVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.domain.vo.StaffFmyRelationImportFailureVO;
import com.ruoyi.info.collection.domain.vo.StaffFmyRelationImportSubmitResultVO;
import com.ruoyi.info.collection.service.ICcdiStaffFmyRelationImportService;
import com.ruoyi.info.collection.service.ICcdiStaffFmyRelationService;
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-09
 */
@Tag(name = "员工亲属关系管理")
@RestController
@RequestMapping("/ccdi/staffFmyRelation")
public class CcdiStaffFmyRelationController extends BaseController {

    @Resource
    private ICcdiStaffFmyRelationService relationService;

    @Resource
    private ICcdiStaffFmyRelationImportService relationImportService;

    /**
     * 查询员工亲属关系列表
     */
    @Operation(summary = "查询员工亲属关系列表")
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiStaffFmyRelationQueryDTO queryDTO) {
        // 使用MyBatis Plus分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiStaffFmyRelationVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiStaffFmyRelationVO> result = relationService.selectRelationPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    /**
     * 获取员工亲属关系详细信息
     */
    @Operation(summary = "获取员工亲属关系详细信息")
    @Parameter(name = "id", description = "主键ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(relationService.selectRelationById(id));
    }

    /**
     * 新增员工亲属关系
     */
    @Operation(summary = "新增员工亲属关系")
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:add')")
    @Log(title = "员工亲属关系", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiStaffFmyRelationAddDTO addDTO) {
        return toAjax(relationService.insertRelation(addDTO));
    }

    /**
     * 修改员工亲属关系
     */
    @Operation(summary = "修改员工亲属关系")
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:edit')")
    @Log(title = "员工亲属关系", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiStaffFmyRelationEditDTO editDTO) {
        return toAjax(relationService.updateRelation(editDTO));
    }

    /**
     * 删除员工亲属关系
     */
    @Operation(summary = "删除员工亲属关系")
    @Parameter(name = "ids", description = "主键ID数组", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:remove')")
    @Log(title = "员工亲属关系", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(relationService.deleteRelationByIds(ids));
    }

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

    /**
     * 异步导入员工亲属关系
     */
    @Operation(summary = "异步导入员工亲属关系")
    @Parameter(name = "file", description = "导入文件", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:import')")
    @Log(title = "员工亲属关系", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@Parameter(description = "导入文件") MultipartFile file) throws Exception {
        List<CcdiStaffFmyRelationExcel> relationList = EasyExcelUtil.importExcel(
                file.getInputStream(),
                CcdiStaffFmyRelationExcel.class,
                "员工亲属关系信息"
        );
        List<CcdiAssetInfoExcel> assetList = EasyExcelUtil.importExcel(
                file.getInputStream(),
                CcdiAssetInfoExcel.class,
                "亲属资产信息"
        );

        boolean hasRelationRows = relationList != null && !relationList.isEmpty();
        boolean hasAssetRows = assetList != null && !assetList.isEmpty();

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

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

    /**
     * 查询导入状态
     */
    @Operation(summary = "查询导入状态")
    @Parameter(name = "taskId", description = "任务ID", required = true)
    @PreAuthorize("@ss.hasPermi('ccdi:staffFmyRelation:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO statusVO = relationImportService.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:staffFmyRelation:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(
            @PathVariable String taskId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

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

}
