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

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.ApiOssExportAppointmentExcelRequest;
import com.yd.oss.feign.response.ApiOssExcelParseResponse;
import com.yd.oss.feign.response.ApiOssExportAppointmentExcelResponse;
import com.yd.oss.service.service.AppointmentExcelService;
import com.yd.oss.service.service.ExcelParserService;
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.Map;

@Slf4j
@Service
public class ApiExcelServiceImpl implements ApiExcelService {

    @Autowired
    private AppointmentExcelService appointmentExcelService;

    @Autowired
    private ExcelParserService excelParserService;

    /**
     * 导出excel-预约信息
     * @param request
     * @return
     */
    @Override
    public Result<ApiOssExportAppointmentExcelResponse> exportAppointment(ApiOssExportAppointmentExcelRequest request) {
        ApiOssExportAppointmentExcelResponse response = new ApiOssExportAppointmentExcelResponse();
        String url = appointmentExcelService.exportAppointment(request.getData(),
                request.getTemplateType(),
                request.getAppointmentBizId());
        response.setUrl(url);
        return Result.success(response);
    }

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

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

}
