package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.service.SalaryAcctRecordService;
import com.engine.salary.service.impl.SalaryAcctRecordServiceImpl;
import com.engine.salary.util.SalaryI18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: sy
 * @Description: 通过薪资核算id归档台账记录
 * @Date: 2023/7/18
 **/
@Slf4j
public class SalaryAcctFileByIdAction implements Action {
    private SalaryAcctRecordService getSalaryAcctRecordService(User user) {
        return ServiceUtil.getService(SalaryAcctRecordServiceImpl.class, user);
    }

    private String acctRecordId;

    public String getAcctRecordId() {
        return acctRecordId;
    }

    public void setAcctRecordId(String acctRecordId) {
        this.acctRecordId = acctRecordId;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        User user = requestInfo.getRequestManager().getUser();

        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        Map<String, String> fieldMap = Arrays.stream(properties).collect(Collectors.toMap(Property::getName,
                property -> Util.null2String(property.getValue())));

        Long salaryAcctId = StringUtils.isNotBlank(fieldMap.get(acctRecordId)) ? Long.parseLong(fieldMap.get(acctRecordId)) : 0L;

        if (!salaryAcctId.equals(0L)) {
            try {
                getSalaryAcctRecordService(user).file(salaryAcctId);
            } catch (Exception e) {
                log.error("薪资核算归档异常", e);
                requestInfo.getRequestManager().setMessage(e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        } else {
            requestInfo.getRequestManager().setMessage(SalaryI18nUtil.getI18nLabel(542300, "薪资核算记录不存在或已被删除"));
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
