package com.boman.web.core.service.excel;

import com.alibaba.fastjson.JSONObject;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.FormDataDto;
import com.boman.web.core.service.TableServiceCmdService;
import com.boman.web.core.service.save.IBaseSaveService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.boman.common.core.utils.obj.ObjectUtils.*;

/**
 * @author shiqian
 * @date 2021年06月08日 09:42
 **/
@Service
public class ImportExportExcelServiceImpl implements IImportExportExcelService {

    @Resource
    private IBaseSaveService saveService;
    @Resource
    private TableServiceCmdService cmdService;


    /**
     * 功能描述: 批量导入数据
     *
     * @param tableName tableName
     * @param dataList  需要保存的数据
     * @return void
     */
    @Override
    public AjaxResult importCommonData(String tableName, List<JSONObject> dataList) {
        requireNonNull(tableName, "importCommonData tableName is empty");
        requireNonNull(dataList, "importCommonData dataList is empty");

        List<String> result = new ArrayList<>(dataList.size());
        FormDataDto dto = new FormDataDto();
        dto.setTable(tableName);
        dto.setObjId(-1L);
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject data = dataList.get(i);
            dto.setFixedData(data);
            AjaxResult ajaxResult;
            try {
                ajaxResult = cmdService.objectSave(dto);
            } catch (Exception e) {
                result.add("第" + i + "条导入失败, 失败原因为: " + e.getMessage());
                e.printStackTrace();
                continue;
            }

            if (AjaxResult.checkFail(ajaxResult)) {
                result.add("第" + i + "条导入失败, 数据为: " + data.toJSONString());
            }
        }

        return AjaxResult.success("成功", result);
    }


}
