package com.engine.payroll.cmd.payroll;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.payroll.biz.SendMsg;
import com.engine.payroll.process.ImportProcess;
import com.engine.payroll.util.PayrollUtil;
import weaver.file.FileUploadToPath;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class DispatchCmd extends AbstractCommonCommand<Map<String, Object>> {
    private HttpServletRequest request;

    public DispatchCmd(Map<String, Object> params, User user, HttpServletRequest request) {
        this.user = user;
        this.params = params;
        this.request = request;
    }

    @Override
    public BizLogContext getLogContext() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String,Object> retmap = new HashMap<String,Object>();
        try {
            //必要的权限判断
            if(!HrmUserVarify.checkUserRightSystemadmin("Payroll:Manager", user)){
                retmap.put("status", "-1");
                retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
                return retmap;
            }

            //generate targetId
            String targetId = PayrollUtil.getInstance().getUnquieID();

            //read excel
            ImportProcess importProcess = new ImportProcess(user, targetId);

            FileUploadToPath fu = new FileUploadToPath(request);
            List errorInfo = importProcess.creatImportMap(fu);

            //如果读取数据和验证模板没有发生错误
            Set<String> userList = new HashSet<>();//构建消息接受人员列表
            Map<String, String> keys = new HashMap<>();
            if (errorInfo.isEmpty()) {
                importProcess.init(request);
                userList = importProcess.processMap();
                keys = importProcess.getKeys();
                importProcess.over(request);
                retmap.put("errorInfo", new ArrayList<>());
            }else{
                importProcess.deleteFile();
                retmap.put("errorInfo", errorInfo);
            }

            //doDispatchMsg
            SendMsg.getInstance().dispatch(request, user, targetId, userList, keys, fu);
            retmap.put("targetId", targetId);
            retmap.put("userCount", userList.size());
            retmap.put("status", "1");
        } catch (Exception e) {
            writeLog(e);
            retmap.put("status", "-1");
            retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
        }
        return retmap;
    }
}
