package com.gxwebsoft.credit.controller;

import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.credit.entity.CreditCompany;
import com.gxwebsoft.credit.entity.CreditSupplier;
import com.gxwebsoft.credit.param.CreditSupplierImportParam;
import com.gxwebsoft.credit.param.CreditSupplierParam;
import com.gxwebsoft.credit.service.CreditCompanyService;
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
import com.gxwebsoft.credit.service.CreditSupplierService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 供应商控制器
 *
 * @author 科技小王子
 * @since 2025-12-19 19:51:47
 */
@Tag(name = "供应商管理")
@RestController
@RequestMapping("/api/credit/credit-supplier")
public class CreditSupplierController extends BaseController {
    @Resource
    private CreditSupplierService creditSupplierService;

    @Resource
    private BatchImportSupport batchImportSupport;

    @Resource
    private CreditCompanyService creditCompanyService;

    @Resource
    private CreditCompanyRecordCountService creditCompanyRecordCountService;

    @Operation(summary = "分页查询供应商")
    @GetMapping("/page")
    public ApiResult<PageResult<CreditSupplier>> page(CreditSupplierParam param) {
        // 使用关联查询
        return success(creditSupplierService.pageRel(param));
    }

    @Operation(summary = "查询全部供应商")
    @GetMapping()
    public ApiResult<List<CreditSupplier>> list(CreditSupplierParam param) {
        // 使用关联查询
        return success(creditSupplierService.listRel(param));
    }

