package com.chinaweal.aiccs.crgs.transfor.service.impl;

import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.transfor.entity.OtUploadBatchLog;
import com.chinaweal.aiccs.crgs.transfor.mapper.OtUploadBatchLogMapper;
import com.chinaweal.aiccs.crgs.transfor.service.OtUploadBatchLogService;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 上传批次记录 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-11-02
 */
@Slf4j
@Service
public class OtUploadBatchLogServiceImpl extends BaseServiceImpl<OtUploadBatchLogMapper, OtUploadBatchLog> implements OtUploadBatchLogService {

    @Override
    public List<Map<String, String>> readTempData(File file) throws IOException {
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(file);
        HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
        HSSFSheet sheet = workbook.getSheetAt(1);
        List<String> keyList = new ArrayList<>();
        HSSFRow headerRow = sheet.getRow(1);
        // 表头读取
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            Cell cell = headerRow.getCell(i);
            String key = cell.toString();
            keyList.add(key == null ? null : key.toLowerCase().replace("_", StringUtils.EMPTY));
        }
        // 数据读取
        int lastRows = sheet.getPhysicalNumberOfRows();
        List<Map<String, String>> result = new ArrayList<>();
        for (int i = 2; i < lastRows; i++) {
            Row curRow = sheet.getRow(i);
            Map<String, String> atomData = new HashMap<>();
            int count = 0;
            for (int j = 0; j < curRow.getLastCellNum() && j < keyList.size(); j++) {
                Cell cell = curRow.getCell(j);
                if (cell != null) {
                    String value = cell.toString();
                    if (StringUtils.isNotBlank(value)) {
                        count++;
                    }
                    atomData.put(keyList.get(j), value);
                }
            }
            if (count > 0) {
                result.add(atomData);
            }
        }
        poifsFileSystem.close();
        return result;
    }

    @Override
    public <T> List<T> transferResult2Bean(List<Map<String, String>> resultList, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        // 获取类的setter
        Map<String, Method> setterMap = new HashMap<>();
        for (Field field : fields) {
            String name = field.getName();
            try {
                Method setter = clazz.getDeclaredMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), String.class);
                setterMap.put(name.toLowerCase(), setter);
            } catch (NoSuchMethodException e) {
                log.error("获取getter失败，字段：{}", name);
            }
        }
        // 结果转换类
        for (Map<String, String> each : resultList) {
            T atom;
            try {
                atom = clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("创建类失败", e);
                return result;
            }
            for (Map.Entry<String, String> entry : each.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Method setter = setterMap.get(key);
                try {
                    setter.invoke(atom, value);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    log.error("setter赋值失败，字段：{}", key, e);
                }
            }
            result.add(atom);
        }
        return result;
    }
}
