package com.ruoyi.info.collection.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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 com.ruoyi.info.collection.domain.dto.CcdiEnterpriseBaseInfoAddDTO;
import com.ruoyi.info.collection.domain.dto.CcdiEnterpriseBaseInfoEditDTO;
import com.ruoyi.info.collection.domain.dto.CcdiEnterpriseBaseInfoQueryDTO;
import com.ruoyi.info.collection.domain.excel.CcdiEnterpriseBaseInfoExcel;
import com.ruoyi.info.collection.domain.vo.CcdiEnterpriseBaseInfoVO;
import com.ruoyi.info.collection.domain.vo.EnterpriseBaseInfoImportFailureVO;
import com.ruoyi.info.collection.domain.vo.ImportResultVO;
import com.ruoyi.info.collection.domain.vo.ImportStatusVO;
import com.ruoyi.info.collection.service.ICcdiEnterpriseBaseInfoImportService;
import com.ruoyi.info.collection.service.ICcdiEnterpriseBaseInfoService;
import com.ruoyi.info.collection.utils.EasyExcelUtil;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 实体库管理 Controller
 *
 * @author ruoyi
 * @date 2026-04-17
 */
@Tag(name = "实体库管理")
@RestController
@RequestMapping("/ccdi/enterpriseBaseInfo")
public class CcdiEnterpriseBaseInfoController extends BaseController {

    @Resource
    private ICcdiEnterpriseBaseInfoService enterpriseBaseInfoService;

    @Resource
    private ICcdiEnterpriseBaseInfoImportService enterpriseBaseInfoImportService;

    @Operation(summary = "查询实体库列表")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(CcdiEnterpriseBaseInfoQueryDTO queryDTO) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<CcdiEnterpriseBaseInfoVO> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CcdiEnterpriseBaseInfoVO> result = enterpriseBaseInfoService.selectEnterpriseBaseInfoPage(page, queryDTO);
        return getDataTable(result.getRecords(), result.getTotal());
    }

    @Operation(summary = "获取实体库详细信息")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:query')")
    @GetMapping("/{socialCreditCode}")
    public AjaxResult getInfo(@PathVariable String socialCreditCode) {
        return success(enterpriseBaseInfoService.selectEnterpriseBaseInfoById(socialCreditCode));
    }

    @Operation(summary = "新增实体库信息")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:add')")
    @Log(title = "实体库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CcdiEnterpriseBaseInfoAddDTO addDTO) {
        return toAjax(enterpriseBaseInfoService.insertEnterpriseBaseInfo(addDTO));
    }

    @Operation(summary = "修改实体库信息")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:edit')")
    @Log(title = "实体库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CcdiEnterpriseBaseInfoEditDTO editDTO) {
        return toAjax(enterpriseBaseInfoService.updateEnterpriseBaseInfo(editDTO));
    }

    @Operation(summary = "删除实体库信息")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:remove')")
    @Log(title = "实体库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{socialCreditCodes}")
    public AjaxResult remove(@PathVariable String[] socialCreditCodes) {
        return toAjax(enterpriseBaseInfoService.deleteEnterpriseBaseInfoByIds(socialCreditCodes));
    }

    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        EasyExcelUtil.importTemplateWithDictDropdown(response, CcdiEnterpriseBaseInfoExcel.class, "实体库管理");
    }

    @Operation(summary = "导入实体库信息")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:import')")
    @Log(title = "实体库管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        List<CcdiEnterpriseBaseInfoExcel> list = EasyExcelUtil.importExcel(file.getInputStream(), CcdiEnterpriseBaseInfoExcel.class);
        if (list == null || list.isEmpty()) {
            return error("至少需要一条数据");
        }

        String taskId = enterpriseBaseInfoService.importEnterpriseBaseInfo(list);
        ImportResultVO result = new ImportResultVO();
        result.setTaskId(taskId);
        result.setStatus("PROCESSING");
        result.setMessage("导入任务已提交,正在后台处理");
        return AjaxResult.success("导入任务已提交,正在后台处理", result);
    }

    @Operation(summary = "查询导入状态")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:import')")
    @GetMapping("/importStatus/{taskId}")
    public AjaxResult getImportStatus(@PathVariable String taskId) {
        ImportStatusVO status = enterpriseBaseInfoImportService.getImportStatus(taskId);
        return success(status);
    }

    @Operation(summary = "查询导入失败记录")
    @PreAuthorize("@ss.hasPermi('ccdi:enterpriseBaseInfo:import')")
    @GetMapping("/importFailures/{taskId}")
    public TableDataInfo getImportFailures(@PathVariable String taskId,
                                           @RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        List<EnterpriseBaseInfoImportFailureVO> failures = enterpriseBaseInfoImportService.getImportFailures(taskId);
        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex >= failures.size()) {
            return getDataTable(new ArrayList<>(), failures.size());
        }
        int toIndex = Math.min(fromIndex + pageSize, failures.size());
        return getDataTable(failures.subList(fromIndex, toIndex), failures.size());
    }
}
