/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.codvision.base.config.excel.AbstractExportClass;
import com.codvision.base.entity.ExcelErrorRecord;
import com.codvision.base.entity.vo.ExcelErrorRecordVO;
import com.codvision.base.mapper.ExcelErrorRecordMapper;
import com.codvision.base.service.IExcelErrorRecordService;
import com.codvision.webcore.bean.QueryPage;
import com.codvision.webcore.service.impl.BaseServiceImpl;
import com.google.common.base.Preconditions;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * excel错误记录 服务实现类
 *
 * @author lingee
 * @date 2023/11/16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ExcelErrorRecordServiceImpl extends BaseServiceImpl<ExcelErrorRecordMapper, ExcelErrorRecord, ExcelErrorRecordVO>
        implements IExcelErrorRecordService {

    @Override
    @SneakyThrows
    public void excelExport(String reqNo) {
        ExcelErrorRecord errorRecord = this.getOne(Wrappers.<ExcelErrorRecord>lambdaQuery().eq(ExcelErrorRecord::getReqNo, reqNo).last("limit 1"));
        Preconditions.checkArgument(errorRecord != null,30001);

        Class<?> clazz = Class.forName(errorRecord.getTargetObject());
        new AbstractExportClass() {
            @Override
            protected List getList(QueryPage queryPage, Object queryBean) {
                List dataList = new ArrayList<>();

                List<ExcelErrorRecord> errorRecords = list(Wrappers.<ExcelErrorRecord>lambdaQuery().eq(ExcelErrorRecord::getReqNo, reqNo));
                if (CollectionUtils.isNotEmpty(errorRecords)) {
                    for (ExcelErrorRecord errorRecord : errorRecords) {
                        Object o = JSONUtil.toBean(errorRecord.getOriginalJsonValue(), clazz);
                        BeanUtil.copyProperties(errorRecord, o);
                        dataList.add(o);
                    }
                }
                return dataList;
            }
        }.excelUser("异常数据信息表", null, clazz);
    }
}
