package com.engine.organization.service.impl;

import com.engine.core.impl.Service;
import com.engine.organization.entity.hrmresource.param.HrmResourceImportParam;
import com.engine.organization.service.HrmResourceImportAdaptService;
import com.engine.organization.service.HrmResourceImportProcessService;
import com.engine.organization.service.ImportCommonService;
import weaver.file.FileUploadToPath;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:dxfeng
 * @createTime: 2022/06/29
 * @version: 1.0
 */
public class ImportCommonServiceImpl extends Service implements ImportCommonService {

    @Override
    public Map<String, Object> saveImportResource(Map<String, Object> params, HttpServletRequest request) {

        Map<String, Object> retmap = new HashMap<String, Object>();
        try {
            /*综合考虑多数据源后，实现通过配置文件配置适配器和解析类*/
            List<Object> lsErrorInfo = new ArrayList<Object>();

            HrmResourceImportAdaptService importAdapt = (HrmResourceImportAdaptService) Class.forName("com.engine.organization.service.impl.HrmResourceImportAdaptServiceImpl").newInstance();

            FileUploadToPath fu = new FileUploadToPath(request);

            int language = this.user.getLanguage();
            importAdapt.setUserlanguage(language);
            List errorInfo = importAdapt.creatImportMap(fu);

            //如果读取数据和验证模板没有发生错误
            if (errorInfo.isEmpty()) {
                Map<String, HrmResourceImportParam> hrMap = importAdapt.getHrmImportMap();
                HrmResourceImportProcessService importProcess = (HrmResourceImportProcessService) Class.forName("com.engine.organization.service.impl.HrmResourceImportProcessServiceImpl").newInstance();
                importProcess.init(request);
                importProcess.processMap(hrMap);
            } else {
                if (errorInfo != null && !errorInfo.isEmpty()) {
                    Map<String, Object> error;
                    for (int i = 0; i < errorInfo.size(); i++) {
                        error = new HashMap<>();
                        error.put("message", Util.null2String(errorInfo.get(i)));
                        lsErrorInfo.add(error);
                    }
                }
            }
            retmap.put("errorInfo", lsErrorInfo);
            retmap.put("status", "1");
        } catch (Exception e) {
            retmap.put("status", "-1");
            retmap.put("message", e.getMessage());
        }
        return retmap;
    }
}