    @Operation(summary = "根据id查询供应商")
    @GetMapping("/{id}")
    public ApiResult<CreditSupplier> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(creditSupplierService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:save')")
    @OperationLog
    @Operation(summary = "添加供应商")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CreditSupplier creditSupplier) {
        // 记录当前登录用户id
        // User loginUser = getLoginUser();
        // if (loginUser != null) {
        // creditSupplier.setUserId(loginUser.getUserId());
        // }
        if (creditSupplierService.save(creditSupplier)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:update')")
    @OperationLog
    @Operation(summary = "修改供应商")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CreditSupplier creditSupplier) {
        if (creditSupplierService.updateById(creditSupplier)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:remove')")
    @OperationLog
    @Operation(summary = "删除供应商")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (batchImportSupport.hardRemoveById(CreditSupplier.class, id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:save')")
    @OperationLog
    @Operation(summary = "批量添加供应商")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<CreditSupplier> list) {
        if (creditSupplierService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:update')")
    @OperationLog
    @Operation(summary = "批量修改供应商")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CreditSupplier> batchParam) {
        if (batchParam.update(creditSupplierService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('credit:creditSupplier:remove')")
    @OperationLog
    @Operation(summary = "批量删除供应商")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (batchImportSupport.hardRemoveByIds(CreditSupplier.class, ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    /**
     * 根据企业名称匹配企业并更新 companyId（匹配 CreditCompany.name / CreditCompany.matchName）
     *
     * <p>默认仅更新 companyId=0 的记录；如需覆盖更新，传 onlyNull=false。</p>
     */
    @PreAuthorize("hasAuthority('credit:creditSupplier:update')")
    @OperationLog
    @Operation(summary = "根据企业名称匹配并更新companyId")
    @PostMapping("/company-id/refresh")
    public ApiResult<Map<String, Object>> refreshCompanyIdByCompanyName(
        @RequestParam(value = "onlyNull", required = false, defaultValue = "true") Boolean onlyNull,
        @RequestParam(value = "limit", required = false) Integer limit
    ) {
        User loginUser = getLoginUser();
        Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;

        BatchImportSupport.CompanyIdRefreshStats stats = batchImportSupport.refreshCompanyIdByCompanyName(
            creditSupplierService,
            creditCompanyService,
            currentTenantId,
            onlyNull,
            limit,
            CreditSupplier::getId,
            CreditSupplier::setId,
            CreditSupplier::getSupplier,
            CreditSupplier::getCompanyId,
            CreditSupplier::setCompanyId,
            CreditSupplier::setCompanyName,
            CreditSupplier::getHasData,
            CreditSupplier::setHasData,
            CreditSupplier::getTenantId,
            CreditSupplier::new
        );

        if (!stats.anyDataRead) {
            return success("无可更新数据", stats.toMap());
        }
        return success("更新完成，更新" + stats.updated + "条", stats.toMap());
    }

    /**
     * 批量导入供应商
     */
    @PreAuthorize("hasAuthority('credit:creditSupplier:save')")
    @Operation(summary = "批量导入供应商")
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(@RequestParam("file") MultipartFile file,
                                               @RequestParam(value = "companyId", required = false) Integer companyId) {
        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;
        Set<Integer> touchedCompanyIds = new HashSet<>();

        try {
            int sheetIndex = ExcelImportSupport.findSheetIndex(file, "供应商", 3);
            ExcelImportSupport.ImportResult<CreditSupplierImportParam> importResult = ExcelImportSupport.read(
                file, CreditSupplierImportParam.class, this::isEmptyImportRow, sheetIndex);
            List<CreditSupplierImportParam> list = importResult.getData();
            int usedTitleRows = importResult.getTitleRows();
            int usedHeadRows = importResult.getHeadRows();
            int usedSheetIndex = importResult.getSheetIndex();

            if (CollectionUtils.isEmpty(list)) {
                return fail("未读取到数据，请确认模板表头与示例格式一致", null);
            }

            User loginUser = getLoginUser();
            Integer currentUserId = loginUser != null ? loginUser.getUserId() : null;
            Integer currentTenantId = loginUser != null ? loginUser.getTenantId() : null;
            Map<String, String> urlBySupplier = ExcelImportSupport.readUrlByKey(file, usedSheetIndex, usedTitleRows, usedHeadRows, "供应商");
            String fixedCompanyName = null;
            if (companyId != null && companyId > 0) {
                CreditCompany fixedCompany = creditCompanyService.getById(companyId);
                fixedCompanyName = fixedCompany != null ? fixedCompany.getName() : null;
            }

            final int chunkSize = 500;
            final int mpBatchSize = 500;
            List<CreditSupplier> chunkItems = new ArrayList<>(chunkSize);
            List<Integer> chunkRowNumbers = new ArrayList<>(chunkSize);

            for (int i = 0; i < list.size(); i++) {
                CreditSupplierImportParam param = list.get(i);
                try {
                    CreditSupplier item = convertImportParamToEntity(param);
                    if (!ImportHelper.isBlank(item.getSupplier())) {
                        String link = urlBySupplier.get(item.getSupplier().trim());
                        if (!ImportHelper.isBlank(link)) {
                            item.setUrl(link.trim());
                        }
                    }

                    if (item.getCompanyId() == null && companyId != null) {
                        item.setCompanyId(companyId);
                        if (ImportHelper.isBlank(item.getCompanyName()) && !ImportHelper.isBlank(fixedCompanyName)) {
                            item.setCompanyName(fixedCompanyName);
                        }
                    }
                    if (item.getUserId() == null && currentUserId != null) {
                        item.setUserId(currentUserId);
                    }
                    if (item.getTenantId() == null && currentTenantId != null) {
                        item.setTenantId(currentTenantId);
                    }
                    if (item.getStatus() == null) {
                        item.setStatus(0);
                    }
                    if (item.getRecommend() == null) {
                        item.setRecommend(0);
                    }
                    if (item.getDeleted() == null) {
                        item.setDeleted(0);
                    }

                    int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
                    if (ImportHelper.isBlank(item.getSupplier())) {
                        errorMessages.add("第" + excelRowNumber + "行：供应商不能为空");
                        continue;
                    }

                    if (item.getCompanyId() != null && item.getCompanyId() > 0) {
                        touchedCompanyIds.add(item.getCompanyId());
                    }

                    chunkItems.add(item);
                    chunkRowNumbers.add(excelRowNumber);
                    if (chunkItems.size() >= chunkSize) {
                        successCount += batchImportSupport.persistInsertOnlyChunk(
                            creditSupplierService,
                            chunkItems,
                            chunkRowNumbers,
                            mpBatchSize,
                            CreditSupplier::getSupplier,
                            "",
                            errorMessages
                        );
                        chunkItems.clear();
                        chunkRowNumbers.clear();
                    }
                } catch (Exception e) {
                    int excelRowNumber = i + 1 + usedTitleRows + usedHeadRows;
                    errorMessages.add("第" + excelRowNumber + "行：" + e.getMessage());
                    e.printStackTrace();
                }
            }

            if (!chunkItems.isEmpty()) {
                successCount += batchImportSupport.persistInsertOnlyChunk(
                    creditSupplierService,
                    chunkItems,
                    chunkRowNumbers,
                    mpBatchSize,
                    CreditSupplier::getSupplier,
                    "",
                    errorMessages
                );
            }

            creditCompanyRecordCountService.refresh(CreditCompanyRecordCountService.CountType.SUPPLIER, touchedCompanyIds);

            if (errorMessages.isEmpty()) {
                return success("成功导入" + successCount + "条数据", null);
            } else {
                return success("导入完成，成功" + successCount + "条，失败" + errorMessages.size() + "条", errorMessages);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail("导入失败：" + e.getMessage(), null);
        }
    }

    /**
     * 下载供应商导入模板
     */
    @Operation(summary = "下载供应商导入模板")
    @GetMapping("/import/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<CreditSupplierImportParam> templateList = new ArrayList<>();

        CreditSupplierImportParam example = new CreditSupplierImportParam();
        example.setSupplier("示例供应商");
        example.setStatusTxt("合作中");
        example.setPurchaseAmount("120");
        example.setPublicDate("2024-02-01");
        example.setDataSource("公开渠道");
        example.setComments("备注信息");
        templateList.add(example);

        Workbook workbook = ExcelImportSupport.buildTemplate("供应商导入模板", "供应商", CreditSupplierImportParam.class, templateList);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=credit_supplier_import_template.xlsx");

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    private boolean isEmptyImportRow(CreditSupplierImportParam param) {
        if (param == null) {
            return true;
        }
        return ImportHelper.isBlank(param.getSupplier())
            && ImportHelper.isBlank(param.getStatusTxt())
            && ImportHelper.isBlank(param.getPurchaseAmount());
    }

    private CreditSupplier convertImportParamToEntity(CreditSupplierImportParam param) {
        CreditSupplier entity = new CreditSupplier();

        entity.setSupplier(param.getSupplier());
        entity.setStatusTxt(param.getStatusTxt());
        entity.setPurchaseAmount(param.getPurchaseAmount());
        entity.setPublicDate(param.getPublicDate());
        entity.setDataSource(param.getDataSource());
        entity.setComments(param.getComments());

        return entity;
    }

}
