package com.yd.oss.api.service.impl;

import com.aliyun.oss.OSS;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.oss.api.service.ApiExcelService;
import com.yd.oss.feign.request.ApiOssExcelParseRequest;
import com.yd.oss.feign.request.ApiOssExportAppointmentExcelRequest;
import com.yd.oss.feign.request.MultiSheetExportRequest;
import com.yd.oss.feign.response.ApiOssExcelParseResponse;
import com.yd.oss.feign.response.ApiOssExportAppointmentExcelResponse;
import com.yd.oss.feign.dto.ExportParam;
import com.yd.oss.feign.dto.ExportResult;
import com.yd.oss.feign.result.ImportResult;
import com.yd.oss.service.config.OssClientFactory;
import com.yd.oss.service.model.OssProvider;
import com.yd.oss.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApiExcelServiceImpl implements ApiExcelService {

    @Autowired
    private AppointmentExcelService appointmentExcelService;

    @Autowired
    private ExcelParserService excelParserService;

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private OssClientFactory ossClientFactory;

    @Autowired
    private IOssProviderService ossProviderService;

    /**
     * 导出excel-预约信息
     * @param request
     * @return
     */
    @Override
    public Result<ApiOssExportAppointmentExcelResponse> exportAppointment(ApiOssExportAppointmentExcelRequest request) {
        ApiOssExportAppointmentExcelResponse response = new ApiOssExportAppointmentExcelResponse();
        // 根据项目ID获取服务商信息
        OssProvider provider = ossProviderService.getProviderByProjectId(request.getProjectBizId());
        if (provider == null) {
            throw new BusinessException("未找到项目对应的OSS提供商，projectBizId=" + request.getProjectBizId());
        }
        OSS ossClient = null;
        try {
            ossClient = ossClientFactory.createOssClient(provider);
            String url = appointmentExcelService.exportAppointment(request.getData(),
                    request.getTemplateType(),
                    request.getAppointmentBizId(),
                    ossClient,provider);
            response.setUrl(url);
            return Result.success(response);
        }catch (Exception e) {
            log.error("导出excel-预约信息异常：{}",e.getMessage());
            throw new BusinessException("导出excel-预约信息异常");
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 通用-Excel解析（支持多sheet页解析）
     * @param file
     * @param sheetClassNames
     * @return
     */
    @Override
    public Result<ApiOssExcelParseResponse> parse(MultipartFile file,
                                                  String sheetClassNames) {
        ApiOssExcelParseResponse response = new ApiOssExcelParseResponse();
        try {
            String[] strings = sheetClassNames.split(",");
            // 将类名字符串转换为Class对象
            Class<?>[] sheetClasses = new Class<?>[strings.length];
            for (int i = 0; i < strings.length; i++) {
                sheetClasses[i] = Class.forName(strings[i]);
            }

            // 解析Excel
            Map<Integer, Object> result = excelParserService.parseExcelWithMultipleSheets(file, sheetClasses);
            response.setMap(result);
            return Result.success(response);
        } catch (Exception e) {
            log.info("Excel解析异常:{}",e.getMessage());
            throw new BusinessException("Excel解析异常！");
        }
    }

    /**
     * 通用-Excel导出参数（如果传dataList附加数据，不传单纯导出表头参数）
     * @param dataList
     * @param exportParam
     * @param entityClass
     * @return
     */
    @Override
    public Result<ExportResult> export(List<?> dataList, ExportParam exportParam, Class<?> entityClass) {
        ExportResult exportResult = excelExportService.exportAndUploadToOss(dataList,exportParam,entityClass);
        return Result.success(exportResult);
    }

    /**
     * 通用-多Sheet Excel导出
     * @param request
     * @return
     */
    @Override
    public Result<ExportResult> exportMultiSheet(MultiSheetExportRequest request) {
        ExportResult exportResult = excelExportService.exportMultiSheetAndUploadToOss(request);
        return Result.success(exportResult);
    }

    /**
     * 通用Excel导入接口
     * @param file Excel文件
     * @param headerRow 表头行号（默认第1行，从0开始）
     * @param dataStartRow 数据开始行号（默认第2行，从0开始）
     * @param requiredFields 必填字段列表（多个字段逗号分隔）
     * @return 导入的结果
     */
    @Override
    public Result<ImportResult> importExcel(MultipartFile file, Integer headerRow,
                                            Integer dataStartRow, String requiredFields,Integer checkStartRow) {
        List<String> requiredFieldList = null;
        if (requiredFields != null && !requiredFields.isEmpty()) {
            requiredFieldList = Arrays.asList(requiredFields.split(","));
        }

        ImportResult importResult = excelImportService.genericImport(file, headerRow, dataStartRow, requiredFieldList,checkStartRow);
        return Result.success(importResult);
    }

    /**
     * 简化导入接口
     * @param file
     * @return
     */
    @Override
    public Result<ImportResult> simpleImport(MultipartFile file) {
        ImportResult importResult = excelImportService.simpleImport(file);
        return Result.success(importResult);
    }

}
