package com.engine.salary.action;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.salaryacct.po.SalaryAcctRecordPO;
import com.engine.salary.mapper.taxagent.TaxAgentMapper;
import com.engine.salary.service.SalaryAcctRecordService;
import com.engine.salary.service.impl.SalaryAcctRecordServiceImpl;
import com.engine.salary.util.db.MapperProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.general.BaseBean;
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 Harryxzy
 * @ClassName FileSalaryAcctRecordAction
 * @date 2023/12/13 9:17
 * @description 薪资核算记录归档action
 */
@Slf4j
public class FileSalaryAcctRecordAction implements Action {


    private SalaryAcctRecordService getSalaryAcctRecordService(User user) {
        return ServiceUtil.getService(SalaryAcctRecordServiceImpl.class, user);
    }

    private TaxAgentMapper getTaxAgentMapper() {
        return MapperProxyFactory.getProxy(TaxAgentMapper.class);
    }


    private String recordIdFieldName;


    public String getRecordIdFieldName() {
        return recordIdFieldName;
    }

    public void setRecordIdFieldName(String recordIdFieldName) {
        this.recordIdFieldName = recordIdFieldName;
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        Map<String, String> fieldMap = Arrays.stream(properties).collect(Collectors.toMap(Property::getName,
                property -> Util.null2String(property.getValue())));
        String salaryAcctRecordId = fieldMap.get(recordIdFieldName);
        if (StringUtils.isBlank(salaryAcctRecordId)) {
            requestInfo.getRequestManager().setMessage("薪资核算记录不存在");
            return FAILURE_AND_CONTINUE;
        }
        User user = new User();
        user.setUid(1);
        Long acctRecordId = Long.valueOf(salaryAcctRecordId);
        SalaryAcctRecordPO salaryAcctRecordPO = getSalaryAcctRecordService(user).getById(acctRecordId);
        if (salaryAcctRecordPO == null) {
            requestInfo.getRequestManager().setMessage("薪资核算记录不存在,或已被删除");
            return FAILURE_AND_CONTINUE;
        }
        if (salaryAcctRecordPO.getStatus() > 1) {
            BaseBean baseBean = new BaseBean();
            baseBean.writeLog("核算记录归档action， 该核算记录已经归档：" + salaryAcctRecordPO.getId());
            return SUCCESS;
        }
        try {
            getSalaryAcctRecordService(user).file(acctRecordId);
        } catch (Exception e) {
            requestInfo.getRequestManager().setMessage(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
        return SUCCESS;
    }
}
